diff --git a/configure.in b/configure.in index d3a16604cca7..24f69c553c5e 100644 --- a/configure.in +++ b/configure.in @@ -133,7 +133,7 @@ LIBGNOME_VERSION=2.0 STARTUP_NOTIFICATION_VERSION=0.8 DBUS_VERSION=0.60 LCMS_VERSION=1.17 -SQLITE_VERSION=3.6.0 +SQLITE_VERSION=3.5.4 MSMANIFEST_TOOL= diff --git a/db/sqlite3/README.MOZILLA b/db/sqlite3/README.MOZILLA index d3b7cdb45d72..c958c94d8efa 100644 --- a/db/sqlite3/README.MOZILLA +++ b/db/sqlite3/README.MOZILLA @@ -1,6 +1,7 @@ -This is sqlite 3.6.0 +This is sqlite 3.5.4.2 --- Shawn Wilsher , 07/2008 + +-- Peter Weilbacher , 04/2008 See http://www.sqlite.org/ for more info. diff --git a/db/sqlite3/src/sqlite.def b/db/sqlite3/src/sqlite.def index 4b2b9f2fab54..0d065bbd60e9 100644 --- a/db/sqlite3/src/sqlite.def +++ b/db/sqlite3/src/sqlite.def @@ -111,7 +111,9 @@ EXPORTS sqlite3_mutex_alloc sqlite3_mutex_enter sqlite3_mutex_free + sqlite3_mutex_held sqlite3_mutex_leave + sqlite3_mutex_notheld sqlite3_mutex_try sqlite3_mprintf sqlite3_open diff --git a/db/sqlite3/src/sqlite3.c b/db/sqlite3/src/sqlite3.c index de3d6745971a..f55ebe077b18 100644 --- a/db/sqlite3/src/sqlite3.c +++ b/db/sqlite3/src/sqlite3.c @@ -1,6 +1,6 @@ /****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite -** version 3.6.0. By combining all the individual C code files into this +** version 3.5.4.2. By combining all the individual C code files into this ** single large file, the entire code can be compiled as a one translation ** unit. This allows many compilers to do optimizations that would not be ** possible if the files were compiled separately. Performance improvements @@ -11,15 +11,14 @@ ** programs, you need this file and the "sqlite3.h" header file that defines ** the programming interface to the SQLite library. (If you do not have ** the "sqlite3.h" header file at hand, you will find a copy in the first -** 6139 lines past this header comment.) Additional code files may be +** 3840 lines past this header comment.) Additional code files may be ** needed if you want a wrapper to interface SQLite with your choice of ** programming language. The code for the "sqlite3" command-line shell ** is also in a separate file. This file contains only code for the core ** SQLite library. ** -** This amalgamation was generated on 2008-07-16 14:52:32 UTC. +** This amalgamation was generated on 2008-04-11 06:58:05 UTC. */ -#define SQLITE_CORE 1 #define SQLITE_AMALGAMATION 1 #ifndef SQLITE_PRIVATE # define SQLITE_PRIVATE static @@ -41,19 +40,54 @@ ************************************************************************* ** Internal interface definitions for SQLite. ** -** @(#) $Id: sqliteInt.h,v 1.742 2008/07/12 14:52:20 drh Exp $ +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef _SQLITEINT_H_ #define _SQLITEINT_H_ /* -** Include the configuration header output by 'configure' if we're using the -** autoconf-based build +** The macro unlikely() is a hint that surrounds a boolean +** expression that is usually false. Macro likely() surrounds +** a boolean expression that is usually true. GCC is able to +** use these hints to generate better code, sometimes. */ -#ifdef _HAVE_SQLITE_CONFIG_H -#include "config.h" +#if defined(__GNUC__) +# define likely(X) __builtin_expect((X),1) +# define unlikely(X) __builtin_expect((X),0) +#else +# define likely(X) !!(X) +# define unlikely(X) !!(X) #endif + +/* +** These #defines should enable >2GB file support on Posix if the +** underlying operating system supports it. If the OS lacks +** large file support, or if the OS is windows, these should be no-ops. +** +** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any +** system #includes. Hence, this block of code must be the very first +** code in all source files. +** +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch +** on the compiler command line. This is necessary if you are compiling +** on a recent machine (ex: RedHat 7.2) but you want your code to work +** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2 +** without this option, LFS is enable. But LFS does not exist in the kernel +** in RedHat 6.0, so the code won't work. Hence, for maximum binary +** portability you should omit LFS. +** +** Similar is true for MacOS. LFS is only supported on MacOS 9 and later. +*/ +#ifndef SQLITE_DISABLE_LFS +# define _LARGE_FILE 1 +# ifndef _FILE_OFFSET_BITS +# define _FILE_OFFSET_BITS 64 +# endif +# define _LARGEFILE_SOURCE 1 +#endif + + /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/ /************** Begin file sqliteLimit.h *************************************/ /* @@ -70,7 +104,7 @@ ** ** This file defines various limits of what SQLite can process. ** -** @(#) $Id: sqliteLimit.h,v 1.8 2008/03/26 15:56:22 drh Exp $ +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* @@ -107,24 +141,18 @@ /* ** The maximum length of a single SQL statement in bytes. -** -** It used to be the case that setting this value to zero would -** turn the limit off. That is no longer true. It is not possible -** to turn this limit off. +** A value of zero means there is no limit. */ #ifndef SQLITE_MAX_SQL_LENGTH -# define SQLITE_MAX_SQL_LENGTH 1000000000 +# define SQLITE_MAX_SQL_LENGTH 0 #endif /* ** The maximum depth of an expression tree. This is limited to ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might ** want to place more severe limits on the complexity of an -** expression. -** -** A value of 0 used to mean that the limit was not enforced. -** But that is no longer true. The limit is now strictly enforced -** at all times. +** expression. A value of 0 (the default) means do not enforce +** any limitation on expression tree depth. */ #ifndef SQLITE_MAX_EXPR_DEPTH # define SQLITE_MAX_EXPR_DEPTH 1000 @@ -169,9 +197,11 @@ #endif /* -** The maximum number of attached databases. This must be between 0 -** and 30. The upper bound on 30 is because a 32-bit integer bitmap -** is used internally to track attached databases. +** The maximum number of attached databases. This must be at least 2 +** in order to support the main database file (0) and the file used to +** hold temporary tables (1). And it must be less than 32 because +** we use a bitmask of databases with a u32 in places (for example +** the Parse.cookieMask field). */ #ifndef SQLITE_MAX_ATTACHED # define SQLITE_MAX_ATTACHED 10 @@ -243,119 +273,46 @@ /************** End of sqliteLimit.h *****************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ -/* Disable nuisance warnings on Borland compilers */ -#if defined(__BORLANDC__) -#pragma warn -rch /* unreachable code */ -#pragma warn -ccc /* Condition is always true or false */ -#pragma warn -aus /* Assigned value is never used */ -#pragma warn -csu /* Comparing signed and unsigned */ -#pragma warn -spa /* Suspicous pointer arithmetic */ -#endif - -/* Needed for various definitions... */ -#define _GNU_SOURCE - /* -** Include standard header files as necessary +** For testing purposes, the various size limit constants are really +** variables that we can modify in the testfixture. */ -#ifdef HAVE_STDINT_H -#include -#endif -#ifdef HAVE_INTTYPES_H -#include -#endif +#ifdef SQLITE_TEST + #undef SQLITE_MAX_LENGTH + #undef SQLITE_MAX_COLUMN + #undef SQLITE_MAX_SQL_LENGTH + #undef SQLITE_MAX_EXPR_DEPTH + #undef SQLITE_MAX_COMPOUND_SELECT + #undef SQLITE_MAX_VDBE_OP + #undef SQLITE_MAX_FUNCTION_ARG + #undef SQLITE_MAX_VARIABLE_NUMBER + #undef SQLITE_MAX_PAGE_SIZE + #undef SQLITE_MAX_PAGE_COUNT + #undef SQLITE_MAX_LIKE_PATTERN_LENGTH -/* -** A macro used to aid in coverage testing. When doing coverage -** testing, the condition inside the argument must be evaluated -** both true and false in order to get full branch coverage. -** This macro can be inserted to ensure adequate test coverage -** in places where simple condition/decision coverage is inadequate. -*/ -#ifdef SQLITE_COVERAGE_TEST -SQLITE_PRIVATE void sqlite3Coverage(int); -# define testcase(X) if( X ){ sqlite3Coverage(__LINE__); } -#else -# define testcase(X) -#endif + #define SQLITE_MAX_LENGTH sqlite3MAX_LENGTH + #define SQLITE_MAX_COLUMN sqlite3MAX_COLUMN + #define SQLITE_MAX_SQL_LENGTH sqlite3MAX_SQL_LENGTH + #define SQLITE_MAX_EXPR_DEPTH sqlite3MAX_EXPR_DEPTH + #define SQLITE_MAX_COMPOUND_SELECT sqlite3MAX_COMPOUND_SELECT + #define SQLITE_MAX_VDBE_OP sqlite3MAX_VDBE_OP + #define SQLITE_MAX_FUNCTION_ARG sqlite3MAX_FUNCTION_ARG + #define SQLITE_MAX_VARIABLE_NUMBER sqlite3MAX_VARIABLE_NUMBER + #define SQLITE_MAX_PAGE_SIZE sqlite3MAX_PAGE_SIZE + #define SQLITE_MAX_PAGE_COUNT sqlite3MAX_PAGE_COUNT + #define SQLITE_MAX_LIKE_PATTERN_LENGTH sqlite3MAX_LIKE_PATTERN_LENGTH -/* -** The ALWAYS and NEVER macros surround boolean expressions which -** are intended to always be true or false, respectively. Such -** expressions could be omitted from the code completely. But they -** are included in a few cases in order to enhance the resilience -** of SQLite to unexpected behavior - to make the code "self-healing" -** or "ductile" rather than being "brittle" and crashing at the first -** hint of unplanned behavior. -** -** When doing coverage testing ALWAYS and NEVER are hard-coded to -** be true and false so that the unreachable code then specify will -** not be counted as untested code. -*/ -#ifdef SQLITE_COVERAGE_TEST -# define ALWAYS(X) (1) -# define NEVER(X) (0) -#else -# define ALWAYS(X) (X) -# define NEVER(X) (X) -#endif - -/* -** The macro unlikely() is a hint that surrounds a boolean -** expression that is usually false. Macro likely() surrounds -** a boolean expression that is usually true. GCC is able to -** use these hints to generate better code, sometimes. -*/ -#if defined(__GNUC__) && 0 -# define likely(X) __builtin_expect((X),1) -# define unlikely(X) __builtin_expect((X),0) -#else -# define likely(X) !!(X) -# define unlikely(X) !!(X) -#endif - -/* - * This macro is used to "hide" some ugliness in casting an int - * value to a ptr value under the MSVC 64-bit compiler. Casting - * non 64-bit values to ptr types results in a "hard" error with - * the MSVC 64-bit compiler which this attempts to avoid. - * - * A simple compiler pragma or casting sequence could not be found - * to correct this in all situations, so this macro was introduced. - * - * It could be argued that the intptr_t type could be used in this - * case, but that type is not available on all compilers, or - * requires the #include of specific headers which differs between - * platforms. - */ -#define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X]) -#define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0)) - -/* -** These #defines should enable >2GB file support on Posix if the -** underlying operating system supports it. If the OS lacks -** large file support, or if the OS is windows, these should be no-ops. -** -** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any -** system #includes. Hence, this block of code must be the very first -** code in all source files. -** -** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch -** on the compiler command line. This is necessary if you are compiling -** on a recent machine (ex: RedHat 7.2) but you want your code to work -** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2 -** without this option, LFS is enable. But LFS does not exist in the kernel -** in RedHat 6.0, so the code won't work. Hence, for maximum binary -** portability you should omit LFS. -** -** Similar is true for MacOS. LFS is only supported on MacOS 9 and later. -*/ -#ifndef SQLITE_DISABLE_LFS -# define _LARGE_FILE 1 -# ifndef _FILE_OFFSET_BITS -# define _FILE_OFFSET_BITS 64 -# endif -# define _LARGEFILE_SOURCE 1 + extern int sqlite3MAX_LENGTH; + extern int sqlite3MAX_COLUMN; + extern int sqlite3MAX_SQL_LENGTH; + extern int sqlite3MAX_EXPR_DEPTH; + extern int sqlite3MAX_COMPOUND_SELECT; + extern int sqlite3MAX_VDBE_OP; + extern int sqlite3MAX_FUNCTION_ARG; + extern int sqlite3MAX_VARIABLE_NUMBER; + extern int sqlite3MAX_PAGE_SIZE; + extern int sqlite3MAX_PAGE_COUNT; + extern int sqlite3MAX_LIKE_PATTERN_LENGTH; #endif @@ -372,40 +329,6 @@ SQLITE_PRIVATE void sqlite3Coverage(int); #endif #endif -/* -** Exactly one of the following macros must be defined in order to -** specify which memory allocation subsystem to use. -** -** SQLITE_SYSTEM_MALLOC // Use normal system malloc() -** SQLITE_MEMDEBUG // Debugging version of system malloc() -** SQLITE_MEMORY_SIZE // internal allocator #1 -** SQLITE_MMAP_HEAP_SIZE // internal mmap() allocator -** SQLITE_POW2_MEMORY_SIZE // internal power-of-two allocator -** -** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as -** the default. -*/ -#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ - defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ - defined(SQLITE_POW2_MEMORY_SIZE)>1 -# error "At most one of the following compile-time configuration options\ - is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG, SQLITE_MEMORY_SIZE,\ - SQLITE_MMAP_HEAP_SIZE, SQLITE_POW2_MEMORY_SIZE" -#endif -#if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)+\ - defined(SQLITE_MEMORY_SIZE)+defined(SQLITE_MMAP_HEAP_SIZE)+\ - defined(SQLITE_POW2_MEMORY_SIZE)==0 -# define SQLITE_SYSTEM_MALLOC 1 -#endif - -/* -** If SQLITE_MALLOC_SOFT_LIMIT is defined, then try to keep the -** sizes of memory allocations below this value where possible. -*/ -#if defined(SQLITE_POW2_MEMORY_SIZE) && !defined(SQLITE_MALLOC_SOFT_LIMIT) -# define SQLITE_MALLOC_SOFT_LIMIT 1024 -#endif - /* ** We need to define _XOPEN_SOURCE as follows in order to enable ** recursive mutexes on most unix systems. But Mac OS X is different. @@ -419,7 +342,7 @@ SQLITE_PRIVATE void sqlite3Coverage(int); ** ** See also ticket #2741. */ -#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && SQLITE_THREADSAFE # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ #endif @@ -459,7 +382,7 @@ SQLITE_PRIVATE void sqlite3Coverage(int); ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new -** features recently added to SQLite. We do not anticipate changes +** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve to make minor changes if ** experience from use "in the wild" suggest such changes are prudent. ** @@ -472,7 +395,7 @@ SQLITE_PRIVATE void sqlite3Coverage(int); ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. ** -** @(#) $Id: sqlite.h.in,v 1.372 2008/07/16 13:29:51 drh Exp $ +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef _SQLITE3_H_ #define _SQLITE3_H_ @@ -494,7 +417,8 @@ extern "C" { #endif /* -** Ensure these symbols were not defined by some previous header file. +** Make sure these symbols where not defined by some previous header +** file. */ #ifdef SQLITE_VERSION # undef SQLITE_VERSION @@ -506,143 +430,104 @@ extern "C" { /* ** CAPI3REF: Compile-Time Library Version Numbers {F10010} ** -** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in -** the sqlite3.h file specify the version of SQLite with which -** that header file is associated. +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". ** -** The "version" of SQLite is a string of the form "X.Y.Z". -** The phrase "alpha" or "beta" might be appended after the Z. -** The X value is major version number always 3 in SQLite3. -** The X value only changes when backwards compatibility is -** broken and we intend to never break backwards compatibility. -** The Y value is the minor version number and only changes when +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when ** there are major feature enhancements that are forwards compatible -** but not backwards compatible. -** The Z value is the release number and is incremented with -** each release but resets back to 0 whenever Y is incremented. +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). ** ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. -** -** INVARIANTS: -** -** {F10011} The SQLITE_VERSION #define in the sqlite3.h header file shall -** evaluate to a string literal that is the SQLite version -** with which the header file is associated. -** -** {F10014} The SQLITE_VERSION_NUMBER #define shall resolve to an integer -** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z -** are the major version, minor version, and release number. */ -#define SQLITE_VERSION "3.6.0" -#define SQLITE_VERSION_NUMBER 3006000 +#define SQLITE_VERSION "3.5.4.2" +#define SQLITE_VERSION_NUMBER 3005004 /* ** CAPI3REF: Run-Time Library Version Numbers {F10020} -** KEYWORDS: sqlite3_version ** -** These features provide the same information as the [SQLITE_VERSION] -** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated -** with the library instead of the header file. Cautious programmers might -** include a check in their application to verify that -** sqlite3_libversion_number() always returns the value +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value ** [SQLITE_VERSION_NUMBER]. ** -** The sqlite3_libversion() function returns the same information as is -** in the sqlite3_version[] string constant. The function is provided -** for use in DLLs since DLL users usually do not have direct access to string +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not ** constants within the DLL. -** -** INVARIANTS: -** -** {F10021} The [sqlite3_libversion_number()] interface shall return -** an integer equal to [SQLITE_VERSION_NUMBER]. -** -** {F10022} The [sqlite3_version] string constant shall contain -** the text of the [SQLITE_VERSION] string. -** -** {F10023} The [sqlite3_libversion()] function shall return -** a pointer to the [sqlite3_version] string constant. */ -SQLITE_API const char sqlite3_version[]; +SQLITE_EXTERN const char sqlite3_version[]; SQLITE_API const char *sqlite3_libversion(void); SQLITE_API int sqlite3_libversion_number(void); /* ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} ** -** SQLite can be compiled with or without mutexes. When -** the [SQLITE_THREADSAFE] C preprocessor macro is true, mutexes -** are enabled and SQLite is threadsafe. When that macro is false, -** the mutexes are omitted. Without the mutexes, it is not safe -** to use SQLite concurrently from more than one thread. +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. ** -** Enabling mutexes incurs a measurable performance penalty. -** So if speed is of utmost importance, it makes sense to disable -** the mutexes. But for maximum safety, mutexes should be enabled. -** The default behavior is for mutexes to be enabled. -** -** This interface can be used by a program to make sure that the -** version of SQLite that it is linking against was compiled with -** the desired setting of the [SQLITE_THREADSAFE] macro. -** -** This interface only reports on the compile-time mutex setting -** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with -** SQLITE_THREADSAFE=1 then mutexes are enabled by default but -** can be fully or partially disabled using a call to [sqlite3_config()] -** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], -** or [SQLITE_CONFIG_MUTEX]. The return value of this function shows -** only the default compile-time setting, not any run-time changes -** to that setting. -** -** INVARIANTS: -** -** {F10101} The [sqlite3_threadsafe()] function shall return nonzero if -** SQLite was compiled with the its mutexes enabled by default -** or zero if SQLite was compiled such that mutexes are -** permanently disabled. -** -** {F10102} The value returned by the [sqlite3_threadsafe()] function -** shall not change when mutex setting are modified at -** runtime using the [sqlite3_config()] interface and -** especially the [SQLITE_CONFIG_SINGLETHREAD], -** [SQLITE_CONFIG_MULTITHREAD], [SQLITE_CONFIG_SERIALIZED], -** and [SQLITE_CONFIG_MUTEX] verbs. +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. */ SQLITE_API int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle {F12000} -** KEYWORDS: {database connection} {database connections} ** -** Each open SQLite database is represented by a pointer to an instance of -** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] -** is its destructor. There are many other interfaces (such as -** [sqlite3_prepare_v2()], [sqlite3_create_function()], and -** [sqlite3_busy_timeout()] to name but three) that are methods on an -** sqlite3 object. +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. */ typedef struct sqlite3 sqlite3; + /* ** CAPI3REF: 64-Bit Integer Types {F10200} -** KEYWORDS: sqlite_int64 sqlite_uint64 ** -** Because there is no cross-platform way to specify 64-bit integer types +** Because there is no cross-platform way to specify such types ** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} ** -** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. -** The sqlite_int64 and sqlite_uint64 types are supported for backwards -** compatibility only. -** -** INVARIANTS: -** -** {F10201} The [sqlite_int64] and [sqlite3_int64] type shall specify -** a 64-bit signed integer. -** -** {F10202} The [sqlite_uint64] and [sqlite3_uint64] type shall specify -** a 64-bit unsigned integer. +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; @@ -659,7 +544,7 @@ typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, -** substitute integer for floating-point. +** substitute integer for floating-point */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 @@ -668,53 +553,22 @@ typedef sqlite_uint64 sqlite3_uint64; /* ** CAPI3REF: Closing A Database Connection {F12010} ** -** This routine is the destructor for the [sqlite3] object. +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. ** -** Applications should [sqlite3_finalize | finalize] all [prepared statements] -** and [sqlite3_blob_close | close] all [BLOB handles] associated with -** the [sqlite3] object prior to attempting to close the object. -** The [sqlite3_next_stmt()] interface can be used to locate all -** [prepared statements] associated with a [database connection] if desired. -** Typical code might look like this: +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} ** -**
-** sqlite3_stmt *pStmt;
-** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
-**     sqlite3_finalize(pStmt);
-** }
-** 
-** -** If [sqlite3_close()] is invoked while a transaction is open, -** the transaction is automatically rolled back. -** -** INVARIANTS: -** -** {F12011} A successful call to [sqlite3_close(C)] shall destroy the -** [database connection] object C. -** -** {F12012} A successful call to [sqlite3_close(C)] shall return SQLITE_OK. -** -** {F12013} A successful call to [sqlite3_close(C)] shall release all -** memory and system resources associated with [database connection] -** C. -** -** {F12014} A call to [sqlite3_close(C)] on a [database connection] C that -** has one or more open [prepared statements] shall fail with -** an [SQLITE_BUSY] error code. -** -** {F12015} A call to [sqlite3_close(C)] where C is a NULL pointer shall -** return SQLITE_OK. -** -** {F12019} When [sqlite3_close(C)] is invoked on a [database connection] C -** that has a pending transaction, the transaction shall be -** rolled back. -** -** LIMITATIONS: -** -** {A12016} The C parameter to [sqlite3_close(C)] must be either a NULL -** pointer or an [sqlite3] object pointer previously obtained -** from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()], and not previously closed. +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. */ SQLITE_API int sqlite3_close(sqlite3 *); @@ -728,112 +582,64 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface {F12100} ** -** The sqlite3_exec() interface is a convenient way of running one or more -** SQL statements without having to write a lot of C code. The UTF-8 encoded -** SQL statements are passed in as the second parameter to sqlite3_exec(). -** The statements are evaluated one by one until either an error or -** an interrupt is encountered, or until they are all done. The 3rd parameter -** is an optional callback that is invoked once for each row of any query -** results produced by the SQL statements. The 5th parameter tells where -** to write any error messages. +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. ** -** The error message passed back through the 5th parameter is held -** in memory obtained from [sqlite3_malloc()]. To avoid a memory leak, -** the calling application should call [sqlite3_free()] on any error -** message returned through the 5th parameter when it has finished using -** the error message. +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. ** -** If the SQL statement in the 2nd parameter is NULL or an empty string -** or a string containing only whitespace and comments, then no SQL -** statements are evaluated and the database is not changed. +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. ** -** The sqlite3_exec() interface is implemented in terms of -** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. -** The sqlite3_exec() routine does nothing to the database that cannot be done -** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. ** -** INVARIANTS: +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. ** -** {F12101} A successful invocation of [sqlite3_exec(D,S,C,A,E)] -** shall sequentially evaluate all of the UTF-8 encoded, -** semicolon-separated SQL statements in the zero-terminated -** string S within the context of the [database connection] D. +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? ** -** {F12102} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL then -** the actions of the interface shall be the same as if the -** S parameter were an empty string. -** -** {F12104} The return value of [sqlite3_exec()] shall be [SQLITE_OK] if all -** SQL statements run successfully and to completion. -** -** {F12105} The return value of [sqlite3_exec()] shall be an appropriate -** non-zero [error code] if any SQL statement fails. -** -** {F12107} If one or more of the SQL statements handed to [sqlite3_exec()] -** return results and the 3rd parameter is not NULL, then -** the callback function specified by the 3rd parameter shall be -** invoked once for each row of result. -** -** {F12110} If the callback returns a non-zero value then [sqlite3_exec()] -** shall abort the SQL statement it is currently evaluating, -** skip all subsequent SQL statements, and return [SQLITE_ABORT]. -** -** {F12113} The [sqlite3_exec()] routine shall pass its 4th parameter through -** as the 1st parameter of the callback. -** -** {F12116} The [sqlite3_exec()] routine shall set the 2nd parameter of its -** callback to be the number of columns in the current row of -** result. -** -** {F12119} The [sqlite3_exec()] routine shall set the 3rd parameter of its -** callback to be an array of pointers to strings holding the -** values for each column in the current result set row as -** obtained from [sqlite3_column_text()]. -** -** {F12122} The [sqlite3_exec()] routine shall set the 4th parameter of its -** callback to be an array of pointers to strings holding the -** names of result columns as obtained from [sqlite3_column_name()]. -** -** {F12125} If the 3rd parameter to [sqlite3_exec()] is NULL then -** [sqlite3_exec()] shall silently discard query results. -** -** {F12131} If an error occurs while parsing or evaluating any of the SQL -** statements in the S parameter of [sqlite3_exec(D,S,C,A,E)] and if -** the E parameter is not NULL, then [sqlite3_exec()] shall store -** in *E an appropriate error message written into memory obtained -** from [sqlite3_malloc()]. -** -** {F12134} The [sqlite3_exec(D,S,C,A,E)] routine shall set the value of -** *E to NULL if E is not NULL and there are no errors. -** -** {F12137} The [sqlite3_exec(D,S,C,A,E)] function shall set the [error code] -** and message accessible via [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()]. -** -** {F12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an -** empty string or contains nothing other than whitespace, comments, -** and/or semicolons, then results of [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** shall reset to indicate no errors. -** -** LIMITATIONS: -** -** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open -** [database connection]. -** -** {A12142} The database connection must not be closed while -** [sqlite3_exec()] is running. -** -** {A12143} The calling function should use [sqlite3_free()] to free -** the memory that *errmsg is left pointing at once the error -** message is no longer needed. -** -** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()] -** must remain unchanged while [sqlite3_exec()] is running. +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} */ SQLITE_API int sqlite3_exec( sqlite3*, /* An open database */ - const char *sql, /* SQL to be evaluated */ + const char *sql, /* SQL to be evaluted */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ @@ -841,15 +647,18 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: Result Codes {F10210} -** KEYWORDS: SQLITE_OK {error code} {error codes} -** KEYWORDS: {result code} {result codes} +** KEYWORDS: SQLITE_OK ** ** Many SQLite functions return an integer result code from the set shown -** here in order to indicates success or failure. +** above in order to indicates success or failure. ** -** New error codes may be added in future versions of SQLite. +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} ** ** See also: [SQLITE_IOERR_READ | extended result codes] +** */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ @@ -885,61 +694,51 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: Extended Result Codes {F10220} -** KEYWORDS: {extended error code} {extended error codes} -** KEYWORDS: {extended result code} {extended result codes} ** ** In its default configuration, SQLite API routines return one of 26 integer -** [SQLITE_OK | result codes]. However, experience has shown that many of -** these result codes are too coarse-grained. They do not provide as +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 and later) include ** support for additional result codes that provide more detailed information -** about errors. The extended result codes are enabled or disabled -** on a per database connection basis using the -** [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed here. -** One may expect the number of extended result codes will be expand -** over time. Software that uses extended result codes should expect -** to see new result codes in future releases of SQLite. +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} ** ** The SQLITE_OK result code will never be extended. It will always ** be exactly zero. -** -** INVARIANTS: -** -** {F10223} The symbolic name for an extended result code shall contains -** a related primary result code as a prefix. -** -** {F10224} Primary result code names shall contain a single "_" character. -** -** {F10225} Extended result code names shall contain two or more "_" characters. -** -** {F10226} The numeric value of an extended result code shall contain the -** numeric value of its corresponding primary result code in -** its least significant 8 bits. */ -#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) -#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) -#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) -#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) -#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) -#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) -#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) -#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) -#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) -#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) -#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) -#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) -#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) -#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) /* ** CAPI3REF: Flags For File Open Operations {F10230} ** -** These bit values are intended for use in the -** 3rd parameter to the [sqlite3_open_v2()] interface and -** in the 4th parameter to the xOpen method of the +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the ** [sqlite3_vfs] object. */ #define SQLITE_OPEN_READONLY 0x00000001 @@ -954,25 +753,24 @@ SQLITE_API int sqlite3_exec( #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 -#define SQLITE_OPEN_NOMUTEX 0x00008000 /* ** CAPI3REF: Device Characteristics {F10240} ** -** The xDeviceCapabilities method of the [sqlite3_io_methods] +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] ** object returns an integer which is a vector of the these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] -** refers to. +** refers to. {END} ** -** The SQLITE_IOCAP_ATOMIC property means that all writes of -** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of -** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other -** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). */ @@ -991,9 +789,9 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: File Locking Levels {F10250} ** -** SQLite uses one of these integer values as the second +** {F10251} SQLite uses one of the following integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods -** of an [sqlite3_io_methods] object. +** of an [sqlite3_io_methods] object. {END} */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 @@ -1004,20 +802,21 @@ SQLITE_API int sqlite3_exec( /* ** CAPI3REF: Synchronization Type Flags {F10260} ** -** When SQLite invokes the xSync() method of an -** [sqlite3_io_methods] object it uses a combination of +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the ** these integer values as the second argument. ** -** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode -** information need not be flushed. The SQLITE_SYNC_NORMAL flag means -** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means ** to use Mac OS-X style fullsync instead of fsync(). */ #define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 + /* ** CAPI3REF: OS Interface Open File Handle {F11110} ** @@ -1036,18 +835,17 @@ struct sqlite3_file { /* ** CAPI3REF: OS Interface File Virtual Methods Object {F11120} ** -** Every file opened by the [sqlite3_vfs] xOpen method populates an -** [sqlite3_file] object (or, more commonly, a subclass of the -** [sqlite3_file] object) with a pointer to an instance of this object. -** This object defines the methods used to perform various operations -** against the open file represented by the [sqlite3_file] object. +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). -** The second choice is a Mac OS-X style fullsync. The [SQLITE_SYNC_DATAONLY] -** flag may be ORed in to indicate that only the data of the file -** and not its inode needs to be synced. -** +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** ** The integer values to xLock() and xUnlock() are one of **
    **
  • [SQLITE_LOCK_NONE], @@ -1056,24 +854,26 @@ struct sqlite3_file { **
  • [SQLITE_LOCK_PENDING], or **
  • [SQLITE_LOCK_EXCLUSIVE]. **
-** xLock() increases the lock. xUnlock() decreases the lock. -** The xCheckReservedLock() method checks whether any database connection, -** either in this process or in some other process, is holding a RESERVED, +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true -** if such a lock exists and false otherwise. -** +** if such a lock exists and false if not. +** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the -** [sqlite3_file_control()] interface. The second "op" argument is an -** integer opcode. The third argument is a generic pointer intended to -** point to a structure that may contain arguments or space in which to +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite -** core reserves all opcodes less than 100 for its own use. +** core reserves opcodes less than 100 for its own use. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. -** Applications that define a custom xFileControl method should use opcodes +** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. ** ** The xSectorSize() method returns the sector size of the @@ -1119,7 +919,7 @@ struct sqlite3_io_methods { int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); int (*xLock)(sqlite3_file*, int); int (*xUnlock)(sqlite3_file*, int); - int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xCheckReservedLock)(sqlite3_file*); int (*xFileControl)(sqlite3_file*, int op, void *pArg); int (*xSectorSize)(sqlite3_file*); int (*xDeviceCharacteristics)(sqlite3_file*); @@ -1130,14 +930,14 @@ struct sqlite3_io_methods { ** CAPI3REF: Standard File Control Opcodes {F11310} ** ** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] ** interface. ** -** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This -** opcode causes the xFileControl method to write the current state of +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) -** into an integer that the pArg argument points to. This capability +** into an integer that the pArg argument points to. {F11312} This capability ** is used during testing and only needs to be supported when SQLITE_TEST ** is defined. */ @@ -1147,8 +947,8 @@ struct sqlite3_io_methods { ** CAPI3REF: Mutex Handle {F17110} ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an -** abstract type for a mutex object. The SQLite core never looks -** at the internal representation of an [sqlite3_mutex]. It only +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. @@ -1158,29 +958,25 @@ typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: OS Interface Object {F11140} ** -** An instance of the sqlite3_vfs object defines the interface between -** the SQLite core and the underlying operating system. The "vfs" +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". ** -** The value of the iVersion field is initially 1 but may be larger in -** future versions of SQLite. Additional fields may be appended to this -** object when the iVersion value is increased. Note that the structure -** of the sqlite3_vfs object changes in the transaction between -** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not -** modified. +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** -** Registered sqlite3_vfs objects are kept on a linked list formed by +** Registered vfs modules are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface -** searches the list. Neither the application code nor the VFS -** implementation should use the pNext pointer. +** searches the list. ** -** The pNext field is the only field in the sqlite3_vfs +** The pNext field is the only fields in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs @@ -1189,28 +985,23 @@ typedef struct sqlite3_mutex sqlite3_mutex; ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** -** {F11141} SQLite will guarantee that the zFilename parameter to xOpen -** is either a NULL pointer or string obtained -** from xFullPathname(). SQLite further guarantees that -** the string will be valid and unchanged until xClose() is -** called. {END} Becasue of the previous sentense, -** the [sqlite3_file] can safely store a pointer to the +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the ** filename if it needs to remember the filename for some reason. -** If the zFilename parameter is xOpen is a NULL pointer then xOpen -** must invite its own temporary name for the file. Whenever the -** xFilename parameter is NULL it will also be the case that the -** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** {F11142} The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} ** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. -** +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** ** {F11143} SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: -** +** **
    **
  • [SQLITE_OPEN_MAIN_DB] **
  • [SQLITE_OPEN_MAIN_JOURNAL] @@ -1222,56 +1013,59 @@ typedef struct sqlite3_mutex sqlite3_mutex; **
{END} ** ** The file I/O implementation can use the object type flags to -** change the way it deals with files. For example, an application -** that does not care about crash recovery or rollback might make -** the open of a journal file a no-op. Writes to this journal would -** also be no-ops, and any attempt to read the journal would return -** SQLITE_IOERR. Or the implementation might recognize that a database -** file will be doing page-aligned sector reads and writes in a random -** order and set up its I/O subsystem accordingly. -** -** SQLite might also add one of the following flags to the xOpen method: -** +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** **
    **
  • [SQLITE_OPEN_DELETEONCLOSE] **
  • [SQLITE_OPEN_EXCLUSIVE] **
-** +** ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] -** will be set for TEMP databases, journals and for subjournals. -** +** will be set for TEMP databases, journals and for subjournals. ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened ** for exclusive access. This flag is set for all files except -** for the main database file. -** -** {F11148} At least szOsFile bytes of memory are allocated by SQLite -** to hold the [sqlite3_file] structure passed as the third -** argument to xOpen. {END} The xOpen method does not have to +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to ** allocate the structure; it should just fill it in. -** -** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] -** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to -** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] -** to test whether a file is at least readable. {END} The file can be a +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a ** directory. -** -** {F11150} SQLite will always allocate at least mxPathname+1 bytes for the -** output buffer xFullPathname. {F11151} The exact size of the output buffer -** is also passed as a parameter to both methods. {END} If the output buffer -** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is -** handled as a fatal error by SQLite, vfs implementations should endeavor -** to prevent this by setting mxPathname to a sufficiently large value. -** +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** ** The xRandomness(), xSleep(), and xCurrentTime() interfaces ** are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is -** the actual number of bytes of randomness obtained. -** The xSleep() method causes the calling thread to sleep for at +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at ** least the number of microseconds given. The xCurrentTime() -** method returns a Julian Day Number for the current date and time. +** method returns a Julian Day Number for the current date and +** time. */ typedef struct sqlite3_vfs sqlite3_vfs; struct sqlite3_vfs { @@ -1284,7 +1078,8 @@ struct sqlite3_vfs { int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); - int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); @@ -1293,7 +1088,6 @@ struct sqlite3_vfs { int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); - int (*xGetLastError)(sqlite3_vfs*, int, char *); /* New fields may be appended in figure versions. The iVersion ** value will increment whenever this happens. */ }; @@ -1303,528 +1097,164 @@ struct sqlite3_vfs { ** ** {F11191} These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. {END} They determine -** what kind of permissions the xAccess method is looking for. -** {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks whether the file exists. -** {F11193} With SQLITE_ACCESS_READWRITE, the xAccess method -** checks whether the file is both readable and writable. -** {F11194} With SQLITE_ACCESS_READ, the xAccess method -** checks whether the file is readable. +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 #define SQLITE_ACCESS_READ 2 -/* -** CAPI3REF: Initialize The SQLite Library {F10130} -** -** The sqlite3_initialize() routine initializes the -** SQLite library. The sqlite3_shutdown() routine -** deallocates any resources that were allocated by sqlite3_initialize(). -** -** A call to sqlite3_initialize() is an "effective" call if it is -** the first time sqlite3_initialize() is invoked during the lifetime of -** the process, or if it is the first time sqlite3_initialize() is invoked -** following a call to sqlite3_shutdown(). Only an effective call -** of sqlite3_initialize() does any initialization. All other calls -** are harmless no-ops. -** -** Among other things, sqlite3_initialize() shall invoke -** sqlite3_os_init(). Similarly, sqlite3_shutdown() -** shall invoke sqlite3_os_end(). -** -** The sqlite3_initialize() routine returns SQLITE_OK on success. -** If for some reason, sqlite3_initialize() is unable to initialize -** the library (perhaps it is unable to allocate a needed resource such -** as a mutex) it returns an [error code] other than SQLITE_OK. -** -** The sqlite3_initialize() routine is called internally by many other -** SQLite interfaces so that an application usually does not need to -** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] -** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized -** already. However, if SQLite is compiled with the SQLITE_OMIT_AUTOINIT -** compile-time option, then the automatic calls to sqlite3_initialize() -** are omitted and the application must call sqlite3_initialize() directly -** prior to using any other SQLite interface. For maximum portability, -** it is recommended that applications always invoke sqlite3_initialize() -** directly prior to using any other SQLite interface. Future releases -** of SQLite may require this. In other words, the behavior exhibited -** when SQLite is compiled with SQLITE_OMIT_AUTOINIT might become the -** default behavior in some future release of SQLite. -** -** The sqlite3_os_init() routine does operating-system specific -** initialization of the SQLite library. The sqlite3_os_end() -** routine undoes the effect of sqlite3_os_init(). Typical tasks -** performed by these routines include allocation or deallocation -** of static resources, initialization of global variables, -** setting up a default [sqlite3_vfs] module, or setting up -** a default configuration using [sqlite3_config()]. -** -** The application should never invoke either sqlite3_os_init() -** or sqlite3_os_end() directly. The application should only invoke -** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() -** interface is called automatically by sqlite3_initialize() and -** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate -** implementations for sqlite3_os_init() and sqlite3_os_end() -** are built into SQLite when it is compiled for unix, windows, or os/2. -** When built for other platforms (using the SQLITE_OS_OTHER=1 compile-time -** option) the application must supply a suitable implementation for -** sqlite3_os_init() and sqlite3_os_end(). An application-supplied -** implementation of sqlite3_os_init() or sqlite3_os_end() -** must return SQLITE_OK on success and some other [error code] upon -** failure. -*/ -SQLITE_API int sqlite3_initialize(void); -SQLITE_API int sqlite3_shutdown(void); -SQLITE_API int sqlite3_os_init(void); -SQLITE_API int sqlite3_os_end(void); - -/* -** CAPI3REF: Configuring The SQLite Library {F10145} -** -** The sqlite3_config() interface is used to make global configuration -** changes to SQLite in order to tune SQLite to the specific needs of -** the application. The default configuration is recommended for most -** applications and so this routine is usually not necessary. It is -** provided to support rare applications with unusual needs. -** -** The sqlite3_config() interface is not threadsafe. The application -** must insure that no other SQLite interfaces are invoked by other -** threads while sqlite3_config() is running. Furthermore, sqlite3_config() -** may only be invoked prior to library initialization using -** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. -** Note, however, that sqlite3_config() can be called as part of the -** implementation of an application-defined [sqlite3_os_init()]. -** -** The first argument to sqlite3_config() is an integer -** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines -** what property of SQLite is to be configured. Subsequent arguments -** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option] -** in the first argument. -** -** When a configuration option is set, sqlite3_config() returns SQLITE_OK. -** If the option is unknown or SQLite is unable to set the option -** then this routine returns a non-zero [error code]. -** -** The sqlite3_config() interface is considered experimental in that -** new configuration options may be added in future releases and existing -** configuration options may be discontinued or modified. -*/ -SQLITE_API int sqlite3_config(int, ...); - -/* -** CAPI3REF: Memory Allocation Routines {F10155} -** -** An instance of this object defines the interface between SQLite -** and low-level memory allocation routines. -** -** This object is used in only one place in the SQLite interface. -** A pointer to an instance of this object is the argument to -** [sqlite3_config()] when the configuration option is -** [SQLITE_CONFIG_MALLOC]. By creating an instance of this object -** and passing it to [sqlite3_config()] during configuration, an -** application can specify an alternative memory allocation subsystem -** for SQLite to use for all of its dynamic memory needs. -** -** Note that SQLite comes with a built-in memory allocator that is -** perfectly adequate for the overwhelming majority of applications -** and that this object is only useful to a tiny minority of applications -** with specialized memory allocation requirements. This object is -** also used during testing of SQLite in order to specify an alternative -** memory allocator that simulates memory out-of-memory conditions in -** order to verify that SQLite recovers gracefully from such -** conditions. -** -** The xMalloc, xFree, and xRealloc methods must work like the -** malloc(), free(), and realloc() functions from the standard library. -** -** xSize should return the allocated size of a memory allocation -** previously obtained from xMalloc or xRealloc. The allocated size -** is always at least as big as the requested size but may be larger. -** -** The xRoundup method returns what would be the allocated size of -** a memory allocation given a particular requested size. Most memory -** allocators round up memory allocations at least to the next multiple -** of 8. Some allocators round up to a larger multiple or to a power of 2. -** -** The xInit method initializes the memory allocator. (For example, -** it might allocate any require mutexes or initialize internal data -** structures. The xShutdown method is invoked (indirectly) by -** [sqlite3_shutdown()] and should deallocate any resources acquired -** by xInit. The pAppData pointer is used as the only parameter to -** xInit and xShutdown. -*/ -typedef struct sqlite3_mem_methods sqlite3_mem_methods; -struct sqlite3_mem_methods { - void *(*xMalloc)(int); /* Memory allocation function */ - void (*xFree)(void*); /* Free a prior allocation */ - void *(*xRealloc)(void*,int); /* Resize an allocation */ - int (*xSize)(void*); /* Return the size of an allocation */ - int (*xRoundup)(int); /* Round up request size to allocation size */ - int (*xInit)(void*); /* Initialize the memory allocator */ - void (*xShutdown)(void*); /* Deinitialize the memory allocator */ - void *pAppData; /* Argument to xInit() and xShutdown() */ -}; - -/* -** CAPI3REF: Configuration Options {F10160} -** -** These constants are the available integer configuration options that -** can be passed as the first argument to the [sqlite3_config()] interface. -** -** New configuration options may be added in future releases of SQLite. -** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_config()] to make sure that -** the call worked. The [sqlite3_config()] interface will return a -** non-zero [error code] if a discontinued or unsupported configuration option -** is invoked. -** -**
-**
SQLITE_CONFIG_SINGLETHREAD
-**
There are no arguments to this option. This option disables -** all mutexing and puts SQLite into a mode where it can only be used -** by a single thread.
-** -**
SQLITE_CONFIG_MULTITHREAD
-**
There are no arguments to this option. This option disables -** mutexing on [database connection] and [prepared statement] objects. -** The application is responsible for serializing access to -** [database connections] and [prepared statements]. But other mutexes -** are enabled so that SQLite will be safe to use in a multi-threaded -** environment.
-** -**
SQLITE_CONFIG_SERIALIZED
-**
There are no arguments to this option. This option enables -** all mutexes including the recursive -** mutexes on [database connection] and [prepared statement] objects. -** In this mode (which is the default when SQLite is compiled with -** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access -** to [database connections] and [prepared statements] so that the -** application is free to use the same [database connection] or the -** same [prepared statement] in different threads at the same time. -** -**

This configuration option merely sets the default mutex -** behavior to serialize access to [database connections]. Individual -** [database connections] can override this setting -** using the [SQLITE_OPEN_NOMUTEX] flag to [sqlite3_open_v2()].

-** -**
SQLITE_CONFIG_MALLOC
-**
This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The argument specifies -** alternative low-level memory allocation routines to be used in place of -** the memory allocation routines built into SQLite.
-** -**
SQLITE_CONFIG_GETMALLOC
-**
This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] -** structure is filled with the currently defined memory allocation routines. -** This option can be used to overload the default memory allocation -** routines with a wrapper that simulations memory allocation failure or -** tracks memory usage, for example.
-** -**
SQLITE_CONFIG_MEMSTATUS
-**
This option takes single boolean argument which enables or disables -** the collection of memory allocation statistics. When disabled, the -** following SQLite interfaces become non-operational: -**
    -**
  • [sqlite3_memory_used()] -**
  • [sqlite3_memory_highwater()] -**
  • [sqlite3_soft_heap_limit()] -**
  • sqlite3_memory_status() -**
-**
-** -**
SQLITE_CONFIG_SCRATCH
-**
This option specifies a static memory buffer that SQLite can use for -** scratch memory. There are three arguments: A pointer to the memory, the -** size of each scratch buffer (sz), and the number of buffers (N). The sz -** argument must be a multiple of 16. The first -** argument should point to an allocation of at least (sz+4)*N bytes of memory. -** SQLite will use no more than one scratch buffer at once per thread, so -** N should be set to the expected maximum number of threads. The sz -** parameter should be 6 times the size of the largest database page size. -** Scratch buffers are used as part of the btree balance operation. If -** The btree balancer needs additional memory beyond what is provided by -** scratch buffers or if no scratch buffer space is specified, then SQLite -** goes to [sqlite3_malloc()] to obtain the memory it needs.
-** -**
SQLITE_CONFIG_PAGECACHE
-**
This option specifies a static memory buffer that SQLite can use for -** the database page cache. There are three arguments: A pointer to the -** memory, the size of each page buffer (sz), and the number of pages (N). -** The sz argument must be a power of two between 512 and 32768. The first -** argument should point to an allocation of at least (sz+4)*N bytes of memory. -** SQLite will use the memory provided by the first argument to satisfy its -** memory needs for the first N pages that it adds to cache. If additional -** page cache memory is needed beyond what is provided by this option, then -** SQLite goes to [sqlite3_malloc()] for the additional storage space.
-** -**
SQLITE_CONFIG_HEAP
-**
This option specifies a static memory buffer that SQLite will use -** for all of its dynamic memory allocation needs beyond those provided -** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. -** There are three arguments: A pointer to the memory, the number of -** bytes in the memory buffer, and the minimum allocation size. If -** the first pointer (the memory pointer) is NULL, then SQLite reverts -** to using its default memory allocator (the system malloc() implementation), -** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. If the -** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or -** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory -** allocator is engaged to handle all of SQLites memory allocation needs.
-** -**
SQLITE_CONFIG_MUTEX
-**
This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The argument specifies -** alternative low-level mutex routines to be used in place -** the mutex routines built into SQLite.
-** -**
SQLITE_CONFIG_GETMUTEX
-**
This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The -** [sqlite3_mutex_methods] -** structure is filled with the currently defined mutex routines. -** This option can be used to overload the default mutex allocation -** routines with a wrapper used to track mutex usage for performance -** profiling or testing, for example.
-*/ -#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ -#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ -#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ -#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ -#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ -#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ -#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ -#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ -#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ - - /* ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} ** -** The sqlite3_extended_result_codes() routine enables or disables the -** [extended result codes] feature of SQLite. The extended result -** codes are disabled by default for historical compatibility considerations. +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. ** -** INVARIANTS: -** -** {F12201} Each new [database connection] shall have the -** [extended result codes] feature disabled by default. -** -** {F12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable -** [extended result codes] for the [database connection] D -** if the F parameter is true, or disable them if F is false. +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid {F12220} ** -** Each entry in an SQLite table has a unique 64-bit signed -** integer key called the "rowid". The rowid is always available +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those -** names are not also used by explicitly declared columns. If +** names are not also used by explicitly declared columns. {F12223} If ** the table has a column of type INTEGER PRIMARY KEY then that column -** is another alias for the rowid. +** is another an alias for the rowid. ** -** This routine returns the rowid of the most recent -** successful INSERT into the database from the [database connection] -** in the first argument. If no successful INSERTs -** have ever occurred on that database connection, zero is returned. +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. ** -** If an INSERT occurs within a trigger, then the rowid of the inserted -** row is returned by this routine as long as the trigger is running. -** But once the trigger terminates, the value returned by this routine -** reverts to the last value inserted before the trigger fired. +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. ** -** An INSERT that fails due to a constraint violation is not a -** successful INSERT and does not change the value returned by this -** routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. When INSERT OR REPLACE +** routine when their insertion fails. {F12231} When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change -** the return value of this interface. +** the return value of this interface. ** -** For the purposes of this routine, an INSERT is considered to -** be successful even if it is subsequently rolled back. -** -** INVARIANTS: -** -** {F12221} The [sqlite3_last_insert_rowid()] function returns the rowid -** of the most recent successful INSERT performed on the same -** [database connection] and within the same or higher level -** trigger context, or zero if there have been no qualifying inserts. -** -** {F12223} The [sqlite3_last_insert_rowid()] function returns the -** same value when called from the same trigger context -** immediately before and after a ROLLBACK. -** -** LIMITATIONS: -** -** {A12232} If a separate thread performs a new INSERT on the same -** database connection while the [sqlite3_last_insert_rowid()] -** function is running and thus changes the last insert rowid, -** then the value returned by [sqlite3_last_insert_rowid()] is -** unpredictable and might not equal either the old or the new -** last insert rowid. +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. */ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified {F12240} ** -** This function returns the number of database rows that were changed +** {F12241} This function returns the number of database rows that were changed ** or inserted or deleted by the most recently completed SQL statement -** on the [database connection] specified by the first parameter. -** Only changes that are directly specified by the INSERT, UPDATE, -** or DELETE statement are counted. Auxiliary changes caused by -** triggers are not counted. Use the [sqlite3_total_changes()] function +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function ** to find the total number of changes including changes caused by triggers. ** -** A "row change" is a change to a single row of a single table -** caused by an INSERT, DELETE, or UPDATE statement. Rows that -** are changed as side effects of REPLACE constraint resolution, -** rollback, ABORT processing, DROP TABLE, or by any other -** mechanisms do not count as direct row changes. -** -** A "trigger context" is a scope of execution that begins and -** ends with the script of a trigger. Most SQL statements are -** evaluated outside of any trigger. This is the "top level" -** trigger context. If a trigger fires from the top level, a -** new trigger context is entered for the duration of that one -** trigger. Subtriggers create subcontexts for their duration. -** -** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does -** not create a new trigger context. -** -** This function returns the number of direct row changes in the -** most recent INSERT, UPDATE, or DELETE statement within the same -** trigger context. -** -** Thus, when called from the top level, this function returns the -** number of changes in the most recent INSERT, UPDATE, or DELETE -** that also occurred at the top level. Within the body of a trigger, -** the sqlite3_changes() interface can be called to find the number of +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of ** changes in the most recently completed INSERT, UPDATE, or DELETE ** statement within the body of the same trigger. -** However, the number returned does not include changes -** caused by subtriggers since those have their own context. ** -** SQLite implements the command "DELETE FROM table" without a WHERE clause -** by dropping and recreating the table. (This is much faster than going -** through and deleting individual elements from the table.) Because of this -** optimization, the deletions in "DELETE FROM table" are not row changes and -** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()] -** functions, regardless of the number of elements that were originally -** in the table. To get an accurate count of the number of rows deleted, use +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use ** "DELETE FROM table WHERE 1" instead. ** -** INVARIANTS: -** -** {F12241} The [sqlite3_changes()] function shall return the number of -** row changes caused by the most recent INSERT, UPDATE, -** or DELETE statement on the same database connection and -** within the same or higher trigger context, or zero if there have -** not been any qualifying row changes. -** -** {F12243} Statements of the form "DELETE FROM tablename" with no -** WHERE clause shall cause subsequent calls to -** [sqlite3_changes()] to return zero, regardless of the -** number of rows originally in the table. -** -** LIMITATIONS: -** -** {A12252} If a separate thread makes changes on the same database connection -** while [sqlite3_changes()] is running then the value returned -** is unpredictable and not meaningful. +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. */ SQLITE_API int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} ** -** This function returns the number of row changes caused by INSERT, -** UPDATE or DELETE statements since the [database connection] was opened. -** The count includes all changes from all trigger contexts. However, -** the count does not include changes used to implement REPLACE constraints, -** do rollbacks or ABORT processing, or DROP table processing. -** The changes are counted as soon as the statement that makes them is -** completed (when the statement handle is passed to [sqlite3_reset()] or -** [sqlite3_finalize()]). +** See also the [sqlite3_change()] interface. ** -** SQLite implements the command "DELETE FROM table" without a WHERE clause -** by dropping and recreating the table. (This is much faster than going -** through and deleting individual elements from the table.) Because of this -** optimization, the deletions in "DELETE FROM table" are not row changes and -** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()] -** functions, regardless of the number of elements that were originally -** in the table. To get an accurate count of the number of rows deleted, use +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use ** "DELETE FROM table WHERE 1" instead. ** -** See also the [sqlite3_changes()] interface. -** -** INVARIANTS: -** -** {F12261} The [sqlite3_total_changes()] returns the total number -** of row changes caused by INSERT, UPDATE, and/or DELETE -** statements on the same [database connection], in any -** trigger context, since the database connection was created. -** -** {F12263} Statements of the form "DELETE FROM tablename" with no -** WHERE clause shall not change the value returned -** by [sqlite3_total_changes()]. -** -** LIMITATIONS: -** -** {A12264} If a separate thread makes changes on the same database connection -** while [sqlite3_total_changes()] is running then the value -** returned is unpredictable and not meaningful. +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} */ SQLITE_API int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query {F12270} ** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. This routine is typically +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** -** It is safe to call this routine from a thread different from the -** thread that is currently running the database operation. But it -** is not safe to call this routine with a [database connection] that +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that ** is closed or might close before sqlite3_interrupt() returns. ** -** If an SQL operation is very nearly finished at the time when -** sqlite3_interrupt() is called, then it might not have an opportunity -** to be interrupted and might continue to completion. -** -** An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE -** that is inside an explicit transaction, then the entire transaction -** will be rolled back automatically. -** -** A call to sqlite3_interrupt() has no effect on SQL statements +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements ** that are started after sqlite3_interrupt() returns. -** -** INVARIANTS: -** -** {F12271} The [sqlite3_interrupt()] interface will force all running -** SQL statements associated with the same database connection -** to halt after processing at most one additional row of data. -** -** {F12272} Any SQL statement that is interrupted by [sqlite3_interrupt()] -** will return [SQLITE_INTERRUPT]. -** -** LIMITATIONS: -** -** {A12279} If the database connection closes while [sqlite3_interrupt()] -** is running then bad things will likely happen. */ SQLITE_API void sqlite3_interrupt(sqlite3*); @@ -1836,34 +1266,21 @@ SQLITE_API void sqlite3_interrupt(sqlite3*); ** if additional input is needed before sending the text into ** SQLite for parsing. These routines return true if the input string ** appears to be a complete SQL statement. A statement is judged to be -** complete if it ends with a semicolon token and is not a fragment of a -** CREATE TRIGGER statement. Semicolons that are embedded within -** string literals or quoted identifier names or comments are not -** independent tokens (they are part of the token in which they are -** embedded) and thus do not count as a statement terminator. +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. ** -** These routines do not parse the SQL statements thus -** will not detect syntactically incorrect SQL. -** -** INVARIANTS: -** -** {F10511} A successful evaluation of [sqlite3_complete()] or -** [sqlite3_complete16()] functions shall -** return a numeric 1 if and only if the last non-whitespace -** token in their input is a semicolon that is not in between -** the BEGIN and END of a CREATE TRIGGER statement. -** -** {F10512} If a memory allocation error occurs during an invocation -** of [sqlite3_complete()] or [sqlite3_complete16()] then the -** routine shall return [SQLITE_NOMEM]. -** -** LIMITATIONS: -** -** {A10512} The input to [sqlite3_complete()] must be a zero-terminated -** UTF-8 string. -** -** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated -** UTF-16 string in native byte order. +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); @@ -1871,27 +1288,29 @@ SQLITE_API int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} ** -** This routine sets a callback function that might be invoked whenever -** an attempt is made to open a database table that another thread -** or process has locked. -** -** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] -** is returned immediately upon encountering the lock. If the busy callback -** is not NULL, then the callback will be invoked with two arguments. -** -** The first argument to the handler is a copy of the void* pointer which -** is the third argument to sqlite3_busy_handler(). The second argument to -** the handler callback is the number of times that the busy handler has -** been invoked for this locking event. If the +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. -** If the callback returns non-zero, then another attempt +** {F12317} If the callback returns non-zero, then another attempt ** is made to open the database for reading and the cycle repeats. ** -** The presence of a busy handler does not guarantee that it will be invoked -** when there is lock contention. If SQLite determines that invoking the busy -** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] -** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying @@ -1903,118 +1322,74 @@ SQLITE_API int sqlite3_complete16(const void *sql); ** will induce the first process to release its read lock and allow ** the second process to proceed. ** -** The default busy callback is NULL. +** {F12321} The default busy callback is NULL. {END} ** -** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] ** when SQLite is in the middle of a large transaction where all the -** changes will not fit into the in-memory cache. SQLite will +** changes will not fit into the in-memory cache. {F12323} SQLite will ** already hold a RESERVED lock on the database file, but it needs ** to promote this lock to EXCLUSIVE so that it can spill cache ** pages into the database file without harm to concurrent -** readers. If it is unable to promote the lock, then the in-memory +** readers. {F12324} If it is unable to promote the lock, then the in-memory ** cache will be left in an inconsistent state and so the error ** code is promoted from the relatively benign [SQLITE_BUSY] to -** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion -** forces an automatic rollback of the changes. See the -** +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** ** CorruptionFollowingBusyError wiki page for a discussion of why ** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} ** -** There can only be a single busy handler defined for each -** [database connection]. Setting a new busy handler clears any -** previously set handler. Note that calling [sqlite3_busy_timeout()] -** will also set or clear the busy handler. +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. ** -** INVARIANTS: -** -** {F12311} The [sqlite3_busy_handler(D,C,A)] function shall replace -** busy callback in the [database connection] D with a new -** a new busy handler C and application data pointer A. -** -** {F12312} Newly created [database connections] shall have a busy -** handler of NULL. -** -** {F12314} When two or more [database connections] share a -** [sqlite3_enable_shared_cache | common cache], -** the busy handler for the database connection currently using -** the cache shall be invoked when the cache encounters a lock. -** -** {F12316} If a busy handler callback returns zero, then the SQLite interface -** that provoked the locking event shall return [SQLITE_BUSY]. -** -** {F12318} SQLite shall invokes the busy handler with two arguments which -** are a copy of the pointer supplied by the 3rd parameter to -** [sqlite3_busy_handler()] and a count of the number of prior -** invocations of the busy handler for the same locking event. -** -** LIMITATIONS: -** -** {A12319} A busy handler must not close the database connection -** or [prepared statement] that invoked the busy handler. +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. */ SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); /* ** CAPI3REF: Set A Busy Timeout {F12340} ** -** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps -** for a specified amount of time when a table is locked. The handler -** will sleep multiple times until at least "ms" milliseconds of sleeping -** have accumulated. {F12343} After "ms" milliseconds of sleeping, -** the handler returns 0 which causes [sqlite3_step()] to return -** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. ** -** Calling this routine with an argument less than or equal to zero +** {F12344} Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** -** There can only be a single busy handler for a particular -** [database connection] any any given moment. If another busy handler -** was defined (using [sqlite3_busy_handler()]) prior to calling +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared. -** -** INVARIANTS: -** -** {F12341} The [sqlite3_busy_timeout()] function shall override any prior -** [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting -** on the same [database connection]. -** -** {F12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than -** or equal to zero, then the busy handler shall be cleared so that -** all subsequent locking events immediately return [SQLITE_BUSY]. -** -** {F12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive -** number N, then a busy handler shall be set that repeatedly calls -** the xSleep() method in the [sqlite3_vfs | VFS interface] until -** either the lock clears or until the cumulative sleep time -** reported back by xSleep() exceeds N milliseconds. */ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries {F12370} ** -** Definition: A result table is memory data structure created by the -** [sqlite3_get_table()] interface. A result table records the -** complete query results from one or more queries. +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} ** -** The table conceptually has a number of rows and columns. But -** these numbers are not part of the result table itself. These -** numbers are obtained separately. Let N be the number of rows -** and M be the number of columns. -** -** A result table is an array of pointers to zero-terminated UTF-8 strings. -** There are (N+1)*M elements in the array. The first M pointers point -** to zero-terminated strings that contain the names of the columns. -** The remaining entries all point to query results. NULL values result -** in NULL pointers. All other values are in their UTF-8 zero-terminated -** string representation as returned by [sqlite3_column_text()]. -** -** A result table might consist of one or more memory allocations. -** It is not safe to pass a result table directly to [sqlite3_free()]. -** A result table should be deallocated using [sqlite3_free_table()]. -** -** As an example of the result table format, suppose a query result -** is as follows: +** As an example, suppose the query result where this table: ** **
 **        Name        | Age
@@ -2024,9 +1399,8 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
 **        Cindy       | 21
 ** 
** -** There are two column (M==2) and three rows (N==3). Thus the -** result table has 8 entries. Suppose the result table is stored -** in an array names azResult. Then azResult holds this content: +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: ** **
 **        azResult[0] = "Name";
@@ -2039,65 +1413,28 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
 **        azResult[7] = "21";
 ** 
** -** The sqlite3_get_table() function evaluates one or more -** semicolon-separated SQL statements in the zero-terminated UTF-8 -** string of its 2nd parameter. It returns a result table to the -** pointer given in its 3rd parameter. +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). ** -** After the calling function has finished using the result, it should -** pass the pointer to the result table to sqlite3_free_table() in order to -** release the memory that was malloced. Because of the way the -** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling -** function must not try to call [sqlite3_free()] directly. Only -** [sqlite3_free_table()] is able to release the memory properly and safely. +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} ** -** The sqlite3_get_table() interface is implemented as a wrapper around -** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access -** to any internal data structures of SQLite. It uses only the public -** interface defined here. As a consequence, errors that occur in the -** wrapper layer outside of the internal [sqlite3_exec()] call are not -** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()]. -** -** INVARIANTS: -** -** {F12371} If a [sqlite3_get_table()] fails a memory allocation, then -** it shall free the result table under construction, abort the -** query in process, skip any subsequent queries, set the -** *pazResult output pointer to NULL and return [SQLITE_NOMEM]. -** -** {F12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL -** then a successful invocation of [sqlite3_get_table()] shall -** write the number of columns in the -** result set of the query into *pnColumn. -** -** {F12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL -** then a successful invocation of [sqlite3_get_table()] shall -** writes the number of rows in the -** result set of the query into *pnRow. -** -** {F12376} A successful invocation of [sqlite3_get_table()] that computes -** N rows of result with C columns per row shall make *pazResult -** point to an array of pointers to (N+1)*C strings where the first -** C strings are column names as obtained from -** [sqlite3_column_name()] and the rest are column result values -** obtained from [sqlite3_column_text()]. -** -** {F12379} The values in the pazResult array returned by [sqlite3_get_table()] -** shall remain valid until cleared by [sqlite3_free_table()]. -** -** {F12382} When an error occurs during evaluation of [sqlite3_get_table()] -** the function shall set *pazResult to NULL, write an error message -** into memory obtained from [sqlite3_malloc()], make -** **pzErrmsg point to that error message, and return a -** appropriate [error code]. +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. */ SQLITE_API int sqlite3_get_table( - sqlite3 *db, /* An open database */ - const char *zSql, /* SQL to be evaluated */ - char ***pazResult, /* Results of the query */ - int *pnRow, /* Number of result rows written here */ - int *pnColumn, /* Number of result columns written here */ - char **pzErrmsg /* Error msg written here */ + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ ); SQLITE_API void sqlite3_free_table(char **result); @@ -2107,44 +1444,44 @@ SQLITE_API void sqlite3_free_table(char **result); ** These routines are workalikes of the "printf()" family of functions ** from the standard C library. ** -** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. -** The strings returned by these two routines should be -** released by [sqlite3_free()]. Both routines return a +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** -** In sqlite3_snprintf() routine is similar to "snprintf()" from +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by -** the first parameter. Note that the order of the +** the first parameter. {END} Note that the order of the ** first two parameters is reversed from snprintf(). This is an ** historical accident that cannot be fixed without breaking -** backwards compatibility. Note also that sqlite3_snprintf() +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. We admit that +** characters actually written into the buffer. {END} We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** -** As long as the buffer size is greater than zero, sqlite3_snprintf() -** guarantees that the buffer is always zero-terminated. The first +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first ** parameter "n" is the total size of the buffer, including space for -** the zero terminator. So the longest string that can be completely +** the zero terminator. {END} So the longest string that can be completely ** written will be n-1 characters. ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. -** All of the usual printf() formatting options apply. In addition, there +** All of the usual printf formatting options apply. In addition, there ** is are "%q", "%Q", and "%z" options. ** -** The %q option works like %s in that it substitutes a null-terminated +** {F17410} The %q option works like %s in that it substitutes a null-terminated ** string from the argument list. But %q also doubles every '\'' character. -** %q is designed for use inside a string literal. By doubling each '\'' +** %q is designed for use inside a string literal. {END} By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** -** For example, assume the string variable zText contains text as follows: +** For example, so some string variable contains text as follows: ** **
 **  char *zText = "It's a happy day!";
@@ -2172,13 +1509,14 @@ SQLITE_API void sqlite3_free_table(char **result);
 **  INSERT INTO table1 VALUES('It's a happy day!');
 ** 
** -** This second example is an SQL syntax error. As a general rule you should -** always use %q instead of %s when inserting text into a string literal. +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. ** -** The %Q option works like %q except it also adds single quotes around -** the outside of the total string. Additionally, if the parameter in the -** argument list is a NULL pointer, %Q substitutes the text "NULL" (without -** single quotes) in place of the %Q option. So, for example, one could say: +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: ** **
 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
@@ -2189,26 +1527,9 @@ SQLITE_API void sqlite3_free_table(char **result);
 ** The code above will render a correct SQL statement in the zSQL
 ** variable even if the zText variable is a NULL pointer.
 **
-** The "%z" formatting option works exactly like "%s" with the
+** {F17412} The "%z" formatting option works exactly like "%s" with the
 ** addition that after the string has been read and copied into
 ** the result, [sqlite3_free()] is called on the input string. {END}
-**
-** INVARIANTS:
-**
-** {F17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
-**           return either pointers to zero-terminated UTF-8 strings held in
-**           memory obtained from [sqlite3_malloc()] or NULL pointers if
-**           a call to [sqlite3_malloc()] fails.
-**
-** {F17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
-**           UTF-8 string into the buffer pointed to by the second parameter
-**           provided that the first parameter is greater than zero.
-**
-** {F17407}  The [sqlite3_snprintf()] interface does not write slots of
-**           its output buffer (the second parameter) outside the range
-**           of 0 through N-1 (where N is the first parameter)
-**           regardless of the length of the string
-**           requested by the format specification.
 */
 SQLITE_API char *sqlite3_mprintf(const char*,...);
 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
@@ -2217,122 +1538,74 @@ SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
 /*
 ** CAPI3REF: Memory Allocation Subsystem {F17300}
 **
-** The SQLite core  uses these three routines for all of its own
-** internal memory allocation needs. "Core" in the previous sentence
+** {F17301} The SQLite core  uses these three routines for all of its own
+** internal memory allocation needs. {END}  "Core" in the previous sentence
 ** does not include operating-system specific VFS implementation.  The
-** Windows VFS uses native malloc() and free() for some operations.
+** windows VFS uses native malloc and free for some operations.
 **
-** The sqlite3_malloc() routine returns a pointer to a block
+** {F17302} The sqlite3_malloc() routine returns a pointer to a block
 ** of memory at least N bytes in length, where N is the parameter.
-** If sqlite3_malloc() is unable to obtain sufficient free
-** memory, it returns a NULL pointer.  If the parameter N to
+** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
+** memory, it returns a NULL pointer.  {F17304} If the parameter N to
 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
 ** a NULL pointer.
 **
-** Calling sqlite3_free() with a pointer previously returned
+** {F17305} Calling sqlite3_free() with a pointer previously returned
 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
-** that it might be reused.  The sqlite3_free() routine is
+** that it might be reused.  {F17306} The sqlite3_free() routine is
 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
-** to sqlite3_free() is harmless.  After being freed, memory
+** to sqlite3_free() is harmless.  {U17307} After being freed, memory
 ** should neither be read nor written.  Even reading previously freed
 ** memory might result in a segmentation fault or other severe error.
-** Memory corruption, a segmentation fault, or other severe error
+** {U17309} Memory corruption, a segmentation fault, or other severe error
 ** might result if sqlite3_free() is called with a non-NULL pointer that
 ** was not obtained from sqlite3_malloc() or sqlite3_free().
 **
-** The sqlite3_realloc() interface attempts to resize a
+** {F17310} The sqlite3_realloc() interface attempts to resize a
 ** prior memory allocation to be at least N bytes, where N is the
 ** second parameter.  The memory allocation to be resized is the first
-** parameter.  If the first parameter to sqlite3_realloc()
+** parameter.  {F17311} If the first parameter to sqlite3_realloc()
 ** is a NULL pointer then its behavior is identical to calling
 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
-** If the second parameter to sqlite3_realloc() is zero or
+** {F17312} If the second parameter to sqlite3_realloc() is zero or
 ** negative then the behavior is exactly the same as calling
 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
-** sqlite3_realloc() returns a pointer to a memory allocation
+** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
-** If M is the size of the prior allocation, then min(N,M) bytes
+** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
 ** of the prior allocation are copied into the beginning of buffer returned
 ** by sqlite3_realloc() and the prior allocation is freed.
-** If sqlite3_realloc() returns NULL, then the prior allocation
+** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
 ** is not freed.
 **
-** The memory returned by sqlite3_malloc() and sqlite3_realloc()
+** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
 ** is always aligned to at least an 8 byte boundary. {END}
 **
-** The default implementation of the memory allocation subsystem uses
-** the malloc(), realloc() and free() provided by the standard C library.
-** {F17382} However, if SQLite is compiled with the
-** SQLITE_MEMORY_SIZE=NNN C preprocessor macro (where NNN
-** is an integer), then SQLite create a static array of at least
-** NNN bytes in size and uses that array for all of its dynamic
-** memory allocation needs. {END}  Additional memory allocator options
-** may be added in future releases.
+** {F17381} The default implementation
+** of the memory allocation subsystem uses the malloc(), realloc()
+** and free() provided by the standard C library. {F17382} However, if 
+** SQLite is compiled with the following C preprocessor macro
+**
+** 
SQLITE_MEMORY_SIZE=NNN
+** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability -** is no longer provided. Only built-in memory allocators can be used. +** is no longer provided. Only built-in memory allocators can be +** used. ** -** The Windows OS interface layer calls +** The windows OS interface layer calls ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite -** and whatever filename encoding is used by the particular Windows +** and whatever filename encoding is used by the particular windows ** installation. Memory allocation errors are detected, but ** they are reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. -** -** INVARIANTS: -** -** {F17303} The [sqlite3_malloc(N)] interface returns either a pointer to -** a newly checked-out block of at least N bytes of memory -** that is 8-byte aligned, or it returns NULL if it is unable -** to fulfill the request. -** -** {F17304} The [sqlite3_malloc(N)] interface returns a NULL pointer if -** N is less than or equal to zero. -** -** {F17305} The [sqlite3_free(P)] interface releases memory previously -** returned from [sqlite3_malloc()] or [sqlite3_realloc()], -** making it available for reuse. -** -** {F17306} A call to [sqlite3_free(NULL)] is a harmless no-op. -** -** {F17310} A call to [sqlite3_realloc(0,N)] is equivalent to a call -** to [sqlite3_malloc(N)]. -** -** {F17312} A call to [sqlite3_realloc(P,0)] is equivalent to a call -** to [sqlite3_free(P)]. -** -** {F17315} The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()], -** and [sqlite3_free()] for all of its memory allocation and -** deallocation needs. -** -** {F17318} The [sqlite3_realloc(P,N)] interface returns either a pointer -** to a block of checked-out memory of at least N bytes in size -** that is 8-byte aligned, or a NULL pointer. -** -** {F17321} When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first -** copies the first K bytes of content from P into the newly -** allocated block, where K is the lesser of N and the size of -** the buffer P. -** -** {F17322} When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first -** releases the buffer P. -** -** {F17323} When [sqlite3_realloc(P,N)] returns NULL, the buffer P is -** not modified or released. -** -** LIMITATIONS: -** -** {A17350} The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] -** must be either NULL or else pointers obtained from a prior -** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have -** not yet been released. -** -** {A17351} The application must not read or write any part of -** a block of memory after it has been released using -** [sqlite3_free()] or [sqlite3_realloc()]. */ SQLITE_API void *sqlite3_malloc(int); SQLITE_API void *sqlite3_realloc(void*, int); @@ -2341,173 +1614,94 @@ SQLITE_API void sqlite3_free(void*); /* ** CAPI3REF: Memory Allocator Statistics {F17370} ** -** SQLite provides these two interfaces for reporting on the status -** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] -** routines, which form the built-in memory allocation subsystem. +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. ** -** INVARIANTS: -** -** {F17371} The [sqlite3_memory_used()] routine returns the number of bytes -** of memory currently outstanding (malloced but not freed). -** -** {F17373} The [sqlite3_memory_highwater()] routine returns the maximum -** value of [sqlite3_memory_used()] since the high-water mark -** was last reset. -** -** {F17374} The values returned by [sqlite3_memory_used()] and -** [sqlite3_memory_highwater()] include any overhead -** added by SQLite in its implementation of [sqlite3_malloc()], -** but not overhead added by the any underlying system library -** routines that [sqlite3_malloc()] may call. -** -** {F17375} The memory high-water mark is reset to the current value of -** [sqlite3_memory_used()] if and only if the parameter to -** [sqlite3_memory_highwater()] is true. The value returned -** by [sqlite3_memory_highwater(1)] is the high-water mark -** prior to the reset. +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void); SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); -/* -** CAPI3REF: Pseudo-Random Number Generator {F17390} -** -** SQLite contains a high-quality pseudo-random number generator (PRNG) used to -** select random ROWIDs when inserting new records into a table that -** already uses the largest possible ROWID. The PRNG is also used for -** the build-in random() and randomblob() SQL functions. This interface allows -** applications to access the same PRNG for other purposes. -** -** A call to this routine stores N bytes of randomness into buffer P. -** -** The first time this routine is invoked (either internally or by -** the application) the PRNG is seeded using randomness obtained -** from the xRandomness method of the default [sqlite3_vfs] object. -** On all subsequent invocations, the pseudo-randomness is generated -** internally and without recourse to the [sqlite3_vfs] xRandomness -** method. -** -** INVARIANTS: -** -** {F17392} The [sqlite3_randomness(N,P)] interface writes N bytes of -** high-quality pseudo-randomness into buffer P. -*/ -SQLITE_API void sqlite3_randomness(int N, void *P); - /* ** CAPI3REF: Compile-Time Authorization Callbacks {F12500} ** -** This routine registers a authorizer callback with a particular -** [database connection], supplied in the first argument. +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} ** The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], -** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. The authorizer callback should -** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be -** rejected with an error. If the authorizer callback returns +** rejected with an error. {F12504} If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] -** then the [sqlite3_prepare_v2()] or equivalent call that triggered -** the authorizer will fail with an error message. +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} ** ** When the callback returns [SQLITE_OK], that means the operation -** requested is ok. When the callback returns [SQLITE_DENY], the +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the -** authorizer will fail with an error message explaining that -** access is denied. If the authorizer code is [SQLITE_READ] -** and the callback returns [SQLITE_IGNORE] then the -** [prepared statement] statement is constructed to substitute -** a NULL value in place of the table column that would have -** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] -** return can be used to deny an untrusted user access to individual -** columns of a table. +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} ** -** The first parameter to the authorizer callback is a copy of the third -** parameter to the sqlite3_set_authorizer() interface. The second parameter -** to the callback is an integer [SQLITE_COPY | action code] that specifies -** the particular action to be authorized. The third through sixth parameters -** to the callback are zero-terminated strings that contain additional -** details about the action to be authorized. +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} ** -** An authorizer is used when [sqlite3_prepare | preparing] -** SQL statements from an untrusted source, to ensure that the SQL statements -** do not try to access data they are not allowed to see, or that they do not -** try to execute malicious statements that damage the database. For +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the -** user-entered SQL is being [sqlite3_prepare | prepared] that -** disallows everything except [SELECT] statements. +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. ** -** Applications that need to process SQL from untrusted sources -** might also consider lowering resource limits using [sqlite3_limit()] -** and limiting database size using the [max_page_count] [PRAGMA] -** in addition to using an authorizer. -** -** Only a single authorizer can be in place on a database connection +** {F12520} Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the -** previous call. Disable the authorizer by installing a NULL callback. -** The authorizer is disabled by default. +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} ** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -** -** INVARIANTS: -** -** {F12501} The [sqlite3_set_authorizer(D,...)] interface registers a -** authorizer callback with database connection D. -** -** {F12502} The authorizer callback is invoked as SQL statements are -** being compiled. -** -** {F12503} If the authorizer callback returns any value other than -** [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then -** the [sqlite3_prepare_v2()] or equivalent call that caused -** the authorizer callback to run shall fail with an -** [SQLITE_ERROR] error code and an appropriate error message. -** -** {F12504} When the authorizer callback returns [SQLITE_OK], the operation -** described is processed normally. -** -** {F12505} When the authorizer callback returns [SQLITE_DENY], the -** [sqlite3_prepare_v2()] or equivalent call that caused the -** authorizer callback to run shall fail -** with an [SQLITE_ERROR] error code and an error message -** explaining that access is denied. -** -** {F12506} If the authorizer code (the 2nd parameter to the authorizer -** callback) is [SQLITE_READ] and the authorizer callback returns -** [SQLITE_IGNORE], then the prepared statement is constructed to -** insert a NULL value in place of the table column that would have -** been read if [SQLITE_OK] had been returned. -** -** {F12507} If the authorizer code (the 2nd parameter to the authorizer -** callback) is anything other than [SQLITE_READ], then -** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. -** -** {F12510} The first parameter to the authorizer callback is a copy of -** the third parameter to the [sqlite3_set_authorizer()] interface. -** -** {F12511} The second parameter to the callback is an integer -** [SQLITE_COPY | action code] that specifies the particular action -** to be authorized. -** -** {F12512} The third through sixth parameters to the callback are -** zero-terminated strings that contain -** additional details about the action to be authorized. -** -** {F12520} Each call to [sqlite3_set_authorizer()] overrides -** any previously installed authorizer. -** -** {F12521} A NULL authorizer means that no authorization -** callback is invoked. -** -** {F12522} The default authorizer is NULL. +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, @@ -2531,42 +1725,20 @@ SQLITE_API int sqlite3_set_authorizer( ** CAPI3REF: Authorizer Action Codes {F12550} ** ** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorize certain SQL statement actions. The +** that is invoked to authorizer certain SQL statement actions. {F12551} The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that -** the authorizer callback may be passed. +** the authorizer callback may be passed. {END} ** -** These action code values signify what kind of operation is to be -** authorized. The 3rd and 4th parameters to the authorization +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these -** codes is used as the second parameter. The 5th parameter to the -** authorizer callback is the name of the database ("main", "temp", -** etc.) if applicable. The 6th parameter to the authorizer callback +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for -** the access attempt or NULL if this access attempt is directly from +** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. -** -** INVARIANTS: -** -** {F12551} The second parameter to an -** [sqlite3_set_authorizer | authorizer callback] is always an integer -** [SQLITE_COPY | authorizer code] that specifies what action -** is being authorized. -** -** {F12552} The 3rd and 4th parameters to the -** [sqlite3_set_authorizer | authorization callback] -** will be parameters or NULL depending on which -** [SQLITE_COPY | authorizer code] is used as the second parameter. -** -** {F12553} The 5th parameter to the -** [sqlite3_set_authorizer | authorizer callback] is the name -** of the database (example: "main", "temp", etc.) if applicable. -** -** {F12554} The 6th parameter to the -** [sqlite3_set_authorizer | authorizer callback] is the name -** of the inner-most trigger or view that is responsible for -** the access attempt or NULL if this access attempt is directly from -** top-level SQL code. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ @@ -2608,60 +1780,31 @@ SQLITE_API int sqlite3_set_authorizer( ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** -** The callback function registered by sqlite3_trace() is invoked at -** various times when an SQL statement is being run by [sqlite3_step()]. -** The callback returns a UTF-8 rendering of the SQL statement text -** as the statement first begins executing. Additional callbacks occur -** as each triggered subprogram is entered. The callbacks for triggers -** contain a UTF-8 SQL comment that identifies the trigger. +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. ** -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes. The profile callback contains -** the original statement text and an estimate of wall-clock time -** of how long that statement took to run. +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} ** ** The sqlite3_profile() API is currently considered experimental and -** is subject to change or removal in a future release. -** -** The trigger reporting feature of the trace callback is considered -** experimental and is subject to change or removal in future releases. -** Future versions of SQLite might also add new trace callback -** invocations. -** -** INVARIANTS: -** -** {F12281} The callback function registered by [sqlite3_trace()] is -** whenever an SQL statement first begins to execute and -** whenever a trigger subprogram first begins to run. -** -** {F12282} Each call to [sqlite3_trace()] overrides the previously -** registered trace callback. -** -** {F12283} A NULL trace callback disables tracing. -** -** {F12284} The first argument to the trace callback is a copy of -** the pointer which was the 3rd argument to [sqlite3_trace()]. -** -** {F12285} The second argument to the trace callback is a -** zero-terminated UTF-8 string containing the original text -** of the SQL statement as it was passed into [sqlite3_prepare_v2()] -** or the equivalent, or an SQL comment indicating the beginning -** of a trigger subprogram. -** -** {F12287} The callback function registered by [sqlite3_profile()] is invoked -** as each SQL statement finishes. -** -** {F12288} The first parameter to the profile callback is a copy of -** the 3rd parameter to [sqlite3_profile()]. -** -** {F12289} The second parameter to the profile callback is a -** zero-terminated UTF-8 string that contains the complete text of -** the SQL statement as it was processed by [sqlite3_prepare_v2()] -** or the equivalent. -** -** {F12290} The third parameter to the profile callback is an estimate -** of the number of nanoseconds of wall-clock time required to -** run the SQL statement from start to finish. +** is subject to change. */ SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); SQLITE_API void *sqlite3_profile(sqlite3*, @@ -2670,196 +1813,111 @@ SQLITE_API void *sqlite3_profile(sqlite3*, /* ** CAPI3REF: Query Progress Callbacks {F12910} ** -** This routine configures a callback function - the +** {F12911} This routine configures a callback function - the ** progress callback - that is invoked periodically during long ** running calls to [sqlite3_exec()], [sqlite3_step()] and -** [sqlite3_get_table()]. An example use for this +** [sqlite3_get_table()]. {END} An example use for this ** interface is to keep a GUI updated during a large query. ** -** If the progress callback returns non-zero, the operation is -** interrupted. This feature can be used to implement a -** "Cancel" button on a GUI dialog box. -** -** INVARIANTS: -** -** {F12911} The callback function registered by sqlite3_progress_handler() -** is invoked periodically during long running calls to -** [sqlite3_step()]. -** ** {F12912} The progress callback is invoked once for every N virtual -** machine opcodes, where N is the second argument to -** the [sqlite3_progress_handler()] call that registered -** the callback. If N is less than 1, sqlite3_progress_handler() -** acts as if a NULL progress handler had been specified. -** +** machine opcodes, where N is the second argument to this function. ** {F12913} The progress callback itself is identified by the third -** argument to sqlite3_progress_handler(). +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} ** -** {F12914} The fourth argument to sqlite3_progress_handler() is a -** void pointer passed to the progress callback -** function each time it is invoked. -** -** {F12915} If a call to [sqlite3_step()] results in fewer than N opcodes -** being executed, then the progress callback is never invoked. -** -** {F12916} Every call to [sqlite3_progress_handler()] -** overwrites any previously registered progress handler. -** -** {F12917} If the progress handler callback is NULL then no progress -** handler is invoked. +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} ** ** {F12918} If the progress callback returns a result other than 0, then -** the behavior is a if [sqlite3_interrupt()] had been called. +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. */ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection {F12700} ** -** These routines open an SQLite database file whose name is given by the -** filename argument. The filename argument is interpreted as UTF-8 for -** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte -** order for sqlite3_open16(). A [database connection] handle is usually -** returned in *ppDb, even if an error occurs. The only exception is that -** if SQLite is unable to allocate memory to hold the [sqlite3] object, -** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] -** object. If the database is opened (and/or created) successfully, then -** [SQLITE_OK] is returned. Otherwise an [error code] is returned. The -** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error. ** -** The default encoding for the database will be UTF-8 if -** sqlite3_open() or sqlite3_open_v2() is called and -** UTF-16 in the native byte order if sqlite3_open16() is used. +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. ** -** Whether or not an error occurs when it is opened, resources -** associated with the [database connection] handle should be released by -** passing it to [sqlite3_close()] when it is no longer required. +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. ** -** The sqlite3_open_v2() interface works like sqlite3_open() -** except that it accepts two additional parameters for additional control -** over the new database connection. The flags parameter can take one of -** the following three values, optionally combined with the -** [SQLITE_OPEN_NOMUTEX] flag: +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: ** -**
-**
[SQLITE_OPEN_READONLY]
-**
The database is opened in read-only mode. If the database does not -** already exist, an error is returned.
+**
    +**
  1. [SQLITE_OPEN_READONLY] +**
  2. [SQLITE_OPEN_READWRITE] +**
  3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
** -**
[SQLITE_OPEN_READWRITE]
-**
The database is opened for reading and writing if possible, or reading -** only if the file is write protected by the operating system. In either -** case the database must already exist, otherwise an error is returned.
+** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. ** -**
[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
-**
The database is opened for reading and writing, and is creates it if -** it does not already exist. This is the behavior that is always used for -** sqlite3_open() and sqlite3_open16().
-**
+** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. ** -** If the 3rd parameter to sqlite3_open_v2() is not one of the -** combinations shown above or one of the combinations shown above combined -** with the [SQLITE_OPEN_NOMUTEX] flag, then the behavior is undefined. -** -** If the [SQLITE_OPEN_NOMUTEX] flag is set, then mutexes on the -** opened [database connection] are disabled and the appliation must -** insure that access to the [database connection] and its associated -** [prepared statements] is serialized. The [SQLITE_OPEN_NOMUTEX] flag -** is the default behavior is SQLite is configured using the -** [SQLITE_CONFIG_MULTITHREAD] or [SQLITE_CONFIG_SINGLETHREAD] options -** to [sqlite3_config()]. The [SQLITE_OPEN_NOMUTEX] flag only makes a -** difference when SQLite is in its default [SQLITE_CONFIG_SERIALIZED] mode. -** -** If the filename is ":memory:", then a private, temporary in-memory database -** is created for the connection. This in-memory database will vanish when -** the database connection is closed. Future versions of SQLite might -** make use of additional special filenames that begin with the ":" character. -** It is recommended that when a database filename actually does begin with -** a ":" character you should prefix the filename with a pathname such as -** "./" to avoid ambiguity. -** -** If the filename is an empty string, then a private, temporary -** on-disk database will be created. This private database will be +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be ** automatically deleted as soon as the database connection is closed. ** -** The fourth parameter to sqlite3_open_v2() is the name of the -** [sqlite3_vfs] object that defines the operating system interface that -** the new database connection should use. If the fourth parameter is -** a NULL pointer then the default [sqlite3_vfs] object is used. +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} ** -** Note to Windows users: The encoding used for the filename argument -** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into -** sqlite3_open() or sqlite3_open_v2(). -** -** INVARIANTS: -** -** {F12701} The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces create a new -** [database connection] associated with -** the database file given in their first parameter. -** -** {F12702} The filename argument is interpreted as UTF-8 -** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 -** in the native byte order for [sqlite3_open16()]. -** -** {F12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] writes a pointer to a new -** [database connection] into *ppDb. -** -** {F12704} The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success, -** or an appropriate [error code] on failure. -** -** {F12706} The default text encoding for a new database created using -** [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8. -** -** {F12707} The default text encoding for a new database created using -** [sqlite3_open16()] will be UTF-16. -** -** {F12709} The [sqlite3_open(F,D)] interface is equivalent to -** [sqlite3_open_v2(F,D,G,0)] where the G parameter is -** [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE]. -** -** {F12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the -** bit value [SQLITE_OPEN_READONLY] then the database is opened -** for reading only. -** -** {F12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the -** bit value [SQLITE_OPEN_READWRITE] then the database is opened -** reading and writing if possible, or for reading only if the -** file is write protected by the operating system. -** -** {F12713} If the G parameter to [sqlite3_open(v2(F,D,G,V)] omits the -** bit value [SQLITE_OPEN_CREATE] and the database does not -** previously exist, an error is returned. -** -** {F12714} If the G parameter to [sqlite3_open(v2(F,D,G,V)] contains the -** bit value [SQLITE_OPEN_CREATE] and the database does not -** previously exist, then an attempt is made to create and -** initialize the database. -** -** {F12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] is ":memory:", then an private, -** ephemeral, in-memory database is created for the connection. -** Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required -** in sqlite3_open_v2()? -** -** {F12719} If the filename is NULL or an empty string, then a private, -** ephemeral on-disk database will be created. -** Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required -** in sqlite3_open_v2()? -** -** {F12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)] -** will use the [sqlite3_vfs] object identified by the V parameter, -** or the default [sqlite3_vfs] object if V is a NULL pointer. -** -** {F12723} Two [database connections] will share a common cache if both were -** opened with the same VFS while [shared cache mode] was enabled and -** if both filenames compare equal using memcmp() after having been -** processed by the [sqlite3_vfs | xFullPathname] method of the VFS. +** [sqlite3_open()] or [sqlite3_open_v2()]. */ SQLITE_API int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ @@ -2879,47 +1937,35 @@ SQLITE_API int sqlite3_open_v2( /* ** CAPI3REF: Error Codes And Messages {F12800} ** -** The sqlite3_errcode() interface returns the numeric [result code] or -** [extended result code] for the most recent failed sqlite3_* API call -** associated with a [database connection]. If a prior API call failed -** but the most recent API call succeeded, the return value from -** sqlite3_errcode() is undefined. +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} ** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF-8 or UTF-16 respectively. -** Memory to hold the error message string is managed internally. -** The application does not need to worry about freeing the result. -** However, the error string might be overwritten or deallocated by -** subsequent calls to other SQLite interface functions. +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} ** -** If an interface fails with SQLITE_MISUSE, that means the interface -** was invoked incorrectly by the application. In that case, the -** error code and message may or may not be set. +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} ** -** INVARIANTS: -** -** {F12801} The [sqlite3_errcode(D)] interface returns the numeric -** [result code] or [extended result code] for the most recently -** failed interface call associated with the [database connection] D. -** -** {F12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)] -** interfaces return English-language text that describes -** the error in the mostly recently failed interface call, -** encoded as either UTF-8 or UTF-16 respectively. -** -** {F12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()] -** are valid until the next SQLite interface call. -** -** {F12808} Calls to API routines that do not return an error code -** (example: [sqlite3_data_count()]) do not -** change the error code or message returned by -** [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()]. -** -** {F12809} Interfaces that are not associated with a specific -** [database connection] (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] -** do not change the values returned by -** [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()]. +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. */ SQLITE_API int sqlite3_errcode(sqlite3 *db); SQLITE_API const char *sqlite3_errmsg(sqlite3*); @@ -2927,19 +1973,18 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3*); /* ** CAPI3REF: SQL Statement Object {F13000} -** KEYWORDS: {prepared statement} {prepared statements} ** -** An instance of this object represents a single SQL statement. -** This object is variously known as a "prepared statement" or a +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a ** "compiled SQL statement" or simply as a "statement". -** +** ** The life of a statement object goes something like this: ** **
    **
  1. Create the object using [sqlite3_prepare_v2()] or a related ** function. -**
  2. Bind values to [host parameters] using the sqlite3_bind_*() -** interfaces. +**
  3. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. **
  4. Run the SQL by calling [sqlite3_step()] one or more times. **
  5. Reset the statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. @@ -2951,214 +1996,78 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3*); */ typedef struct sqlite3_stmt sqlite3_stmt; -/* -** CAPI3REF: Run-time Limits {F12760} -** -** This interface allows the size of various constructs to be limited -** on a connection by connection basis. The first parameter is the -** [database connection] whose limit is to be set or queried. The -** second parameter is one of the [limit categories] that define a -** class of constructs to be size limited. The third parameter is the -** new limit for that construct. The function returns the old limit. -** -** If the new limit is a negative number, the limit is unchanged. -** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper -** bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ. -** (The "_LIMIT_" in the name is changed to "_MAX_".) -** Attempts to increase a limit above its hard upper bound are -** silently truncated to the hard upper limit. -** -** Run time limits are intended for use in applications that manage -** both their own internal database and also databases that are controlled -** by untrusted external sources. An example application might be a -** webbrowser that has its own databases for storing history and -** separate databases controlled by JavaScript applications downloaded -** off the Internet. The internal databases can be given the -** large, default limits. Databases managed by external sources can -** be given much smaller limits designed to prevent a denial of service -** attack. Developers might also want to use the [sqlite3_set_authorizer()] -** interface to further control untrusted SQL. The size of the database -** created by an untrusted script can be contained using the -** [max_page_count] [PRAGMA]. -** -** New run-time limit categories may be added in future releases. -** -** INVARIANTS: -** -** {F12762} A successful call to [sqlite3_limit(D,C,V)] where V is -** positive changes the limit on the size of construct C in the -** [database connection] D to the lesser of V and the hard upper -** bound on the size of C that is set at compile-time. -** -** {F12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative -** leaves the state of the [database connection] D unchanged. -** -** {F12769} A successful call to [sqlite3_limit(D,C,V)] returns the -** value of the limit on the size of construct C in the -** [database connection] D as it was prior to the call. -*/ -SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal); - -/* -** CAPI3REF: Run-Time Limit Categories {F12790} -** KEYWORDS: {limit category} {limit categories} -** -** These constants define various aspects of a [database connection] -** that can be limited in size by calls to [sqlite3_limit()]. -** The meanings of the various limits are as follows: -** -**
    -**
    SQLITE_LIMIT_LENGTH
    -**
    The maximum size of any string or BLOB or table row.
    -** -**
    SQLITE_LIMIT_SQL_LENGTH
    -**
    The maximum length of an SQL statement.
    -** -**
    SQLITE_LIMIT_COLUMN
    -**
    The maximum number of columns in a table definition or in the -** result set of a SELECT or the maximum number of columns in an index -** or in an ORDER BY or GROUP BY clause.
    -** -**
    SQLITE_LIMIT_EXPR_DEPTH
    -**
    The maximum depth of the parse tree on any expression.
    -** -**
    SQLITE_LIMIT_COMPOUND_SELECT
    -**
    The maximum number of terms in a compound SELECT statement.
    -** -**
    SQLITE_LIMIT_VDBE_OP
    -**
    The maximum number of instructions in a virtual machine program -** used to implement an SQL statement.
    -** -**
    SQLITE_LIMIT_FUNCTION_ARG
    -**
    The maximum number of arguments on a function.
    -** -**
    SQLITE_LIMIT_ATTACHED
    -**
    The maximum number of attached databases.
    -** -**
    SQLITE_LIMIT_LIKE_PATTERN_LENGTH
    -**
    The maximum length of the pattern argument to the LIKE or -** GLOB operators.
    -** -**
    SQLITE_LIMIT_VARIABLE_NUMBER
    -**
    The maximum number of variables in an SQL statement that can -** be bound.
    -**
    -*/ -#define SQLITE_LIMIT_LENGTH 0 -#define SQLITE_LIMIT_SQL_LENGTH 1 -#define SQLITE_LIMIT_COLUMN 2 -#define SQLITE_LIMIT_EXPR_DEPTH 3 -#define SQLITE_LIMIT_COMPOUND_SELECT 4 -#define SQLITE_LIMIT_VDBE_OP 5 -#define SQLITE_LIMIT_FUNCTION_ARG 6 -#define SQLITE_LIMIT_ATTACHED 7 -#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 -#define SQLITE_LIMIT_VARIABLE_NUMBER 9 - /* ** CAPI3REF: Compiling An SQL Statement {F13010} -** KEYWORDS: {SQL statement compiler} ** ** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. +** program using one of these routines. ** -** The first argument, "db", is a [database connection] obtained from a -** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()]. -** -** The second argument, "zSql", is the statement to be compiled, encoded +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() -** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() -** use UTF-16. +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} ** -** If the nByte argument is less than zero, then zSql is read up to the -** first zero terminator. If nByte is non-negative, then it is the maximum -** number of bytes read from zSql. When nByte is non-negative, the -** zSql string ends at either the first '\000' or '\u0000' character or -** the nByte-th byte, whichever comes first. If the caller knows -** that the supplied string is nul-terminated, then there is a small -** performance advantage to be gained by passing an nByte parameter that -** is equal to the number of bytes in the input string including -** the nul-terminator bytes. +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} ** -** *pzTail is made to point to the first byte past the end of the -** first SQL statement in zSql. These routines only compile the first +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first ** statement in zSql, so *pzTail is left pointing to what remains -** uncompiled. +** uncompiled. {END} ** -** *ppStmt is left pointing to a compiled [prepared statement] that can be -** executed using [sqlite3_step()]. If there is an error, *ppStmt is set -** to NULL. If the input text contains no SQL (if the input is an empty -** string or a comment) then *ppStmt is set to NULL. -** {A13018} The calling procedure is responsible for deleting the compiled -** SQL statement using [sqlite3_finalize()] after it has finished with it. +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. ** -** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned. +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. -** In the "v2" interfaces, the prepared statement -** that is returned (the [sqlite3_stmt] object) contains a copy of the -** original SQL text. This causes the [sqlite3_step()] interface to +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to ** behave a differently in two ways: ** **
      -**
    1. +**
    2. {F13022} ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL -** statement and try to run it again. If the schema has changed in +** statement and try to run it again. {F12023} If the schema has changed in ** a way that makes the statement no longer valid, [sqlite3_step()] will still -** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is -** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the -** error go away. Note: use [sqlite3_errmsg()] to find the text -** of the parsing error that results in an [SQLITE_SCHEMA] return. +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} **
    3. ** **
    4. -** When an error occurs, [sqlite3_step()] will return one of the detailed -** [error codes] or [extended error codes]. The legacy behavior was that -** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code -** and you would have to make a second call to [sqlite3_reset()] in order -** to find the underlying cause of the problem. With the "v2" prepare -** interfaces, the underlying reason for the error is returned immediately. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} **
    5. **
    -** -** INVARIANTS: -** -** {F13011} The [sqlite3_prepare(db,zSql,...)] and -** [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the -** text in their zSql parameter as UTF-8. -** -** {F13012} The [sqlite3_prepare16(db,zSql,...)] and -** [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the -** text in their zSql parameter as UTF-16 in the native byte order. -** -** {F13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)] -** and its variants is less than zero, the SQL text is -** read from zSql is read up to the first zero terminator. -** -** {F13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)] -** and its variants is non-negative, then at most nBytes bytes of -** SQL text is read from zSql. -** -** {F13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants -** if the zSql input text contains more than one SQL statement -** and pzTail is not NULL, then *pzTail is made to point to the -** first byte past the end of the first SQL statement in zSql. -** What does *pzTail point to if there is one statement? -** -** {F13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)] -** or one of its variants writes into *ppStmt a pointer to a new -** [prepared statement] or a pointer to NULL if zSql contains -** nothing other than whitespace or comments. -** -** {F13019} The [sqlite3_prepare_v2()] interface and its variants return -** [SQLITE_OK] or an appropriate [error code] upon failure. -** -** {F13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its -** variants returns an error (any value other than [SQLITE_OK]), -** they first set *ppStmt to NULL. */ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle */ @@ -3192,232 +2101,117 @@ SQLITE_API int sqlite3_prepare16_v2( /* ** CAPIREF: Retrieving Statement SQL {F13100} ** -** This interface can be used to retrieve a saved copy of the original -** SQL text used to create a [prepared statement] if that statement was -** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. ** -** INVARIANTS: -** -** {F13101} If the [prepared statement] passed as the argument to -** [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns -** a pointer to a zero-terminated string containing a UTF-8 rendering -** of the original SQL statement. -** -** {F13102} If the [prepared statement] passed as the argument to -** [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or -** [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer. -** -** {F13103} The string returned by [sqlite3_sql(S)] is valid until the -** [prepared statement] S is deleted using [sqlite3_finalize(S)]. +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); /* -** CAPI3REF: Dynamically Typed Value Object {F15000} -** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** CAPI3REF: Dynamically Typed Value Object {F15000} ** -** SQLite uses the sqlite3_value object to represent all values -** that can be stored in a database table. SQLite uses dynamic typing -** for the values it stores. Values stored in sqlite3_value objects -** can be integers, floating point values, strings, BLOBs, or NULL. -** -** An sqlite3_value object may be either "protected" or "unprotected". -** Some interfaces require a protected sqlite3_value. Other interfaces -** will accept either a protected or an unprotected sqlite3_value. -** Every interface that accepts sqlite3_value arguments specifies -** whether or not it requires a protected sqlite3_value. -** -** The terms "protected" and "unprotected" refer to whether or not -** a mutex is held. A internal mutex is held for a protected -** sqlite3_value object but no mutex is held for an unprotected -** sqlite3_value object. If SQLite is compiled to be single-threaded -** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) -** or if SQLite is run in one of reduced mutex modes -** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] -** then there is no distinction between protected and unprotected -** sqlite3_value objects and they can be used interchangeably. However, -** for maximum code portability it is recommended that applications -** still make the distinction between between protected and unprotected -** sqlite3_value objects even when not strictly required. -** -** The sqlite3_value objects that are passed as parameters into the -** implementation of [application-defined SQL functions] are protected. -** The sqlite3_value object returned by -** [sqlite3_column_value()] is unprotected. -** Unprotected sqlite3_value objects may only be used with -** [sqlite3_result_value()] and [sqlite3_bind_value()]. -** The [sqlite3_value_blob | sqlite3_value_type()] family of -** interfaces require protected sqlite3_value objects. +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. */ typedef struct Mem sqlite3_value; /* -** CAPI3REF: SQL Function Context Object {F16001} +** CAPI3REF: SQL Function Context Object {F16001} ** ** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to an sqlite3_context object -** is always first parameter to [application-defined SQL functions]. -** The application-defined SQL function implementation will pass this -** pointer through into calls to [sqlite3_result_int | sqlite3_result()], -** [sqlite3_aggregate_context()], [sqlite3_user_data()], -** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], -** and/or [sqlite3_set_auxdata()]. +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. */ typedef struct sqlite3_context sqlite3_context; /* -** CAPI3REF: Binding Values To Prepared Statements {F13500} -** KEYWORDS: {host parameter} {host parameters} {host parameter name} -** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** CAPI3REF: Binding Values To Prepared Statements {F13500} ** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** literals may be replaced by a parameter in one of these forms: +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: ** **
      **
    • ? **
    • ?NNN -**
    • :VVV -**
    • @VVV +**
    • :AAA +**
    • @AAA **
    • $VVV **
    ** ** In the parameter forms shown above NNN is an integer literal, -** and VVV is an alpha-numeric parameter name. The values of these -** parameters (also called "host parameter names" or "SQL parameters") +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") ** can be set using the sqlite3_bind_*() routines defined here. ** -** The first argument to the sqlite3_bind_*() routines is always -** a pointer to the [sqlite3_stmt] object returned from -** [sqlite3_prepare_v2()] or its variants. -** -** The second argument is the index of the SQL parameter to be set. -** The leftmost SQL parameter has an index of 1. When the same named -** SQL parameter is used more than once, second and subsequent -** occurrences have the same index as the first occurrence. -** The index for named parameters can be looked up using the -** [sqlite3_bind_parameter_index()] API if desired. The index +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index ** for "?NNN" parameters is the value of NNN. -** The NNN value must be between 1 and the [sqlite3_limit()] -** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. ** -** The third argument is the value to bind to the parameter. +** {F13509} The third argument is the value to bind to the parameter. {END} ** -** In those routines that have a fourth argument, its value is the -** number of bytes in the parameter. To be clear: the value is the -** number of bytes in the value, not the number of characters. +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} ** If the fourth parameter is negative, the length of the string is -** the number of bytes up to the first zero terminator. +** number of bytes up to the first zero terminator. {END} ** +** {F13513} ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or -** string after SQLite has finished with it. If the fifth argument is -** the special value [SQLITE_STATIC], then SQLite assumes that the +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the ** information is in static, unmanaged space and does not need to be freed. -** If the fifth argument has the value [SQLITE_TRANSIENT], then +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before -** the sqlite3_bind_*() routine returns. +** the sqlite3_bind_*() routine returns. {END} ** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that -** is filled with zeroes. A zeroblob uses a fixed amount of memory -** (just an integer to hold its size) while it is being processed. -** Zeroblobs are intended to serve as placeholders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | incremental BLOB I/O] routines. -** A negative value for the zeroblob results in a zero-length BLOB. +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} ** -** The sqlite3_bind_*() routines must be called after +** {F13530} The sqlite3_bind_*() routines must be called after ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. +** before [sqlite3_step()]. {F13531} ** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. +** {F13532} Unbound parameters are interpreted as NULL. {END} ** -** These routines return [SQLITE_OK] on success or an error code if -** anything goes wrong. [SQLITE_RANGE] is returned if the parameter -** index is out of range. [SQLITE_NOMEM] is returned if malloc() fails. -** [SQLITE_MISUSE] might be returned if these routines are called on a +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a ** virtual machine that is the wrong state or which has already been finalized. -** Detection of misuse is unreliable. Applications should not depend -** on SQLITE_MISUSE returns. SQLITE_MISUSE is intended to indicate a -** a logic error in the application. Future versions of SQLite might -** panic rather than return SQLITE_MISUSE. -** -** See also: [sqlite3_bind_parameter_count()], -** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13506} The [SQL statement compiler] recognizes tokens of the forms -** "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters, -** where NNN is any sequence of one or more digits -** and where VVV is any sequence of one or more alphanumeric -** characters or "::" optionally followed by a string containing -** no spaces and contained within parentheses. -** -** {F13509} The initial value of an SQL parameter is NULL. -** -** {F13512} The index of an "?" SQL parameter is one larger than the -** largest index of SQL parameter to the left, or 1 if -** the "?" is the leftmost SQL parameter. -** -** {F13515} The index of an "?NNN" SQL parameter is the integer NNN. -** -** {F13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is -** the same as the index of leftmost occurrences of the same -** parameter, or one more than the largest index over all -** parameters to the left if this is the first occurrence -** of this parameter, or 1 if this is the leftmost parameter. -** -** {F13521} The [SQL statement compiler] fails with an [SQLITE_RANGE] -** error if the index of an SQL parameter is less than 1 -** or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER -** parameter. -** -** {F13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)] -** associate the value V with all SQL parameters having an -** index of N in the [prepared statement] S. -** -** {F13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)] -** override prior calls with the same values of S and N. -** -** {F13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)] -** persist across calls to [sqlite3_reset(S)]. -** -** {F13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L -** bytes of the BLOB or string pointed to by V, when L -** is non-negative. -** -** {F13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or -** [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters -** from V through the first zero character when L is negative. -** -** {F13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] when D is the special -** constant [SQLITE_STATIC], SQLite assumes that the value V -** is held in static unmanaged space that will not change -** during the lifetime of the binding. -** -** {F13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] when D is the special -** constant [SQLITE_TRANSIENT], the routine makes a -** private copy of the value V before it returns. -** -** {F13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to -** a function, SQLite invokes that function to destroy the -** value V after it has finished using the value V. -** -** {F13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound -** is a BLOB of L bytes, or a zero-length BLOB if L is negative. -** -** {F13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may -** be either a [protected sqlite3_value] object or an -** [unprotected sqlite3_value] object. */ SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double); @@ -3430,171 +2224,98 @@ SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); /* -** CAPI3REF: Number Of SQL Parameters {F13600} +** CAPI3REF: Number Of Host Parameters {F13600} ** -** This routine can be used to find the number of [SQL parameters] -** in a [prepared statement]. SQL parameters are tokens of the -** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as -** placeholders for values that are [sqlite3_bind_blob | bound] -** to the parameters at a later time. +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} ** -** This routine actually returns the index of the largest (rightmost) -** parameter. For all forms except ?NNN, this will correspond to the -** number of unique parameters. If parameters of the ?NNN are used, -** there may be gaps in the list. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_name()], and -** [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13601} The [sqlite3_bind_parameter_count(S)] interface returns -** the largest index of all SQL parameters in the -** [prepared statement] S, or 0 if S contains no SQL parameters. +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter {F13620} ** -** This routine returns a pointer to the name of the n-th -** [SQL parameter] in a [prepared statement]. -** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" -** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" -** respectively. -** In other words, the initial ":" or "$" or "@" or "?" -** is included as part of the name. -** Parameters of the form "?" without a following integer have no name -** and are also referred to as "anonymous parameters". +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. ** -** The first host parameter has an index of 1, not 0. +** {F13623} The first host parameter has an index of 1, not 0. ** -** If the value n is out of range or if the n-th parameter is -** nameless, then NULL is returned. The returned string is -** always in UTF-8 encoding even if the named parameter was +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13621} The [sqlite3_bind_parameter_name(S,N)] interface returns -** a UTF-8 rendering of the name of the SQL parameter in -** the [prepared statement] S having index N, or -** NULL if there is no SQL parameter with index N or if the -** parameter with index N is an anonymous parameter "?". */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name {F13640} ** -** Return the index of an SQL parameter given its name. The -** index value returned is suitable for use as the second -** parameter to [sqlite3_bind_blob|sqlite3_bind()]. A zero -** is returned if no matching parameter is found. The parameter -** name must be given in UTF-8 even if the original statement -** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13641} The [sqlite3_bind_parameter_index(S,N)] interface returns -** the index of SQL parameter in the [prepared statement] -** S whose name matches the UTF-8 string N, or 0 if there is -** no match. +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. */ SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} ** -** Contrary to the intuition of many, [sqlite3_reset()] does not reset -** the [sqlite3_bind_blob | bindings] on a [prepared statement]. -** Use this routine to reset all host parameters to NULL. -** -** INVARIANTS: -** -** {F13661} The [sqlite3_clear_bindings(S)] interface resets all SQL -** parameter bindings in the [prepared statement] S back to NULL. +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set {F13710} ** -** Return the number of columns in the result set returned by the -** [prepared statement]. This routine returns 0 if pStmt is an SQL -** statement that does not return data (for example an [UPDATE]). -** -** INVARIANTS: -** -** {F13711} The [sqlite3_column_count(S)] interface returns the number of -** columns in the result set generated by the [prepared statement] S, -** or 0 if S does not generate a result set. +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set {F13720} ** -** These routines return the name assigned to a particular column -** in the result set of a [SELECT] statement. The sqlite3_column_name() -** interface returns a pointer to a zero-terminated UTF-8 string +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated -** UTF-16 string. The first parameter is the [prepared statement] -** that implements the [SELECT] statement. The second parameter is the -** column number. The leftmost column is number 0. +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. ** -** The returned string pointer is valid until either the [prepared statement] -** is destroyed by [sqlite3_finalize()] or until the next call to -** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. ** -** If sqlite3_malloc() fails during the processing of either routine +** {F13725} If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. -** -** The name of a result column is the value of the "AS" clause for -** that column, if there is an AS clause. If there is no AS clause -** then the name of the column is unspecified and may change from -** one release of SQLite to the next. -** -** INVARIANTS: -** -** {F13721} A successful invocation of the [sqlite3_column_name(S,N)] -** interface returns the name of the Nth column (where 0 is -** the leftmost column) for the result set of the -** [prepared statement] S as a zero-terminated UTF-8 string. -** -** {F13723} A successful invocation of the [sqlite3_column_name16(S,N)] -** interface returns the name of the Nth column (where 0 is -** the leftmost column) for the result set of the -** [prepared statement] S as a zero-terminated UTF-16 string -** in the native byte order. -** -** {F13724} The [sqlite3_column_name()] and [sqlite3_column_name16()] -** interfaces return a NULL pointer if they are unable to -** allocate memory to hold their normal return strings. -** -** {F13725} If the N parameter to [sqlite3_column_name(S,N)] or -** [sqlite3_column_name16(S,N)] is out of range, then the -** interfaces return a NULL pointer. -** -** {F13726} The strings returned by [sqlite3_column_name(S,N)] and -** [sqlite3_column_name16(S,N)] are valid until the next -** call to either routine with the same S and N parameters -** or until [sqlite3_finalize(S)] is called. -** -** {F13727} When a result column of a [SELECT] statement contains -** an AS clause, the name of that column is the identifier -** to the right of the AS keyword. */ SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N); SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); @@ -3602,91 +2323,41 @@ SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result {F13740} ** -** These routines provide a means to determine what column of what -** table in which database a result of a [SELECT] statement comes from. -** The name of the database or table or column can be returned as -** either a UTF-8 or UTF-16 string. The _database_ routines return +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return ** the database name, the _table_ routines return the table name, and -** the origin_ routines return the column name. -** The returned string is valid until the [prepared statement] is destroyed -** using [sqlite3_finalize()] or until the same information is requested +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested ** again in a different encoding. ** -** The names returned are the original un-aliased names of the +** {F13745} The names returned are the original un-aliased names of the ** database, table, and column. ** -** The first argument to the following calls is a [prepared statement]. -** These functions return information about the Nth column returned by +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by ** the statement, where N is the second function argument. ** -** If the Nth column returned by the statement is an expression or -** subquery and is not a column value, then all of these functions return -** NULL. These routine might also return NULL if a memory allocation error -** occurs. Otherwise, they return the name of the attached database, table -** and column that query result column was extracted from. +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. ** -** As with all other SQLite APIs, those postfixed with "16" return +** {F13750} As with all other SQLite APIs, those postfixed with "16" return ** UTF-16 encoded strings, the other functions return UTF-8. {END} ** -** These APIs are only available if the library was compiled with the -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. ** -** {A13751} +** {U13751} ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. -** -** INVARIANTS: -** -** {F13741} The [sqlite3_column_database_name(S,N)] interface returns either -** the UTF-8 zero-terminated name of the database from which the -** Nth result column of the [prepared statement] S is extracted, -** or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13742} The [sqlite3_column_database_name16(S,N)] interface returns either -** the UTF-16 native byte order zero-terminated name of the database -** from which the Nth result column of the [prepared statement] S is -** extracted, or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13743} The [sqlite3_column_table_name(S,N)] interface returns either -** the UTF-8 zero-terminated name of the table from which the -** Nth result column of the [prepared statement] S is extracted, -** or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13744} The [sqlite3_column_table_name16(S,N)] interface returns either -** the UTF-16 native byte order zero-terminated name of the table -** from which the Nth result column of the [prepared statement] S is -** extracted, or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13745} The [sqlite3_column_origin_name(S,N)] interface returns either -** the UTF-8 zero-terminated name of the table column from which the -** Nth result column of the [prepared statement] S is extracted, -** or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13746} The [sqlite3_column_origin_name16(S,N)] interface returns either -** the UTF-16 native byte order zero-terminated name of the table -** column from which the Nth result column of the -** [prepared statement] S is extracted, or NULL if the Nth column -** of S is a general expression or if unable to allocate memory -** to store the name. -** -** {F13748} The return values from -** [sqlite3_column_database_name | column metadata interfaces] -** are valid for the lifetime of the [prepared statement] -** or until the encoding is changed by another metadata -** interface call for the same prepared statement and column. -** -** LIMITATIONS: -** -** {A13751} If two or more threads call one or more -** [sqlite3_column_database_name | column metadata interfaces] -** for the same [prepared statement] and result column -** at the same time then the results are undefined. */ SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int); @@ -3698,24 +2369,24 @@ SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result {F13760} ** -** The first parameter is a [prepared statement]. -** If this statement is a [SELECT] statement and the Nth column of the -** returned result set of that [SELECT] is a table column (not an +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an ** expression or subquery) then the declared type of the table -** column is returned. If the Nth column of the result set is an +** column is returned. {F13762} If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. -** The returned string is always UTF-8 encoded. {END} -** -** For example, given the database schema: +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** -** and the following statement to be compiled: +** And the following statement compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** -** this routine would return the string "VARIANT" for the second result -** column (i==1), and a NULL pointer for the first result column (i==0). +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). ** ** SQLite uses dynamic run-time typing. So just because a column ** is declared to contain a particular type does not mean that the @@ -3723,55 +2394,36 @@ SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); ** strongly typed, but the typing is dynamic not static. Type ** is associated with individual values, not with the containers ** used to hold those values. -** -** INVARIANTS: -** -** {F13761} A successful call to [sqlite3_column_decltype(S,N)] returns a -** zero-terminated UTF-8 string containing the declared datatype -** of the table column that appears as the Nth column (numbered -** from 0) of the result set to the [prepared statement] S. -** -** {F13762} A successful call to [sqlite3_column_decltype16(S,N)] -** returns a zero-terminated UTF-16 native byte order string -** containing the declared datatype of the table column that appears -** as the Nth column (numbered from 0) of the result set to the -** [prepared statement] S. -** -** {F13763} If N is less than 0 or N is greater than or equal to -** the number of columns in the [prepared statement] S, -** or if the Nth column of S is an expression or subquery rather -** than a table column, or if a memory allocation failure -** occurs during encoding conversions, then -** calls to [sqlite3_column_decltype(S,N)] or -** [sqlite3_column_decltype16(S,N)] return NULL. */ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int); +SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *, int i); SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); -/* -** CAPI3REF: Evaluate An SQL Statement {F13200} +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} ** -** After a [prepared statement] has been prepared using either -** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy -** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function -** must be called one or more times to evaluate the statement. +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. ** -** The details of the behavior of the sqlite3_step() interface depend +** The details of the behavior of this sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** -** In the legacy interface, the return value will be either [SQLITE_BUSY], +** In the lagacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. -** With the "v2" interface, any of the other [result codes] or -** [extended result codes] might be returned as well. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. ** ** [SQLITE_BUSY] means that the database engine was unable to acquire the -** database locks it needs to do its job. If the statement is a [COMMIT] +** database locks it needs to do its job. If the statement is a COMMIT ** or occurs outside of an explicit transaction, then you can retry the -** statement. If the statement is not a [COMMIT] and occurs within a +** statement. If the statement is not a COMMIT and occurs within a ** explicit transaction then you should rollback the transaction before ** continuing. ** @@ -3780,91 +2432,64 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** -** If the SQL statement being executed returns any data, then [SQLITE_ROW] -** is returned each time a new row of data is ready for processing by the -** caller. The values may be accessed using the [column access functions]. +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. -** +** ** [SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. -** With the legacy interface, a more specific error code (for example, +** With the legacy interface, a more specific error code (example: ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the -** [prepared statement]. In the "v2" interface, +** [sqlite3_stmt | prepared statement]. In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. -** Perhaps it was called on a [prepared statement] that has -** already been [sqlite3_finalize | finalized] or on one that had +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** -** Goofy Interface Alert: In the legacy interface, the sqlite3_step() -** API always returns a generic error code, [SQLITE_ERROR], following any -** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call -** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the -** specific [error codes] that better describes the error. +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead -** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, -** then the more specific [error codes] are returned directly +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. -** -** INVARIANTS: -** -** {F13202} If the [prepared statement] S is ready to be run, then -** [sqlite3_step(S)] advances that prepared statement until -** completion or until it is ready to return another row of the -** result set, or until an [sqlite3_interrupt | interrupt] -** or a run-time error occurs. -** -** {F15304} When a call to [sqlite3_step(S)] causes the [prepared statement] -** S to run to completion, the function returns [SQLITE_DONE]. -** -** {F15306} When a call to [sqlite3_step(S)] stops because it is ready to -** return another row of the result set, it returns [SQLITE_ROW]. -** -** {F15308} If a call to [sqlite3_step(S)] encounters an -** [sqlite3_interrupt | interrupt] or a run-time error, -** it returns an appropriate error code that is not one of -** [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE]. -** -** {F15310} If an [sqlite3_interrupt | interrupt] or a run-time error -** occurs during a call to [sqlite3_step(S)] -** for a [prepared statement] S created using -** legacy interfaces [sqlite3_prepare()] or -** [sqlite3_prepare16()], then the function returns either -** [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE]. */ SQLITE_API int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set {F13770} ** -** Returns the number of values in the current row of the result set. +** Return the number of values in the current row of the result set. ** -** INVARIANTS: -** -** {F13771} After a call to [sqlite3_step(S)] that returns [SQLITE_ROW], -** the [sqlite3_data_count(S)] routine will return the same value -** as the [sqlite3_column_count(S)] function. -** -** {F13772} After [sqlite3_step(S)] has returned any value other than -** [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the -** [prepared statement] for the first time since it was -** [sqlite3_prepare | prepared] or [sqlite3_reset | reset], -** the [sqlite3_data_count(S)] routine returns zero. +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes {F10265} -** KEYWORDS: SQLITE_TEXT ** -** {F10266} Every value in SQLite has one of five fundamental datatypes: +** {F10266}Every value in SQLite has one of five fundamental datatypes: ** **
      **
    • 64-bit signed integer @@ -3878,7 +2503,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both -** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not ** SQLITE_TEXT. */ #define SQLITE_INTEGER 1 @@ -3893,31 +2518,31 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); #define SQLITE3_TEXT 3 /* -** CAPI3REF: Result Values From A Query {F13800} -** KEYWORDS: {column access functions} +** CAPI3REF: Results Values From A Query {F13800} ** -** These routines form the "result set query" interface. +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. ** -** These routines return information about a single column of the current -** result row of a query. In every case the first argument is a pointer -** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] -** that was returned from [sqlite3_prepare_v2()] or one of its variants) -** and the second argument is the index of the column for which information -** should be returned. The leftmost column of the result set has the index 0. -** -** If the SQL statement does not currently point to a valid row, or if the -** column index is out of range, the result is undefined. +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither -** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines -** are pending, then the results are undefined. +** are pending, then the results are undefined. ** -** The sqlite3_column_type() routine returns the +** The sqlite3_column_type() routine returns ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value @@ -3927,7 +2552,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** -** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. @@ -3939,27 +2564,19 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** bytes in the string, not the number of characters. ** ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), -** even empty strings, are always zero terminated. The return -** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary ** pointer, possibly even a NULL pointer. ** ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() -** but leaves the result in UTF-16 in native byte order instead of UTF-8. +** but leaves the result in UTF-16 instead of UTF-8. ** The zero terminator is not included in this count. ** -** The object returned by [sqlite3_column_value()] is an -** [unprotected sqlite3_value] object. An unprotected sqlite3_value object -** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. -** If the [unprotected sqlite3_value] object returned by -** [sqlite3_column_value()] is used in any other way, including calls -** to routines like [sqlite3_value_int()], [sqlite3_value_text()], -** or [sqlite3_value_bytes()], then the behavior is undefined. -** ** These routines attempt to convert the value where appropriate. For ** example, if the internal representation is FLOAT and a text result -** is requested, [sqlite3_snprintf()] is used internally to perform the -** conversion automatically. The following table details the conversions -** that are applied: +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: ** **
      ** @@ -3971,7 +2588,7 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); **
      NULL BLOB Result is NULL pointer **
      INTEGER FLOAT Convert from integer to float **
      INTEGER TEXT ASCII rendering of the integer -**
      INTEGER BLOB Same as INTEGER->TEXT +**
      INTEGER BLOB Same as for INTEGER->TEXT **
      FLOAT INTEGER Convert from float to integer **
      FLOAT TEXT ASCII rendering of the float **
      FLOAT BLOB Same as FLOAT->TEXT @@ -3986,56 +2603,57 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** ** The table above makes reference to standard C library functions atoi() ** and atof(). SQLite does not really use these functions. It has its -** own equivalent internal routines. The atoi() and atof() names are +** on equavalent internal routines. The atoi() and atof() names are ** used in the table for brevity and because they are familiar to most ** C programmers. ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or -** sqlite3_column_text16() may be invalidated. +** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** **
        -**
      • The initial content is a BLOB and sqlite3_column_text() or -** sqlite3_column_text16() is called. A zero-terminator might -** need to be added to the string.
      • -**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or -** sqlite3_column_text16() is called. The content must be converted -** to UTF-16.
      • -**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or -** sqlite3_column_text() is called. The content must be converted -** to UTF-8.
      • +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • **
      ** ** Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer points to will have been modified. Other kinds -** of conversion are done in place when it is possible, but sometimes they -** are not possible and in those cases prior pointers are invalidated. +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. ** ** The safest and easiest to remember policy is to invoke these routines ** in one of the following ways: ** -**
        +**
          **
        • sqlite3_column_text() followed by sqlite3_column_bytes()
        • **
        • sqlite3_column_blob() followed by sqlite3_column_bytes()
        • **
        • sqlite3_column_text16() followed by sqlite3_column_bytes16()
        • -**
        +**
      ** -** In other words, you should call sqlite3_column_text(), -** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result -** into the desired format, then invoke sqlite3_column_bytes() or -** sqlite3_column_bytes16() to find the size of the result. Do not mix calls -** to sqlite3_column_text() or sqlite3_column_blob() with calls to -** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() -** with calls to sqlite3_column_bytes(). +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). ** ** The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. The memory space used to hold strings -** and BLOBs is freed automatically. Do not pass the pointers returned -** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** If a memory allocation error occurs during the evaluation of any @@ -4043,61 +2661,6 @@ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM]. -** -** INVARIANTS: -** -** {F13803} The [sqlite3_column_blob(S,N)] interface converts the -** Nth column in the current row of the result set for -** the [prepared statement] S into a BLOB and then returns a -** pointer to the converted value. -** -** {F13806} The [sqlite3_column_bytes(S,N)] interface returns the -** number of bytes in the BLOB or string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_column_blob(S,N)] or -** [sqlite3_column_text(S,N)]. -** -** {F13809} The [sqlite3_column_bytes16(S,N)] interface returns the -** number of bytes in the string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_column_text16(S,N)]. -** -** {F13812} The [sqlite3_column_double(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a floating point value and -** returns a copy of that value. -** -** {F13815} The [sqlite3_column_int(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a 64-bit signed integer and -** returns the lower 32 bits of that integer. -** -** {F13818} The [sqlite3_column_int64(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a 64-bit signed integer and -** returns a copy of that integer. -** -** {F13821} The [sqlite3_column_text(S,N)] interface converts the -** Nth column in the current row of the result set for -** the [prepared statement] S into a zero-terminated UTF-8 -** string and returns a pointer to that string. -** -** {F13824} The [sqlite3_column_text16(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a zero-terminated 2-byte -** aligned UTF-16 native byte order string and returns -** a pointer to that string. -** -** {F13827} The [sqlite3_column_type(S,N)] interface returns -** one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT], -** [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for -** the Nth column in the current row of the result set for -** the [prepared statement] S. -** -** {F13830} The [sqlite3_column_value(S,N)] interface returns a -** pointer to an [unprotected sqlite3_value] object for the -** Nth column in the current row of the result set for -** the [prepared statement] S. */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); @@ -4113,86 +2676,62 @@ SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object {F13300} ** -** The sqlite3_finalize() function is called to delete a [prepared statement]. -** If the statement was executed successfully or not executed at all, then -** SQLITE_OK is returned. If execution of the statement failed then an -** [error code] or [extended error code] is returned. +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. ** ** This routine can be called at any point during the execution of the -** [prepared statement]. If the virtual machine has not +** [sqlite3_stmt | virtual machine]. If the virtual machine has not ** completed execution when this routine is called, that is like -** encountering an error or an [sqlite3_interrupt | interrupt]. -** Incomplete updates may be rolled back and transactions canceled, -** depending on the circumstances, and the -** [error code] returned will be [SQLITE_ABORT]. -** -** INVARIANTS: -** -** {F11302} The [sqlite3_finalize(S)] interface destroys the -** [prepared statement] S and releases all -** memory and file resources held by that object. -** -** {F11304} If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S returned an error, -** then [sqlite3_finalize(S)] returns that same error. +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object {F13330} ** -** The sqlite3_reset() function is called to reset a [prepared statement] -** object back to its initial state, ready to be re-executed. +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. ** Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. -** -** {F11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S -** back to the beginning of its program. -** -** {F11334} If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], -** or if [sqlite3_step(S)] has never before been called on S, -** then [sqlite3_reset(S)] returns [SQLITE_OK]. -** -** {F11336} If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S indicated an error, then -** [sqlite3_reset(S)] returns an appropriate [error code]. -** -** {F11338} The [sqlite3_reset(S)] interface does not change the values -** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions {F16100} -** KEYWORDS: {function creation routines} -** KEYWORDS: {application-defined SQL function} -** KEYWORDS: {application-defined SQL functions} ** -** These two functions (collectively known as "function creation routines") -** are used to add SQL functions or aggregates or to redefine the behavior -** of existing SQL functions or aggregates. The only difference between the -** two is that the second parameter, the name of the (scalar) function or -** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16 -** for sqlite3_create_function16(). +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). ** -** The first parameter is the [database connection] to which the SQL -** function is to be added. If a single program uses more than one database -** connection internally, then SQL functions must be added individually to -** each database connection. +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. ** -** The second parameter is the name of the SQL function to be created or -** redefined. The length of the name is limited to 255 bytes, exclusive of -** the zero-terminator. Note that the name length limit is in bytes, not +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not ** characters. Any attempt to create a function with a longer name -** will result in [SQLITE_ERROR] being returned. +** will result in an SQLITE_ERROR error. ** ** The third parameter is the number of arguments that the SQL function or ** aggregate takes. If this parameter is negative, then the SQL function or ** aggregate may take any number of arguments. ** -** The fourth parameter, eTextRep, specifies what +** The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. Any SQL function implementation should be able to work ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be @@ -4201,107 +2740,45 @@ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); ** times with the same function but with different values of eTextRep. ** When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. -** If there is only a single implementation which does not care what text -** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. ** -** The fifth parameter is an arbitrary pointer. The implementation of the -** function can gain access to this pointer using [sqlite3_user_data()]. +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. ** ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are -** pointers to C-language functions that implement the SQL function or -** aggregate. A scalar SQL function requires an implementation of the xFunc -** callback only, NULL pointers should be passed as the xStep and xFinal -** parameters. An aggregate SQL function requires an implementation of xStep -** and xFinal and NULL should be passed for xFunc. To delete an existing -** SQL function or aggregate, pass NULL for all three function callbacks. +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. ** ** It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of -** arguments or differing preferred text encodings. SQLite will use +** arguments or differing perferred text encodings. SQLite will use ** the implementation most closely matches the way in which the ** SQL function is used. -** -** INVARIANTS: -** -** {F16103} The [sqlite3_create_function16()] interface behaves exactly -** like [sqlite3_create_function()] in every way except that it -** interprets the zFunctionName argument as zero-terminated UTF-16 -** native byte order instead of as zero-terminated UTF-8. -** -** {F16106} A successful invocation of -** the [sqlite3_create_function(D,X,N,E,...)] interface registers -** or replaces callback functions in the [database connection] D -** used to implement the SQL function named X with N parameters -** and having a preferred text encoding of E. -** -** {F16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)] -** replaces the P, F, S, and L values from any prior calls with -** the same D, X, N, and E values. -** -** {F16112} The [sqlite3_create_function(D,X,...)] interface fails with -** a return code of [SQLITE_ERROR] if the SQL function name X is -** longer than 255 bytes exclusive of the zero terminator. -** -** {F16118} Either F must be NULL and S and L are non-NULL or else F -** is non-NULL and S and L are NULL, otherwise -** [sqlite3_create_function(D,X,N,E,P,F,S,L)] returns [SQLITE_ERROR]. -** -** {F16121} The [sqlite3_create_function(D,...)] interface fails with an -** error code of [SQLITE_BUSY] if there exist [prepared statements] -** associated with the [database connection] D. -** -** {F16124} The [sqlite3_create_function(D,X,N,...)] interface fails with an -** error code of [SQLITE_ERROR] if parameter N (specifying the number -** of arguments to the SQL function being registered) is less -** than -1 or greater than 127. -** -** {F16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)] -** interface causes callbacks to be invoked for the SQL function -** named X when the number of arguments to the SQL function is -** exactly N. -** -** {F16130} When N is -1, the [sqlite3_create_function(D,X,N,...)] -** interface causes callbacks to be invoked for the SQL function -** named X with any number of arguments. -** -** {F16133} When calls to [sqlite3_create_function(D,X,N,...)] -** specify multiple implementations of the same function X -** and when one implementation has N>=0 and the other has N=(-1) -** the implementation with a non-zero N is preferred. -** -** {F16136} When calls to [sqlite3_create_function(D,X,N,E,...)] -** specify multiple implementations of the same function X with -** the same number of arguments N but with different -** encodings E, then the implementation where E matches the -** database encoding is preferred. -** -** {F16139} For an aggregate SQL function created using -** [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer -** function L will always be invoked exactly once if the -** step function S is called one or more times. -** -** {F16142} When SQLite invokes either the xFunc or xStep function of -** an application-defined SQL function or aggregate created -** by [sqlite3_create_function()] or [sqlite3_create_function16()], -** then the array of [sqlite3_value] objects passed as the -** third parameter are always [protected sqlite3_value] objects. */ SQLITE_API int sqlite3_create_function( - sqlite3 *db, + sqlite3 *, const char *zFunctionName, int nArg, int eTextRep, - void *pApp, + void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); SQLITE_API int sqlite3_create_function16( - sqlite3 *db, + sqlite3*, const void *zFunctionName, int nArg, int eTextRep, - void *pApp, + void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) @@ -4347,101 +2824,40 @@ SQLITE_API int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlit ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 4th parameter to these callbacks is an array of pointers to -** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** [sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** -** These routines work only with [protected sqlite3_value] objects. -** Any attempt to use these routines on an [unprotected sqlite3_value] -** object results in undefined behavior. +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. ** -** These routines work just like the corresponding [column access functions] -** except that these routines take a single [protected sqlite3_value] object -** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. -** -** The sqlite3_value_text16() interface extracts a UTF-16 string +** The sqlite3_value_text16() interface extracts a UTF16 string ** in the native byte-order of the host machine. The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces -** extract UTF-16 strings as big-endian and little-endian respectively. +** extract UTF16 strings as big-endian and little-endian respectively. ** ** The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other -** words, if the value is a string that looks like a number) -** then the conversion is performed. Otherwise no conversion occurs. -** The [SQLITE_INTEGER | datatype] after conversion is returned. +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. ** -** Please pay particular attention to the fact that the pointer returned -** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], -** or [sqlite3_value_text16()]. +** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as -** the SQL function that supplied the [sqlite3_value*] parameters. +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. ** -** INVARIANTS: -** -** {F15103} The [sqlite3_value_blob(V)] interface converts the -** [protected sqlite3_value] object V into a BLOB and then -** returns a pointer to the converted value. -** -** {F15106} The [sqlite3_value_bytes(V)] interface returns the -** number of bytes in the BLOB or string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_value_blob(V)] or -** [sqlite3_value_text(V)]. -** -** {F15109} The [sqlite3_value_bytes16(V)] interface returns the -** number of bytes in the string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_value_text16(V)], -** [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)]. -** -** {F15112} The [sqlite3_value_double(V)] interface converts the -** [protected sqlite3_value] object V into a floating point value and -** returns a copy of that value. -** -** {F15115} The [sqlite3_value_int(V)] interface converts the -** [protected sqlite3_value] object V into a 64-bit signed integer and -** returns the lower 32 bits of that integer. -** -** {F15118} The [sqlite3_value_int64(V)] interface converts the -** [protected sqlite3_value] object V into a 64-bit signed integer and -** returns a copy of that integer. -** -** {F15121} The [sqlite3_value_text(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated UTF-8 -** string and returns a pointer to that string. -** -** {F15124} The [sqlite3_value_text16(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated 2-byte -** aligned UTF-16 native byte order -** string and returns a pointer to that string. -** -** {F15127} The [sqlite3_value_text16be(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated 2-byte -** aligned UTF-16 big-endian -** string and returns a pointer to that string. -** -** {F15130} The [sqlite3_value_text16le(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated 2-byte -** aligned UTF-16 little-endian -** string and returns a pointer to that string. -** -** {F15133} The [sqlite3_value_type(V)] interface returns -** one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT], -** [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for -** the [sqlite3_value] object V. -** -** {F15136} The [sqlite3_value_numeric_type(V)] interface converts -** the [protected sqlite3_value] object V into either an integer or -** a floating point value if it can do so without loss of -** information, and returns one of [SQLITE_NULL], -** [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or -** [SQLITE_BLOB] as appropriate for the -** [protected sqlite3_value] object V after the conversion attempt. */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API int sqlite3_value_bytes(sqlite3_value*); @@ -4460,153 +2876,81 @@ SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); ** CAPI3REF: Obtain Aggregate Function Context {F16210} ** ** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. ** -** The first time the sqlite3_aggregate_context() routine is called for a -** particular aggregate, SQLite allocates nBytes of memory, zeroes out that -** memory, and returns a pointer to it. On second and subsequent calls to -** sqlite3_aggregate_context() for the same aggregate function index, -** the same buffer is returned. The implementation of the aggregate can use -** the returned buffer to accumulate data. +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} ** -** SQLite automatically frees the allocated buffer when the aggregate -** query concludes. -** -** The first parameter should be a copy of the -** [sqlite3_context | SQL function context] that is the first parameter -** to the callback routine that implements the aggregate function. +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. -** -** INVARIANTS: -** -** {F16211} The first invocation of [sqlite3_aggregate_context(C,N)] for -** a particular instance of an aggregate function (for a particular -** context C) causes SQLite to allocate N bytes of memory, -** zero that memory, and return a pointer to the allocated memory. -** -** {F16213} If a memory allocation error occurs during -** [sqlite3_aggregate_context(C,N)] then the function returns 0. -** -** {F16215} Second and subsequent invocations of -** [sqlite3_aggregate_context(C,N)] for the same context pointer C -** ignore the N parameter and return a pointer to the same -** block of memory returned by the first invocation. -** -** {F16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is -** automatically freed on the next call to [sqlite3_reset()] -** or [sqlite3_finalize()] for the [prepared statement] containing -** the aggregate function associated with context C. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions {F16240} ** -** The sqlite3_user_data() interface returns a copy of +** {F16241} The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) -** of the [sqlite3_create_function()] +** of the the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. {END} ** -** This routine must be called from the same thread in which +** {U16243} This routine must be called from the same thread in which ** the application-defined function is running. -** -** INVARIANTS: -** -** {F16243} The [sqlite3_user_data(C)] interface returns a copy of the -** P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)] -** or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that -** registered the SQL function associated with [sqlite3_context] C. */ SQLITE_API void *sqlite3_user_data(sqlite3_context*); -/* -** CAPI3REF: Database Connection For Functions {F16250} -** -** The sqlite3_context_db_handle() interface returns a copy of -** the pointer to the [database connection] (the 1st parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally -** registered the application defined function. -** -** INVARIANTS: -** -** {F16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the -** D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)] -** or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that -** registered the SQL function associated with [sqlite3_context] C. -*/ -SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*); - /* ** CAPI3REF: Function Auxiliary Data {F16270} ** ** The following two functions may be used by scalar SQL functions to -** associate metadata with argument values. If the same value is passed to +** associate meta-data with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under -** some circumstances the associated metadata may be preserved. This may +** some circumstances the associated meta-data may be preserved. This may ** be used, for example, to add a regular-expression matching scalar ** function. The compiled version of the regular expression is stored as -** metadata associated with the SQL value passed as the regular expression +** meta-data associated with the SQL value passed as the regular expression ** pattern. The compiled regular expression can be reused on multiple ** invocations of the same function so that the original pattern string ** does not need to be recompiled on each invocation. ** -** The sqlite3_get_auxdata() interface returns a pointer to the metadata +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data ** associated by the sqlite3_set_auxdata() function with the Nth argument -** value to the application-defined function. If no metadata has been ever -** been set for the Nth argument of the function, or if the corresponding -** function parameter has changed since the meta-data was set, -** then sqlite3_get_auxdata() returns a NULL pointer. +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. ** -** The sqlite3_set_auxdata() interface saves the metadata -** pointed to by its 3rd parameter as the metadata for the N-th -** argument of the application-defined function. Subsequent +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent ** calls to sqlite3_get_auxdata() might return this data, if it has -** not been destroyed. -** If it is not NULL, SQLite will invoke the destructor +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor ** function given by the 4th parameter to sqlite3_set_auxdata() on -** the metadata when the corresponding function parameter changes -** or when the SQL statement completes, whichever comes first. +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} ** -** SQLite is free to call the destructor and drop metadata on any -** parameter of any function at any time. The only guarantee is that -** the destructor will be called before the metadata is dropped. -** -** In practice, metadata is preserved between function calls for +** In practice, meta-data is preserved between function calls for ** expressions that are constant at compile time. This includes literal ** values and SQL variables. ** ** These routines must be called from the same thread in which ** the SQL function is running. -** -** INVARIANTS: -** -** {F16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer -** to metadata associated with the Nth parameter of the SQL function -** whose context is C, or NULL if there is no metadata associated -** with that parameter. -** -** {F16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata -** pointer P to the Nth parameter of the SQL function with context C. -** -** {F16276} SQLite will invoke the destructor D with a single argument -** which is the metadata pointer P following a call to -** [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold -** the metadata. -** -** {F16277} SQLite ceases to hold metadata for an SQL function parameter -** when the value of that parameter changes. -** -** {F16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor -** is called for any prior metadata associated with the same function -** context C and parameter N. -** -** {F16279} SQLite will call destructors for any metadata it is holding -** in a particular [prepared statement] S when either -** [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called. */ SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); @@ -4615,10 +2959,10 @@ SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(voi /* ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} ** -** These are special values for the destructor that is passed in as the +** These are special value for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant -** and will never change. It does not need to be destroyed. The +** and will never change. It does not need to be destroyed. The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. @@ -4638,197 +2982,97 @@ typedef void (*sqlite3_destructor_type)(void*); ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** -** These functions work very much like the [parameter binding] family of -** functions used to bind values to host parameters in prepared statements. -** Refer to the [SQL parameter] documentation for additional information. +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. ** -** The sqlite3_result_blob() interface sets the result from -** an application-defined function to be the BLOB whose content is pointed +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the -** third parameter. -** -** The sqlite3_result_zeroblob() interfaces set the result of -** the application-defined function to be a BLOB containing all zero +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero ** bytes and N bytes in size, where N is the value of the 2nd parameter. ** -** The sqlite3_result_double() interface sets the result from -** an application-defined function to be a floating point value specified +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified ** by its 2nd argument. ** -** The sqlite3_result_error() and sqlite3_result_error16() functions +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. -** SQLite uses the string pointed to by the +** {F16411} SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() -** as the text of an error message. SQLite interprets the error -** message string from sqlite3_result_error() as UTF-8. SQLite -** interprets the string from sqlite3_result_error16() as UTF-16 in native -** byte order. If the third parameter to sqlite3_result_error() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. -** If the third parameter to sqlite3_result_error() or +** {F16415} If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. -** The sqlite3_result_error() and sqlite3_result_error16() -** routines make a private copy of the error message text before -** they return. Hence, the calling function can deallocate or +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or ** modify the text after they return without harm. -** The sqlite3_result_error_code() function changes the error code -** returned by SQLite as a result of an error in a function. By default, -** the error code is SQLITE_ERROR. A subsequent call to sqlite3_result_error() -** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** -** The sqlite3_result_toobig() interface causes SQLite to throw an error -** indicating that a string or BLOB is to long to represent. +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. ** -** The sqlite3_result_nomem() interface causes SQLite to throw an error -** indicating that a memory allocation failed. -** -** The sqlite3_result_int() interface sets the return value +** {F16431} The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. -** The sqlite3_result_int64() interface sets the return value +** {F16432} The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** -** The sqlite3_result_null() interface sets the return value +** {F16437} The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** -** The sqlite3_result_text(), sqlite3_result_text16(), +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. -** SQLite takes the text result from the application from +** {F16442} SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. -** If the 3rd parameter to the sqlite3_result_text* interfaces -** is negative, then SQLite takes result text from the 2nd parameter +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. -** If the 3rd parameter to the sqlite3_result_text* interfaces +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. -** If the 4th parameter to the sqlite3_result_text* interfaces +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that -** function as the destructor on the text or BLOB result when it has +** function as the destructor on the text or blob result when it has ** finished using that result. -** If the 4th parameter to the sqlite3_result_text* interfaces or -** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite -** assumes that the text or BLOB result is in constant space and does not -** copy the it or call a destructor when it has finished using that result. -** If the 4th parameter to the sqlite3_result_text* interfaces +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** -** The sqlite3_result_value() interface sets the result of -** the application-defined function to be a copy the -** [unprotected sqlite3_value] object specified by the 2nd parameter. The +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] -** so that the [sqlite3_value] specified in the parameter may change or +** so that [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. -** A [protected sqlite3_value] object may always be used where an -** [unprotected sqlite3_value] object is required, so either -** kind of [sqlite3_value] object can be used with this interface. ** -** If these routines are called from within the different thread -** than the one containing the application-defined function that received +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved ** the [sqlite3_context] pointer, the results are undefined. -** -** INVARIANTS: -** -** {F16403} The default return value from any SQL function is NULL. -** -** {F16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the -** return value of function C to be a BLOB that is N bytes -** in length and with content pointed to by V. -** -** {F16409} The [sqlite3_result_double(C,V)] interface changes the -** return value of function C to be the floating point value V. -** -** {F16412} The [sqlite3_result_error(C,V,N)] interface changes the return -** value of function C to be an exception with error code -** [SQLITE_ERROR] and a UTF-8 error message copied from V up to the -** first zero byte or until N bytes are read if N is positive. -** -** {F16415} The [sqlite3_result_error16(C,V,N)] interface changes the return -** value of function C to be an exception with error code -** [SQLITE_ERROR] and a UTF-16 native byte order error message -** copied from V up to the first zero terminator or until N bytes -** are read if N is positive. -** -** {F16418} The [sqlite3_result_error_toobig(C)] interface changes the return -** value of the function C to be an exception with error code -** [SQLITE_TOOBIG] and an appropriate error message. -** -** {F16421} The [sqlite3_result_error_nomem(C)] interface changes the return -** value of the function C to be an exception with error code -** [SQLITE_NOMEM] and an appropriate error message. -** -** {F16424} The [sqlite3_result_error_code(C,E)] interface changes the return -** value of the function C to be an exception with error code E. -** The error message text is unchanged. -** -** {F16427} The [sqlite3_result_int(C,V)] interface changes the -** return value of function C to be the 32-bit integer value V. -** -** {F16430} The [sqlite3_result_int64(C,V)] interface changes the -** return value of function C to be the 64-bit integer value V. -** -** {F16433} The [sqlite3_result_null(C)] interface changes the -** return value of function C to be NULL. -** -** {F16436} The [sqlite3_result_text(C,V,N,D)] interface changes the -** return value of function C to be the UTF-8 string -** V up to the first zero if N is negative -** or the first N bytes of V if N is non-negative. -** -** {F16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the -** return value of function C to be the UTF-16 native byte order -** string V up to the first zero if N is negative -** or the first N bytes of V if N is non-negative. -** -** {F16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the -** return value of function C to be the UTF-16 big-endian -** string V up to the first zero if N is negative -** or the first N bytes or V if N is non-negative. -** -** {F16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the -** return value of function C to be the UTF-16 little-endian -** string V up to the first zero if N is negative -** or the first N bytes of V if N is non-negative. -** -** {F16448} The [sqlite3_result_value(C,V)] interface changes the -** return value of function C to be the [unprotected sqlite3_value] -** object V. -** -** {F16451} The [sqlite3_result_zeroblob(C,N)] interface changes the -** return value of function C to be an N-byte BLOB of all zeros. -** -** {F16454} The [sqlite3_result_error()] and [sqlite3_result_error16()] -** interfaces make a copy of their error message strings before -** returning. -** -** {F16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)], -** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)], -** [sqlite3_result_text16be(C,V,N,D)], or -** [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC] -** then no destructor is ever called on the pointer V and SQLite -** assumes that V is immutable. -** -** {F16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)], -** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)], -** [sqlite3_result_text16be(C,V,N,D)], or -** [sqlite3_result_text16le(C,V,N,D)] is the constant -** [SQLITE_TRANSIENT] then the interfaces makes a copy of the -** content of V and retains the copy. -** -** {F16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)], -** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)], -** [sqlite3_result_text16be(C,V,N,D)], or -** [sqlite3_result_text16le(C,V,N,D)] is some value other than -** the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then -** SQLite will invoke the destructor D with V as its only argument -** when it has finished with the V value. */ SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_double(sqlite3_context*, double); @@ -4836,7 +3080,6 @@ SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*); SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*); -SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int); SQLITE_API void sqlite3_result_int(sqlite3_context*, int); SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); SQLITE_API void sqlite3_result_null(sqlite3_context*); @@ -4850,93 +3093,52 @@ SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); /* ** CAPI3REF: Define New Collating Sequences {F16600} ** +** {F16601} ** These functions are used to add new collation sequences to the -** [database connection] specified as the first argument. +** [sqlite3*] handle specified as the first argument. ** +** {F16602} ** The name of the new collation sequence is specified as a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() -** and a UTF-16 string for sqlite3_create_collation16(). In all cases +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases ** the name is passed as the second function argument. ** +** {F16604} ** The third argument may be one of the constants [SQLITE_UTF8], ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied ** routine expects to be passed pointers to strings encoded using UTF-8, -** UTF-16 little-endian, or UTF-16 big-endian, respectively. The +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that ** the routine expects pointers to 16-bit word aligned strings -** of UTF-16 in the native byte order of the host computer. +** of UTF16 in the native byte order of the host computer. ** +** {F16607} ** A pointer to the user supplied routine must be passed as the fifth -** argument. If it is NULL, this is the same as deleting the collation +** argument. {F16609} If it is NULL, this is the same as deleting the collation ** sequence (so that SQLite cannot call it anymore). -** Each time the application supplied function is invoked, it is passed -** as its first parameter a copy of the void* passed as the fourth argument -** to sqlite3_create_collation() or sqlite3_create_collation16(). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. ** +** {F16612} ** The remaining arguments to the application-supplied routine are two strings, -** each represented by a (length, data) pair and encoded in the encoding +** each represented by a [length, data] pair and encoded in the encoding ** that was passed as the third argument when the collation sequence was -** registered. {END} The application defined collation routine should -** return negative, zero or positive if the first string is less than, -** equal to, or greater than the second string. i.e. (STRING1 - STRING2). +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). ** +** {F16615} ** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** except that it takes an extra argument which is a destructor for -** the collation. The destructor is called when the collation is +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is ** destroyed and is passed a copy of the fourth parameter void* pointer ** of the sqlite3_create_collation_v2(). -** Collations are destroyed when they are overridden by later calls to the -** collation creation functions or when the [database connection] is closed -** using [sqlite3_close()]. -** -** INVARIANTS: -** -** {F16603} A successful call to the -** [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface -** registers function F as the comparison function used to -** implement collation X on the [database connection] B for -** databases having encoding E. -** -** {F16604} SQLite understands the X parameter to -** [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated -** UTF-8 string in which case is ignored for ASCII characters and -** is significant for non-ASCII characters. -** -** {F16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)] -** with the same values for B, X, and E, override prior values -** of P, F, and D. -** -** {F16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)] -** is not NULL then it is called with argument P when the -** collating function is dropped by SQLite. -** -** {F16612} A collating function is dropped when it is overloaded. -** -** {F16615} A collating function is dropped when the database connection -** is closed using [sqlite3_close()]. -** -** {F16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)] -** is passed through as the first parameter to the comparison -** function F for all subsequent invocations of F. -** -** {F16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly -** the same as a call to [sqlite3_create_collation_v2()] with -** the same parameters and a NULL destructor. -** -** {F16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)], -** SQLite uses the comparison function F for all text comparison -** operations on the [database connection] B on text values that -** use the collating sequence named X. -** -** {F16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same -** as [sqlite3_create_collation(B,X,E,P,F)] except that the -** collation name X is understood as UTF-16 in native byte order -** instead of UTF-8. -** -** {F16630} When multiple comparison functions are available for the same -** collating sequence, SQLite chooses the one whose text encoding -** requires the least amount of conversion from the default -** text encoding of the database. +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. */ SQLITE_API int sqlite3_create_collation( sqlite3*, @@ -4955,7 +3157,7 @@ SQLITE_API int sqlite3_create_collation_v2( ); SQLITE_API int sqlite3_create_collation16( sqlite3*, - const void *zName, + const char *zName, int eTextRep, void*, int(*xCompare)(void*,int,const void*,int,const void*) @@ -4964,47 +3166,31 @@ SQLITE_API int sqlite3_create_collation16( /* ** CAPI3REF: Collation Needed Callbacks {F16700} ** +** {F16701} ** To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the -** [database connection] to be called whenever an undefined collation -** sequence is required. +** database handle to be called whenever an undefined collation sequence is +** required. ** +** {F16702} ** If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings -** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, -** the names are passed as UTF-16 in machine native byte order. -** A call to either function replaces any existing callback. +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. ** -** When the callback is invoked, the first argument passed is a copy +** {F16705} When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or -** sqlite3_collation_needed16(). The second argument is the database -** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], -** or [SQLITE_UTF16LE], indicating the most desirable form of the collation -** sequence function required. The fourth parameter is the name of the -** required collation sequence. +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. -** -** INVARIANTS: -** -** {F16702} A successful call to [sqlite3_collation_needed(D,P,F)] -** or [sqlite3_collation_needed16(D,P,F)] causes -** the [database connection] D to invoke callback F with first -** parameter P whenever it needs a comparison function for a -** collating sequence that it does not know about. -** -** {F16704} Each successful call to [sqlite3_collation_needed()] or -** [sqlite3_collation_needed16()] overrides the callback registered -** on the same [database connection] by prior calls to either -** interface. -** -** {F16706} The name of the requested collating function passed in the -** 4th parameter to the callback is in UTF-8 if the callback -** was registered using [sqlite3_collation_needed()] and -** is in UTF-16 native byte order if the callback was -** registered using [sqlite3_collation_needed16()]. */ SQLITE_API int sqlite3_collation_needed( sqlite3*, @@ -5043,198 +3229,104 @@ SQLITE_API int sqlite3_rekey( ); /* -** CAPI3REF: Suspend Execution For A Short Time {F10530} +** CAPI3REF: Suspend Execution For A Short Time {F10530} ** -** The sqlite3_sleep() function causes the current thread to suspend execution +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** -** If the operating system does not support sleep requests with -** millisecond time resolution, then the time will be rounded up to -** the nearest second. The number of milliseconds of sleep actually +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually ** requested from the operating system is returned. ** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -** -** INVARIANTS: -** -** {F10533} The [sqlite3_sleep(M)] interface invokes the xSleep -** method of the default [sqlite3_vfs|VFS] in order to -** suspend execution of the current thread for at least -** M milliseconds. -** -** {F10536} The [sqlite3_sleep(M)] interface returns the number of -** milliseconds of sleep actually requested of the operating -** system, which might be larger than the parameter M. +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} */ SQLITE_API int sqlite3_sleep(int); /* -** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} ** ** If this global variable is made to point to a string which is -** the name of a folder (a.k.a. directory), then all temporary files +** the name of a folder (a.ka. directory), then all temporary files ** created by SQLite will be placed in that directory. If this variable -** is a NULL pointer, then SQLite performs a search for an appropriate -** temporary file directory. +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. ** -** It is not safe to modify this variable once a [database connection] +** It is not safe to modify this variable once a database connection ** has been opened. It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been call and remain unchanged thereafter. */ -SQLITE_API char *sqlite3_temp_directory; +SQLITE_EXTERN char *sqlite3_temp_directory; /* -** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} -** KEYWORDS: {autocommit mode} +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} ** -** The sqlite3_get_autocommit() interface returns non-zero or +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or ** zero if the given database connection is or is not in autocommit mode, -** respectively. Autocommit mode is on by default. -** Autocommit mode is disabled by a [BEGIN] statement. -** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} ** ** If certain kinds of errors occur on a statement within a multi-statement -** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the -** transaction might be rolled back automatically. The only way to -** find out whether SQLite automatically rolled back the transaction after -** an error is to use this function. +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} ** -** INVARIANTS: -** -** {F12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or -** zero if the [database connection] D is or is not in autocommit -** mode, respectively. -** -** {F12932} Autocommit mode is on by default. -** -** {F12933} Autocommit mode is disabled by a successful [BEGIN] statement. -** -** {F12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK] -** statement. -** -** LIMITATIONS: -** -** {A12936} If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} */ SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* -** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} ** -** The sqlite3_db_handle interface returns the [database connection] handle -** to which a [prepared statement] belongs. The database handle returned by -** sqlite3_db_handle is the same database handle that was the first argument -** to the [sqlite3_prepare_v2()] call (or its variants) that was used to -** create the statement in the first place. -** -** INVARIANTS: -** -** {F13123} The [sqlite3_db_handle(S)] interface returns a pointer -** to the [database connection] associated with the -** [prepared statement] S. +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. */ SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*); -/* -** CAPI3REF: Find the next prepared statement {F13140} -** -** This interface returns a pointer to the next [prepared statement] after -** pStmt associated with the [database connection] pDb. If pStmt is NULL -** then this interface returns a pointer to the first prepared statement -** associated with the database connection pDb. If no prepared statement -** satisfies the conditions of this routine, it returns NULL. -** -** INVARIANTS: -** -** {F13143} If D is a [database connection] that holds one or more -** unfinalized [prepared statements] and S is a NULL pointer, -** then [sqlite3_next_stmt(D, S)] routine shall return a pointer -** to one of the prepared statements associated with D. -** -** {F13146} If D is a [database connection] that holds no unfinalized -** [prepared statements] and S is a NULL pointer, then -** [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer. -** -** {F13149} If S is a [prepared statement] in the [database connection] D -** and S is not the last prepared statement in D, then -** [sqlite3_next_stmt(D, S)] routine shall return a pointer -** to the next prepared statement in D after S. -** -** {F13152} If S is the last [prepared statement] in the -** [database connection] D then the [sqlite3_next_stmt(D, S)] -** routine shall return a NULL pointer. -*/ -SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} ** -** The sqlite3_commit_hook() interface registers a callback +** {F12951} The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is committed. -** Any callback set by a previous call to sqlite3_commit_hook() +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. -** The sqlite3_rollback_hook() interface registers a callback +** {F12953} The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is committed. -** Any callback set by a previous call to sqlite3_commit_hook() +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. -** The pArg argument is passed through to the callback. -** If the callback on a commit hook function returns non-zero, -** then the commit is converted into a rollback. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. ** -** If another function was previously registered, its +** {F12958} If another function was previously registered, its ** pArg value is returned. Otherwise NULL is returned. ** -** Registering a NULL function disables the callback. +** {F12959} Registering a NULL function disables the callback. ** -** For the purposes of this API, a transaction is said to have been +** {F12961} For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. -** The rollback callback is not invoked if a transaction is +** {F12962} The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. -** The rollback callback is not invoked if a transaction is +** {F12964} The rollback callback is not invoked if a transaction is ** rolled back because a commit callback returned non-zero. -** Check on this +** Check on this {END} ** -** INVARIANTS: -** -** {F12951} The [sqlite3_commit_hook(D,F,P)] interface registers the -** callback function F to be invoked with argument P whenever -** a transaction commits on the [database connection] D. -** -** {F12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument -** from the previous call with the same [database connection] D, -** or NULL on the first call for a particular database connection D. -** -** {F12953} Each call to [sqlite3_commit_hook()] overwrites the callback -** registered by prior calls. -** -** {F12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL -** then the commit hook callback is canceled and no callback -** is invoked when a transaction commits. -** -** {F12955} If the commit callback returns non-zero then the commit is -** converted into a rollback. -** -** {F12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the -** callback function F to be invoked with argument P whenever -** a transaction rolls back on the [database connection] D. -** -** {F12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P -** argument from the previous call with the same -** [database connection] D, or NULL on the first call -** for a particular database connection D. -** -** {F12963} Each call to [sqlite3_rollback_hook()] overwrites the callback -** registered by prior calls. -** -** {F12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL -** then the rollback hook callback is canceled and no callback -** is invoked when a transaction rolls back. +** These are experimental interfaces and are subject to change. */ SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); @@ -5242,60 +3334,32 @@ SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks {F12970} ** -** The sqlite3_update_hook() interface registers a callback function -** with the [database connection] identified by the first argument -** to be invoked whenever a row is updated, inserted or deleted. -** Any callback set by a previous call to this function -** for the same database connection is overridden. +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. ** -** The second argument is a pointer to the function to invoke when a -** row is updated, inserted or deleted. -** The first argument to the callback is a copy of the third argument -** to sqlite3_update_hook(). -** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], -** or [SQLITE_UPDATE], depending on the operation that caused the callback -** to be invoked. -** The third and fourth arguments to the callback contain pointers to the -** database and table name containing the affected row. -** The final callback parameter is the rowid of the row. In the case of -** an update, this is the rowid after the update takes place. +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. ** -** The update hook is not invoked when internal system tables are +** {F12983} The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence). ** -** If another function was previously registered, its pArg value -** is returned. Otherwise NULL is returned. -** -** INVARIANTS: -** -** {F12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback -** function F to be invoked with first parameter P whenever -** a table row is modified, inserted, or deleted on -** the [database connection] D. -** -** {F12973} The [sqlite3_update_hook(D,F,P)] interface returns the value -** of P for the previous call on the same [database connection] D, -** or NULL for the first call. -** -** {F12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)] -** is NULL then the no update callbacks are made. -** -** {F12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls -** to the same interface on the same [database connection] D. -** -** {F12979} The update hook callback is not invoked when internal system -** tables such as sqlite_master and sqlite_sequence are modified. -** -** {F12981} The second parameter to the update callback -** is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], -** depending on the operation that caused the callback to be invoked. -** -** {F12983} The third and fourth arguments to the callback contain pointers -** to zero-terminated UTF-8 strings which are the names of the -** database and table that is being updated. - -** {F12985} The final callback parameter is the rowid of the row after -** the change occurs. +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. */ SQLITE_API void *sqlite3_update_hook( sqlite3*, @@ -5304,177 +3368,135 @@ SQLITE_API void *sqlite3_update_hook( ); /* -** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} -** KEYWORDS: {shared cache} {shared cache mode} +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} ** +** {F10331} ** This routine enables or disables the sharing of the database cache -** and schema data structures between [database connection | connections] -** to the same database. Sharing is enabled if the argument is true -** and disabled if the argument is false. +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. ** -** Cache sharing is enabled and disabled for an entire process. {END} -** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, -** sharing was enabled or disabled for each thread separately. +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. ** +** {F10334} ** The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. -** Existing database connections continue use the sharing mode -** that was in effect at the time they were opened. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} ** -** Virtual tables cannot be used with a shared cache. When shared +** Virtual tables cannot be used with a shared cache. {F10336} When shared ** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. +** virtual tables will always return an error. {END} ** -** This routine returns [SQLITE_OK] if shared cache was enabled or disabled -** successfully. An [error code] is returned otherwise. +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} ** -** Shared cache is disabled by default. But this might change in +** {F10339} Shared cache is disabled by default. {END} But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. -** -** INVARIANTS: -** -** {F10331} A successful invocation of [sqlite3_enable_shared_cache(B)] -** will enable or disable shared cache mode for any subsequently -** created [database connection] in the same process. -** -** {F10336} When shared cache is enabled, the [sqlite3_create_module()] -** interface will always return an error. -** -** {F10337} The [sqlite3_enable_shared_cache(B)] interface returns -** [SQLITE_OK] if shared cache was enabled or disabled successfully. -** -** {F10339} Shared cache is disabled by default. */ SQLITE_API int sqlite3_enable_shared_cache(int); /* -** CAPI3REF: Attempt To Free Heap Memory {F17340} +** CAPI3REF: Attempt To Free Heap Memory {F17340} ** -** The sqlite3_release_memory() interface attempts to free N bytes -** of heap memory by deallocating non-essential memory allocations -** held by the database library. {END} Memory used to cache database -** pages to improve performance is an example of non-essential memory. -** sqlite3_release_memory() returns the number of bytes actually freed, -** which might be more or less than the amount requested. -** -** INVARIANTS: -** -** {F17341} The [sqlite3_release_memory(N)] interface attempts to -** free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library. -** -** {F16342} The [sqlite3_release_memory(N)] returns the number -** of bytes actually freed, which might be more or less -** than the amount requested. +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. */ SQLITE_API int sqlite3_release_memory(int); /* -** CAPI3REF: Impose A Limit On Heap Size {F17350} +** CAPI3REF: Impose A Limit On Heap Size {F17350} ** -** The sqlite3_soft_heap_limit() interface places a "soft" limit -** on the amount of heap memory that may be allocated by SQLite. -** If an internal allocation is requested that would exceed the -** soft heap limit, [sqlite3_release_memory()] is invoked one or -** more times to free up some space before the allocation is performed. +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} ** -** The limit is called "soft", because if [sqlite3_release_memory()] -** cannot free sufficient memory to prevent the limit from being exceeded, +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, ** the memory is allocated anyway and the current operation proceeds. ** +** {F16354} ** A negative or zero value for N means that there is no soft heap limit and ** [sqlite3_release_memory()] will only be called when memory is exhausted. -** The default value for the soft heap limit is zero. +** {F16355} The default value for the soft heap limit is zero. ** -** SQLite makes a best effort to honor the soft heap limit. -** But if the soft heap limit cannot be honored, execution will -** continue without error or notification. This is why the limit is +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is ** called a "soft" limit. It is advisory only. ** ** Prior to SQLite version 3.5.0, this routine only constrained the memory ** allocated by a single thread - the same thread in which this routine ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is -** applied to all threads. The value specified for the soft heap limit -** is an upper bound on the total memory allocation for all threads. In +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In ** version 3.5.0 there is no mechanism for limiting the heap usage for ** individual threads. -** -** INVARIANTS: -** -** {F16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit -** of N bytes on the amount of heap memory that may be allocated -** using [sqlite3_malloc()] or [sqlite3_realloc()] at any point -** in time. -** -** {F16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would -** cause the total amount of allocated memory to exceed the -** soft heap limit, then [sqlite3_release_memory()] is invoked -** in an attempt to reduce the memory usage prior to proceeding -** with the memory allocation attempt. -** -** {F16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger -** attempts to reduce memory usage through the soft heap limit -** mechanism continue even if the attempt to reduce memory -** usage is unsuccessful. -** -** {F16354} A negative or zero value for N in a call to -** [sqlite3_soft_heap_limit(N)] means that there is no soft -** heap limit and [sqlite3_release_memory()] will only be -** called when memory is completely exhausted. -** -** {F16355} The default value for the soft heap limit is zero. -** -** {F16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the -** values set by all prior calls. */ SQLITE_API void sqlite3_soft_heap_limit(int); /* -** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} ** -** This routine returns metadata about a specific column of a specific -** database table accessible using the [database connection] handle -** passed as the first function argument. +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. ** -** The column is identified by the second, third and fourth parameters to +** The column is identified by the second, third and fourth parameters to ** this function. The second parameter is either the name of the database ** (i.e. "main", "temp" or an attached database) containing the specified ** table or NULL. If it is NULL, then all attached databases are searched -** for the table using the same algorithm used by the database engine to +** for the table using the same algorithm as the database engine uses to ** resolve unqualified table references. ** -** The third and fourth parameters to this function are the table and column -** name of the desired column, respectively. Neither of these parameters +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters ** may be NULL. ** -** Metadata is returned by writing to the memory locations passed as the 5th -** and subsequent parameters to this function. Any of these arguments may be -** NULL, in which case the corresponding element of metadata is omitted. +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. ** -**
      -** -**
      Parameter Output
      Type
      Description +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
       **
      -** 
      5th const char* Data type -**
      6th const char* Name of default collation sequence -**
      7th int True if column has a NOT NULL constraint -**
      8th int True if column is part of the PRIMARY KEY -**
      9th int True if column is AUTOINCREMENT -**
      -**
      +** 5th const char* Data type +** 6th const char* Name of the default collation sequence +** 7th int True if the column has a NOT NULL constraint +** 8th int True if the column is part of the PRIMARY KEY +** 9th int True if the column is AUTOINCREMENT +** ** -** The memory pointed to by the character pointers returned for the -** declaration type and collation sequence is valid only until the next -** call to any SQLite API function. ** -** If the specified table is actually a view, an [error code] is returned. +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. ** -** If the specified column is "rowid", "oid" or "_rowid_" and an -** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. If there is no -** explicitly declared INTEGER PRIMARY KEY column, then the output -** parameters are set as follows: +** explicitly declared IPK column, then the output parameters are set as +** follows: ** **
       **     data type: "INTEGER"
      @@ -5486,11 +3508,11 @@ SQLITE_API void sqlite3_soft_heap_limit(int);
       **
       ** This function may load one or more schemas from database files. If an
       ** error occurs during this process, or if the requested table or column
      -** cannot be found, an [error code] is returned and an error message left
      -** in the [database connection] (to be retrieved using sqlite3_errmsg()).
      +** cannot be found, an SQLITE error code is returned and an error message
      +** left in the database handle (to be retrieved using sqlite3_errmsg()).
       **
       ** This API is only available if the library was compiled with the
      -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
      +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
       */
       SQLITE_API int sqlite3_table_column_metadata(
         sqlite3 *db,                /* Connection handle */
      @@ -5507,28 +3529,25 @@ SQLITE_API int sqlite3_table_column_metadata(
       /*
       ** CAPI3REF: Load An Extension {F12600}
       **
      -** This interface loads an SQLite extension library from the named file.
      +** {F12601} The sqlite3_load_extension() interface
      +** attempts to load an SQLite extension library contained in the file
      +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
      +** in which case the name of the entry point defaults
      +** to "sqlite3_extension_init".
       **
      -** {F12601} The sqlite3_load_extension() interface attempts to load an
      -**          SQLite extension library contained in the file zFile.
      +** {F12604} The sqlite3_load_extension() interface shall
      +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
       **
      -** {F12602} The entry point is zProc.
      +** {F12605}
      +** If an error occurs and pzErrMsg is not 0, then the
      +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
      +** error message text stored in memory obtained from [sqlite3_malloc()].
      +** {END}  The calling function should free this memory
      +** by calling [sqlite3_free()].
       **
      -** {F12603} zProc may be 0, in which case the name of the entry point
      -**          defaults to "sqlite3_extension_init".
      -**
      -** {F12604} The sqlite3_load_extension() interface shall return
      -**          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
      -**
      -** {F12605} If an error occurs and pzErrMsg is not 0, then the
      -**          [sqlite3_load_extension()] interface shall attempt to
      -**          fill *pzErrMsg with error message text stored in memory
      -**          obtained from [sqlite3_malloc()]. {END}  The calling function
      -**          should free this memory by calling [sqlite3_free()].
      -**
      -** {F12606} Extension loading must be enabled using
      -**          [sqlite3_enable_load_extension()] prior to calling this API,
      -**          otherwise an error will be returned.
      +** {F12606}
      +** Extension loading must be enabled using [sqlite3_enable_load_extension()]
      +** prior to calling this API or an error will be returned.
       */
       SQLITE_API int sqlite3_load_extension(
         sqlite3 *db,          /* Load the extension into this database connection */
      @@ -5538,64 +3557,65 @@ SQLITE_API int sqlite3_load_extension(
       );
       
       /*
      -** CAPI3REF: Enable Or Disable Extension Loading {F12620}
      +** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
       **
       ** So as not to open security holes in older applications that are
       ** unprepared to deal with extension loading, and as a means of disabling
      -** extension loading while evaluating user-entered SQL, the following API
      -** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
      +** extension loading while evaluating user-entered SQL, the following
      +** API is provided to turn the [sqlite3_load_extension()] mechanism on and
      +** off.  {F12622} It is off by default. {END} See ticket #1863.
       **
      -** Extension loading is off by default. See ticket #1863.
      -**
      -** {F12621} Call the sqlite3_enable_load_extension() routine with onoff==1
      -**          to turn extension loading on and call it with onoff==0 to turn
      -**          it back off again.
      -**
      -** {F12622} Extension loading is off by default.
      +** {F12621} Call the sqlite3_enable_load_extension() routine
      +** with onoff==1 to turn extension loading on
      +** and call it with onoff==0 to turn it back off again. {END}
       */
       SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
       
       /*
       ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
       **
      +** {F12641} This function
      +** registers an extension entry point that is automatically invoked
      +** whenever a new database connection is opened using
      +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
      +**
       ** This API can be invoked at program startup in order to register
       ** one or more statically linked extensions that will be available
      -** to all new [database connections]. {END}
      +** to all new database connections.
       **
      -** This routine stores a pointer to the extension in an array that is
      -** obtained from [sqlite3_malloc()].  If you run a memory leak checker
      -** on your program and it reports a leak because of this array, invoke
      -** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
      -**
      -** {F12641} This function registers an extension entry point that is
      -**          automatically invoked whenever a new [database connection]
      -**          is opened using [sqlite3_open()], [sqlite3_open16()],
      -**          or [sqlite3_open_v2()].
      -**
      -** {F12642} Duplicate extensions are detected so calling this routine
      -**          multiple times with the same extension is harmless.
      +** {F12642} Duplicate extensions are detected so calling this routine multiple
      +** times with the same extension is harmless.
       **
       ** {F12643} This routine stores a pointer to the extension in an array
      -**          that is obtained from [sqlite3_malloc()].
      +** that is obtained from sqlite_malloc(). {END} If you run a memory leak
      +** checker on your program and it reports a leak because of this
      +** array, then invoke [sqlite3_reset_auto_extension()] prior
      +** to shutdown to free the memory.
       **
      -** {F12644} Automatic extensions apply across all threads.
      +** {F12644} Automatic extensions apply across all threads. {END}
      +**
      +** This interface is experimental and is subject to change or
      +** removal in future releases of SQLite.
       */
       SQLITE_API int sqlite3_auto_extension(void *xEntryPoint);
       
      +
       /*
       ** CAPI3REF: Reset Automatic Extension Loading {F12660}
       **
      -** This function disables all previously registered automatic
      -** extensions. {END}  It undoes the effect of all prior
      -** [sqlite3_auto_extension()] calls.
      -**
       ** {F12661} This function disables all previously registered
      -**          automatic extensions.
      +** automatic extensions. {END}  This
      +** routine undoes the effect of all prior [sqlite3_automatic_extension()]
      +** calls.
       **
      -** {F12662} This function disables automatic extensions in all threads.
      +** {F12662} This call disabled automatic extensions in all threads. {END}
      +**
      +** This interface is experimental and is subject to change or
      +** removal in future releases of SQLite.
       */
       SQLITE_API void sqlite3_reset_auto_extension(void);
       
      +
       /*
       ****** EXPERIMENTAL - subject to change without notice **************
       **
      @@ -5603,7 +3623,7 @@ SQLITE_API void sqlite3_reset_auto_extension(void);
       ** to be experimental.  The interface might change in incompatible ways.
       ** If this is a problem for you, do not use the interface at this time.
       **
      -** When the virtual-table mechanism stabilizes, we will declare the
      +** When the virtual-table mechanism stablizes, we will declare the
       ** interface fixed, support it indefinitely, and remove this comment.
       */
       
      @@ -5616,15 +3636,9 @@ typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
       typedef struct sqlite3_module sqlite3_module;
       
       /*
      -** CAPI3REF: Virtual Table Object {F18000}
      -** KEYWORDS: sqlite3_module
      -**
       ** A module is a class of virtual tables.  Each module is defined
       ** by an instance of the following structure.  This structure consists
       ** mostly of methods for the module.
      -**
      -** This interface is experimental and is subject to change or
      -** removal in future releases of SQLite.
       */
       struct sqlite3_module {
         int iVersion;
      @@ -5658,21 +3672,20 @@ struct sqlite3_module {
       };
       
       /*
      -** CAPI3REF: Virtual Table Indexing Information {F18100}
      -** KEYWORDS: sqlite3_index_info
      -**
       ** The sqlite3_index_info structure and its substructures is used to
       ** pass information into and receive the reply from the xBestIndex
       ** method of an sqlite3_module.  The fields under **Inputs** are the
       ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
       ** results into the **Outputs** fields.
       **
      -** The aConstraint[] array records WHERE clause constraints of the form:
      +** The aConstraint[] array records WHERE clause constraints of the
      +** form:
       **
      -** 
      column OP expr
      +** column OP expr ** -** where OP is =, <, <=, >, or >=. The particular operator is -** stored in aConstraint[].op. The index of the column is stored in +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot. @@ -5704,9 +3717,6 @@ struct sqlite3_module { ** particular lookup. A full scan of a table with N entries should have ** a cost of N. A binary search of a table of N entries should have a ** cost of approximately log(N). -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ struct sqlite3_index_info { /* Inputs */ @@ -5742,15 +3752,10 @@ struct sqlite3_index_info { #define SQLITE_INDEX_CONSTRAINT_MATCH 64 /* -** CAPI3REF: Register A Virtual Table Implementation {F18200} -** -** This routine is used to register a new module name with a -** [database connection]. Module names must be registered before -** creating new virtual tables on the module, or before using -** preexisting virtual tables of the module. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. */ SQLITE_API int sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ @@ -5760,9 +3765,7 @@ SQLITE_API int sqlite3_create_module( ); /* -** CAPI3REF: Register A Virtual Table Implementation {F18210} -** -** This routine is identical to the [sqlite3_create_module()] method above, +** This routine is identical to the sqlite3_create_module() method above, ** except that it allows a destructor function to be specified. It is ** even more experimental than the rest of the virtual tables API. */ @@ -5775,27 +3778,21 @@ SQLITE_API int sqlite3_create_module_v2( ); /* -** CAPI3REF: Virtual Table Instance Object {F18010} -** KEYWORDS: sqlite3_vtab -** ** Every module implementation uses a subclass of the following structure ** to describe a particular instance of the module. Each subclass will -** be tailored to the specific needs of the module implementation. -** The purpose of this superclass is to define certain fields that are -** common to all module implementations. +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. ** ** Virtual tables methods can set an error message by assigning a -** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should -** take care that any prior string is freed by a call to [sqlite3_free()] +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() ** prior to assigning a new string to zErrMsg. After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field ** since virtual tables are commonly implemented in loadable extensions which ** do not have access to sqlite3MPrintf() or sqlite3Free(). -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ @@ -5804,11 +3801,7 @@ struct sqlite3_vtab { /* Virtual table implementations will typically add additional fields */ }; -/* -** CAPI3REF: Virtual Table Cursor Object {F18020} -** KEYWORDS: sqlite3_vtab_cursor -** -** Every module implementation uses a subclass of the following structure +/* Every module implementation uses a subclass of the following structure ** to describe cursors that point into the virtual table and are used ** to loop through the virtual table. Cursors are created using the ** xOpen method of the module. Each module implementation will define @@ -5816,9 +3809,6 @@ struct sqlite3_vtab { ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ struct sqlite3_vtab_cursor { sqlite3_vtab *pVtab; /* Virtual table of this cursor */ @@ -5826,20 +3816,13 @@ struct sqlite3_vtab_cursor { }; /* -** CAPI3REF: Declare The Schema Of A Virtual Table {F18280} -** ** The xCreate and xConnect methods of a module use the following API ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); /* -** CAPI3REF: Overload A Function For A Virtual Table {F18300} -** ** Virtual tables can provide alternative implementations of functions ** using the xFindFunction method. But global versions of those functions ** must exist in order to be overloaded. @@ -5849,7 +3832,7 @@ SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); ** before this API is called, a new function is created. The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only -** purpose is to be a placeholder function that can be overloaded +** purpose is to be a place-holder function that can be overloaded ** by virtual tables. ** ** This API should be considered part of the virtual table interface, @@ -5871,82 +3854,40 @@ SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nA /* ** CAPI3REF: A Handle To An Open BLOB {F17800} -** KEYWORDS: {BLOB handle} {BLOB handles} ** -** An instance of this object represents an open BLOB on which -** [sqlite3_blob_open | incremental BLOB I/O] can be performed. -** Objects of this type are created by [sqlite3_blob_open()] -** and destroyed by [sqlite3_blob_close()]. +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces -** can be used to read or write small subsections of the BLOB. -** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O {F17810} ** -** This interfaces opens a [BLOB handle | handle] to the BLOB located -** in row iRow, column zColumn, table zTable in database zDb; -** in other words, the same BLOB that would be selected by: +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: ** **
       **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
       ** 
      {END} ** -** If the flags parameter is non-zero, the the BLOB is opened for read -** and write access. If it is zero, the BLOB is opened for read access. +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} ** -** Note that the database name is not the filename that contains -** the database but rather the symbolic name of the database that -** is assigned when the database is connected using [ATTACH]. -** For the main database file, the database name is "main". -** For TEMP tables, the database name is "temp". -** -** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written -** to *ppBlob. Otherwise an [error code] is returned and any value written -** to *ppBlob should not be used by the caller. -** This function sets the [database connection] error code and message +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -** -** If the row that a BLOB handle points to is modified by an -** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects -** then the BLOB handle is marked as "expired". -** This is true if any column of the row is changed, even a column -** other than the one the BLOB handle is open on. -** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for -** a expired BLOB handle fail with an return code of [SQLITE_ABORT]. -** Changes written into a BLOB prior to the BLOB expiring are not -** rollback by the expiration of the BLOB. Such changes will eventually -** commit if the transaction continues to completion. -** -** INVARIANTS: -** -** {F17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)] -** interface shall open an [sqlite3_blob] object P on the BLOB -** in column C of the table T in the database B on -** the [database connection] D. -** -** {F17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start -** a new transaction on the [database connection] D if that -** connection is not already in a transaction. -** -** {F17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open -** the BLOB for read and write access if and only if the F -** parameter is non-zero. -** -** {F17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on -** success and an appropriate [error code] on failure. -** -** {F17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)] -** then subsequent calls to [sqlite3_errcode(D)], -** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return -** information appropriate for that error. -** -** {F17824} If any column in the row that a [sqlite3_blob] has open is -** changed by a separate [UPDATE] or [DELETE] statement or by -** an [ON CONFLICT] side effect, then the [sqlite3_blob] shall -** be marked as invalid. +** We should go through and mark all interfaces that behave this +** way with a similar statement */ SQLITE_API int sqlite3_blob_open( sqlite3*, @@ -5959,228 +3900,104 @@ SQLITE_API int sqlite3_blob_open( ); /* -** CAPI3REF: Close A BLOB Handle {F17830} +** CAPI3REF: Close A BLOB Handle {F17830} ** -** Closes an open [BLOB handle]. +** Close an open [sqlite3_blob | blob handle]. ** -** Closing a BLOB shall cause the current transaction to commit +** {F17831} Closing a BLOB shall cause the current transaction to commit ** if there are no other BLOBs, no pending prepared statements, and the -** database connection is in [autocommit mode]. -** If any writes were made to the BLOB, they might be held in cache +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache ** until the close operation if they will fit. {END} -** ** Closing the BLOB often forces the changes ** out to disk and so if any I/O errors occur, they will likely occur ** at the time when the BLOB is closed. {F17833} Any errors that occur during ** closing are reported as a non-zero return value. ** -** The BLOB is closed unconditionally. Even if this routine returns +** {F17839} The BLOB is closed unconditionally. Even if this routine returns ** an error code, the BLOB is still closed. -** -** INVARIANTS: -** -** {F17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob] -** object P previously opened using [sqlite3_blob_open()]. -** -** {F17836} Closing an [sqlite3_blob] object using -** [sqlite3_blob_close()] shall cause the current transaction to -** commit if there are no other open [sqlite3_blob] objects -** or [prepared statements] on the same [database connection] and -** the database connection is in [autocommit mode]. -** -** {F17839} The [sqlite3_blob_close(P)] interfaces shall close the -** [sqlite3_blob] object P unconditionally, even if -** [sqlite3_blob_close(P)] returns something other than [SQLITE_OK]. */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* -** CAPI3REF: Return The Size Of An Open BLOB {F17840} +** CAPI3REF: Return The Size Of An Open BLOB {F17805} ** -** Returns the size in bytes of the BLOB accessible via the open -** []BLOB handle] in its only argument. -** -** INVARIANTS: -** -** {F17843} The [sqlite3_blob_bytes(P)] interface returns the size -** in bytes of the BLOB that the [sqlite3_blob] object P -** refers to. +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* -** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} ** -** This function is used to read data from an open [BLOB handle] into a -** caller-supplied buffer. N bytes of data are copied into buffer Z -** from the open BLOB, starting at offset iOffset. +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. ** -** If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is read. If N or iOffset is -** less than zero, [SQLITE_ERROR] is returned and no data is read. +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. ** -** An attempt to read from an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. -** -** On success, SQLITE_OK is returned. -** Otherwise, an [error code] or an [extended error code] is returned. -** -** INVARIANTS: -** -** {F17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)] -** shall reads N bytes of data out of the BLOB referenced by -** [BLOB handle] P beginning at offset X and store those bytes -** into buffer Z. -** -** {F17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB -** is less than N+X bytes, then the function shall leave the -** Z buffer unchanged and return [SQLITE_ERROR]. -** -** {F17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero -** then the function shall leave the Z buffer unchanged -** and return [SQLITE_ERROR]. -** -** {F17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK] -** if N bytes are successfully read into buffer Z. -** -** {F17863} If the [BLOB handle] P is expired and X and N are within bounds -** then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer -** unchanged and return [SQLITE_ABORT]. -** -** {F17865} If the requested read could not be completed, -** the [sqlite3_blob_read(P,Z,N,X)] interface shall return an -** appropriate [error code] or [extended error code]. -** -** {F17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)] -** then subsequent calls to [sqlite3_errcode(D)], -** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return -** information appropriate for that error, where D is the -** [database connection] that was used to open the [BLOB handle] P. +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. */ -SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); +SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); /* -** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} ** -** This function is used to write data into an open [BLOB handle] from a -** caller-supplied buffer. N bytes of data are copied from the buffer Z -** into the open BLOB, starting at offset iOffset. +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. ** -** If the [BLOB handle] passed as the first argument was not opened for -** writing (the flags parameter to [sqlite3_blob_open()] was zero), -** this function returns [SQLITE_READONLY]. +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. ** -** This function may only modify the contents of the BLOB; it is -** not possible to increase the size of a BLOB using this API. -** If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is written. If N is +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is ** less than zero [SQLITE_ERROR] is returned and no data is written. ** -** An attempt to write to an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. Writes to the BLOB that occurred -** before the [BLOB handle] expired are not rolled back by the -** expiration of the handle, though of course those changes might -** have been overwritten by the statement that expired the BLOB handle -** or by other independent statements. -** -** On success, SQLITE_OK is returned. -** Otherwise, an [error code] or an [extended error code] is returned. -** -** INVARIANTS: -** -** {F17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)] -** shall write N bytes of data from buffer Z into the BLOB -** referenced by [BLOB handle] P beginning at offset X into -** the BLOB. -** -** {F17874} In the absence of other overridding changes, the changes -** written to a BLOB by [sqlite3_blob_write()] shall -** remain in effect after the associated [BLOB handle] expires. -** -** {F17875} If the [BLOB handle] P was opened for reading only then -** an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave -** the referenced BLOB unchanged and return [SQLITE_READONLY]. -** -** {F17876} If the size of the BLOB referenced by [BLOB handle] P is -** less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall -** leave the BLOB unchanged and return [SQLITE_ERROR]. -** -** {F17877} If the [BLOB handle] P is expired and X and N are within bounds -** then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB -** unchanged and return [SQLITE_ABORT]. -** -** {F17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)] -** shall leave the BLOB referenced by [BLOB handle] P unchanged -** and return [SQLITE_ERROR]. -** -** {F17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return -** [SQLITE_OK] if N bytes where successfully written into the BLOB. -** -** {F17885} If the requested write could not be completed, -** the [sqlite3_blob_write(P,Z,N,X)] interface shall return an -** appropriate [error code] or [extended error code]. -** -** {F17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)] -** then subsequent calls to [sqlite3_errcode(D)], -** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return -** information appropriate for that error. +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. */ SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* -** CAPI3REF: Virtual File System Objects {F11200} +** CAPI3REF: Virtual File System Objects {F11200} ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact -** with the underlying operating system. Most SQLite builds come with a +** with the underlying operating system. Most builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. -** Names are case sensitive. -** Names are zero-terminated UTF-8 strings. -** If there is no match, a NULL pointer is returned. -** If zVfsName is NULL then the default VFS is returned. +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} ** -** New VFSes are registered with sqlite3_vfs_register(). -** Each new VFS becomes the default VFS if the makeDflt flag is set. -** The same VFS can be registered multiple times without injury. -** To make an existing VFS into the default VFS, register it again -** with the makeDflt flag set. If two different VFSes with the -** same name are registered, the behavior is undefined. If a +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. -** -** Unregister a VFS with the sqlite3_vfs_unregister() interface. -** If the default VFS is unregistered, another VFS is chosen as +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary. -** -** INVARIANTS: -** -** {F11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the -** registered [sqlite3_vfs] object whose name exactly matches -** the zero-terminated UTF-8 string N, or it returns NULL if -** there is no match. -** -** {F11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then -** the function returns a pointer to the default [sqlite3_vfs] -** object if there is one, or NULL if there is no default -** [sqlite3_vfs] object. -** -** {F11209} The [sqlite3_vfs_register(P,F)] interface registers the -** well-formed [sqlite3_vfs] object P using the name given -** by the zName field of the object. -** -** {F11212} Using the [sqlite3_vfs_register(P,F)] interface to register -** the same [sqlite3_vfs] object multiple times is a harmless no-op. -** -** {F11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs] -** object P the default [sqlite3_vfs] object if F is non-zero. -** -** {F11218} The [sqlite3_vfs_unregister(P)] interface unregisters the -** [sqlite3_vfs] object P so that it is no longer returned by -** subsequent calls to [sqlite3_vfs_find()]. */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); @@ -6190,11 +4007,11 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** CAPI3REF: Mutexes {F17000} ** ** The SQLite core uses these routines for thread -** synchronization. Though they are intended for internal +** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** -** The SQLite source code contains multiple implementations +** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: @@ -6206,19 +4023,20 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); **
    • SQLITE_MUTEX_NOOP ** ** -** The SQLITE_MUTEX_NOOP implementation is a set of routines -** that does no real locking and is appropriate for use in +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_OS2, ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations -** are appropriate for use on OS/2, Unix, and Windows. -** +** are appropriate for use on os/2, unix, and windows. +** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex -** implementation is included with the library. In this case the -** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize(). +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. ** ** {F17011} The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. {F17012} If it returns NULL @@ -6234,8 +4052,7 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); **
    • SQLITE_MUTEX_STATIC_MEM2 **
    • SQLITE_MUTEX_STATIC_PRNG **
    • SQLITE_MUTEX_STATIC_LRU -**
    • SQLITE_MUTEX_STATIC_LRU2 -** +** {END} ** ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE @@ -6257,45 +4074,41 @@ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); ** ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() -** returns a different mutex on every call. {F17034} But for the static +** returns a different mutex on every call. {F17034} But for the static ** mutex types, the same mutex is returned on every call that has -** the same type number. +** the same type number. {END} ** ** {F17019} The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every -** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in -** use when they are deallocated. {A17022} Attempting to deallocate a static +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static ** mutex results in undefined behavior. {F17023} SQLite never deallocates ** a static mutex. {END} ** ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. {F17024} If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns [SQLITE_OK] +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. {F17026} Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** {F17027} In such cases the, ** mutex must be exited an equal number of times before another thread -** can enter. {A17028} If the same thread tries to enter any other +** can enter. {U17028} If the same thread tries to enter any other ** kind of mutex more than once, the behavior is undefined. ** {F17029} SQLite will never exhibit -** such behavior in its own use of mutexes. +** such behavior in its own use of mutexes. {END} ** -** Some systems (for example, Windows 95) do not support the operation -** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() -** will always return SQLITE_BUSY. {F17030} The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} ** ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. {A17032} The behavior +** previously entered by the same thread. {U17032} The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. {F17033} SQLite will ** never do either. {END} ** -** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or -** sqlite3_mutex_leave() is a NULL pointer, then all three routines -** behave as no-ops. -** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); @@ -6305,87 +4118,26 @@ SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* -** CAPI3REF: Mutex Methods Object {F17120} -** -** An instance of this structure defines the low-level routines -** used to allocate and use mutexes. -** -** Usually, the default mutex implementations provided by SQLite are -** sufficient, however the user has the option of substituting a custom -** implementation for specialized deployments or systems for which SQLite -** does not provide a suitable implementation. In this case, the user -** creates and populates an instance of this structure to pass -** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. -** Additionally, an instance of this structure can be used as an -** output variable when querying the system for the current mutex -** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. -** -** The xMutexInit method defined by this structure is invoked as -** part of system initialization by the sqlite3_initialize() function. -** {F17001} The xMutexInit routine shall be called by SQLite once for each -** effective call to [sqlite3_initialize()]. -** -** The xMutexEnd method defined by this structure is invoked as -** part of system shutdown by the sqlite3_shutdown() function. The -** implementation of this method is expected to release all outstanding -** resources obtained by the mutex methods implementation, especially -** those obtained by the xMutexInit method. {F17003} The xMutexEnd() -** interface shall be invoked once for each call to [sqlite3_shutdown()]. -** -** The remaining seven methods defined by this structure (xMutexAlloc, -** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and -** xMutexNotheld) implement the following interfaces (respectively): -** -**
        -**
      • [sqlite3_mutex_alloc()]
      • -**
      • [sqlite3_mutex_free()]
      • -**
      • [sqlite3_mutex_enter()]
      • -**
      • [sqlite3_mutex_try()]
      • -**
      • [sqlite3_mutex_leave()]
      • -**
      • [sqlite3_mutex_held()]
      • -**
      • [sqlite3_mutex_notheld()]
      • -**
      -** -** The only difference is that the public sqlite3_XXX functions enumerated -** above silently ignore any invocations that pass a NULL pointer instead -** of a valid mutex handle. The implementations of the methods defined -** by this structure are not required to handle this case, the results -** of passing a NULL pointer instead of a valid mutex handle are undefined -** (i.e. it is acceptable to provide an implementation that segfaults if -** it is passed a NULL pointer). -*/ -typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; -struct sqlite3_mutex_methods { - int (*xMutexInit)(void); - int (*xMutexEnd)(void); - sqlite3_mutex *(*xMutexAlloc)(int); - void (*xMutexFree)(sqlite3_mutex *); - void (*xMutexEnter)(sqlite3_mutex *); - int (*xMutexTry)(sqlite3_mutex *); - void (*xMutexLeave)(sqlite3_mutex *); - int (*xMutexHeld)(sqlite3_mutex *); - int (*xMutexNotheld)(sqlite3_mutex *); -}; - -/* -** CAPI3REF: Mutex Verification Routines {F17080} +** CAPI3REF: Mutex Verifcation Routines {F17080} ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. {F17081} The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. {F17082} The core only ** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. {A17087} External mutex implementations +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** {F17083} These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. +** is held or not held, respectively, by the calling thread. {END} ** ** {X17084} The implementation is not required to provided versions of these -** routines that actually work. If the implementation does not provide working -** versions of these routines, it should at least provide stubs that always -** return true so that one does not get spurious assertion failures. +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} ** ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. {END} This seems counter-intuitive since @@ -6393,7 +4145,7 @@ struct sqlite3_mutex_methods { ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is -** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*); @@ -6403,7 +4155,7 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); ** CAPI3REF: Mutex Types {F17001} ** ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. +** which is one of these integer constants. {END} */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 @@ -6412,7 +4164,6 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); #define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ -#define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */ /* ** CAPI3REF: Low-Level Control Of Database Files {F11300} @@ -6431,8 +4182,8 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); ** {F11306} If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. {F11307} This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might -** also return SQLITE_ERROR. {A11309} There is no way to distinguish between +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. {END} ** @@ -6440,133 +4191,6 @@ SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); */ SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); -/* -** CAPI3REF: Testing Interface {F11400} -** -** The sqlite3_test_control() interface is used to read out internal -** state of SQLite and to inject faults into SQLite for testing -** purposes. The first parameter is an operation code that determines -** the number, meaning, and operation of all subsequent parameters. -** -** This interface is not for use by applications. It exists solely -** for verifying the correct operation of the SQLite library. Depending -** on how the SQLite library is compiled, this interface might not exist. -** -** The details of the operation codes, their meanings, the parameters -** they take, and what they do are all subject to change without notice. -** Unlike most of the SQLite API, this function is not guaranteed to -** operate consistently from one release to the next. -*/ -SQLITE_API int sqlite3_test_control(int op, ...); - -/* -** CAPI3REF: Testing Interface Operation Codes {F11410} -** -** These constants are the valid operation code parameters used -** as the first argument to [sqlite3_test_control()]. -** -** These parameters and their meanings are subject to change -** without notice. These values are for testing purposes only. -** Applications should not use any of these parameters or the -** [sqlite3_test_control()] interface. -*/ -#define SQLITE_TESTCTRL_PRNG_SAVE 5 -#define SQLITE_TESTCTRL_PRNG_RESTORE 6 -#define SQLITE_TESTCTRL_PRNG_RESET 7 -#define SQLITE_TESTCTRL_BITVEC_TEST 8 -#define SQLITE_TESTCTRL_FAULT_INSTALL 9 -#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 - -/* -** CAPI3REF: SQLite Runtime Status {F17200} -** -** This interface is used to retrieve runtime status information -** about the preformance of SQLite, and optionally to reset various -** highwater marks. The first argument is an integer code for -** the specific parameter to measure. Recognized integer codes -** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...]. -** The current value of the parameter is returned into *pCurrent. -** The highest recorded value is returned in *pHighwater. If the -** resetFlag is true, then the highest record value is reset after -** *pHighwater is written. Some parameters do not record the highest -** value. For those parameters -** nothing is written into *pHighwater and the resetFlag is ignored. -** Other parameters record only the highwater mark and not the current -** value. For these latter parameters nothing is written into *pCurrent. -** -** This routine returns SQLITE_OK on success and a non-zero -** [error code] on failure. -** -** This routine is threadsafe but is not atomic. This routine can -** called while other threads are running the same or different SQLite -** interfaces. However the values returned in *pCurrent and -** *pHighwater reflect the status of SQLite at different points in time -** and it is possible that another thread might change the parameter -** in between the times when *pCurrent and *pHighwater are written. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. -*/ -SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); - -/* -** CAPI3REF: Status Parameters {F17250} -** -** These integer constants designate various run-time status parameters -** that can be returned by [sqlite3_status()]. -** -**
      -**
      SQLITE_STATUS_MEMORY_USED
      -**
      This parameter is the current amount of memory checked out -** using [sqlite3_malloc()], either directly or indirectly. The -** figure includes calls made to [sqlite3_malloc()] by the application -** and internal memory usage by the SQLite library. Scratch memory -** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache -** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in -** this parameter. The amount returned is the sum of the allocation -** sizes as reported by the xSize method in [sqlite3_mem_methods].
      -** -**
      SQLITE_STATUS_PAGECACHE_USED
      -**
      This parameter returns the number of pages used out of the -** page cache buffer configured using [SQLITE_CONFIG_PAGECACHE]. The -** value returned is in pages, not in bytes.
      -** -**
      SQLITE_STATUS_PAGECACHE_OVERFLOW
      -**
      This parameter returns the number of bytes of page cache -** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE] -** buffer and where forced to overflow to [sqlite3_malloc()].
      -** -**
      SQLITE_STATUS_SCRATCH_USED
      -**
      This parameter returns the number of allocations used out of the -** scratch allocation lookaside buffer configured using -** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not -** in bytes. Since a single thread may only have one allocation -** outstanding at time, this parameter also reports the number of threads -** using scratch memory at the same time.
      -** -**
      SQLITE_STATUS_SCRATCH_OVERFLOW
      -**
      This parameter returns the number of bytes of scratch memory -** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH] -** buffer and where forced to overflow to [sqlite3_malloc()].
      -** -**
      SQLITE_STATUS_MALLOC_SIZE
      -**
      This parameter records the largest memory allocation request -** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their -** internal equivalents). The value of interest is return in the -** *pHighwater parameter to [sqlite3_status()]. The value written -** into the *pCurrent parameter is undefined.
      -**
      -** -** New status parameters may be added from time to time. -*/ -#define SQLITE_STATUS_MEMORY_USED 0 -#define SQLITE_STATUS_PAGECACHE_USED 1 -#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 -#define SQLITE_STATUS_SCRATCH_USED 3 -#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 -#define SQLITE_STATUS_MALLOC_SIZE 5 - - /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. @@ -6598,7 +4222,7 @@ SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetF ** This is the header file for the generic hash-table implemenation ** used in SQLite. ** -** $Id: hash.h,v 1.11 2007/09/04 14:31:47 danielk1977 Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef _SQLITE_HASH_H_ #define _SQLITE_HASH_H_ @@ -6860,6 +4484,8 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); #include #include +#define sqlite3_isnan(X) ((X)!=(X)) + /* ** If compiling for a processor that lacks floating point support, ** substitute integer for floating-point @@ -6915,11 +4541,11 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); #endif /* -** Provide a default value for SQLITE_TEMP_STORE in case it is not specified +** Provide a default value for TEMP_STORE in case it is not specified ** on the command-line */ -#ifndef SQLITE_TEMP_STORE -# define SQLITE_TEMP_STORE 1 +#ifndef TEMP_STORE +# define TEMP_STORE 1 #endif /* @@ -6948,39 +4574,19 @@ SQLITE_PRIVATE void sqlite3HashClear(Hash*); ** cc '-DUINTPTR_TYPE=long long int' ... */ #ifndef UINT32_TYPE -# ifdef HAVE_UINT32_T -# define UINT32_TYPE uint32_t -# else -# define UINT32_TYPE unsigned int -# endif +# define UINT32_TYPE unsigned int #endif #ifndef UINT16_TYPE -# ifdef HAVE_UINT16_T -# define UINT16_TYPE uint16_t -# else -# define UINT16_TYPE unsigned short int -# endif +# define UINT16_TYPE unsigned short int #endif #ifndef INT16_TYPE -# ifdef HAVE_INT16_T -# define INT16_TYPE int16_t -# else -# define INT16_TYPE short int -# endif +# define INT16_TYPE short int #endif #ifndef UINT8_TYPE -# ifdef HAVE_UINT8_T -# define UINT8_TYPE uint8_t -# else -# define UINT8_TYPE unsigned char -# endif +# define UINT8_TYPE unsigned char #endif #ifndef INT8_TYPE -# ifdef HAVE_INT8_T -# define INT8_TYPE int8_t -# else -# define INT8_TYPE signed char -# endif +# define INT8_TYPE signed char #endif #ifndef LONGDOUBLE_TYPE # define LONGDOUBLE_TYPE long double @@ -6998,7 +4604,7 @@ typedef UINT8_TYPE i8; /* 1-byte signed integer */ ** evaluated at runtime. */ #ifdef SQLITE_AMALGAMATION -SQLITE_PRIVATE const int sqlite3one; +SQLITE_PRIVATE const int sqlite3One; #else SQLITE_PRIVATE const int sqlite3one; #endif @@ -7012,14 +4618,6 @@ SQLITE_PRIVATE const int sqlite3one; # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE) #endif -/* -** Constants for the largest and smallest possible 64-bit signed integers. -** These macros are designed to work correctly on both 32-bit and 64-bit -** compilers. -*/ -#define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32)) -#define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64) - /* ** An instance of the following structure is used to store the busy-handler ** callback for a given sqlite handle. @@ -7036,67 +4634,9 @@ struct BusyHandler { int nBusy; /* Incremented with each busy call */ }; -/* -** Name of the master database table. The master database table -** is a special table that holds the names and attributes of all -** user tables and indices. -*/ -#define MASTER_NAME "sqlite_master" -#define TEMP_MASTER_NAME "sqlite_temp_master" - -/* -** The root-page of the master database table. -*/ -#define MASTER_ROOT 1 - -/* -** The name of the schema table. -*/ -#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) - -/* -** A convenience macro that returns the number of elements in -** an array. -*/ -#define ArraySize(X) (sizeof(X)/sizeof(X[0])) - -/* -** Forward references to structures -*/ -typedef struct AggInfo AggInfo; -typedef struct AuthContext AuthContext; -typedef struct Bitvec Bitvec; -typedef struct CollSeq CollSeq; -typedef struct Column Column; -typedef struct Db Db; -typedef struct Schema Schema; -typedef struct Expr Expr; -typedef struct ExprList ExprList; -typedef struct FKey FKey; -typedef struct FuncDef FuncDef; -typedef struct IdList IdList; -typedef struct Index Index; -typedef struct KeyClass KeyClass; -typedef struct KeyInfo KeyInfo; -typedef struct Module Module; -typedef struct NameContext NameContext; -typedef struct Parse Parse; -typedef struct Select Select; -typedef struct SrcList SrcList; -typedef struct StrAccum StrAccum; -typedef struct Table Table; -typedef struct TableLock TableLock; -typedef struct Token Token; -typedef struct TriggerStack TriggerStack; -typedef struct TriggerStep TriggerStep; -typedef struct Trigger Trigger; -typedef struct WhereInfo WhereInfo; -typedef struct WhereLevel WhereLevel; - /* ** Defer sourcing vdbe.h and btree.h until after the "u8" and -** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque -** pointer types (i.e. FuncDef) defined above. +** "BusyHandler typedefs. */ /************** Include btree.h in the middle of sqliteInt.h *****************/ /************** Begin file btree.h *******************************************/ @@ -7115,7 +4655,7 @@ typedef struct WhereLevel WhereLevel; ** subsystem. See comments in the source code for a detailed description ** of what each interface routine does. ** -** @(#) $Id: btree.h,v 1.102 2008/07/11 21:02:54 drh Exp $ +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef _BTREE_H_ #define _BTREE_H_ @@ -7178,6 +4718,11 @@ SQLITE_PRIVATE int sqlite3BtreeOpen( #define BTREE_READWRITE 16 /* Open for both reading and writing */ #define BTREE_CREATE 32 /* Create the database if it does not exist */ +/* Additional values for the 4th argument of sqlite3BtreeOpen that +** are not associated with PAGER_ values. +*/ +#define BTREE_PRIVATE 64 /* Never share with other connections */ + SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int); @@ -7224,27 +4769,17 @@ SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue); SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value); SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int); -struct UnpackedRecord; /* Forward declaration. Definition in vdbeaux.c. */ - SQLITE_PRIVATE int sqlite3BtreeCursor( Btree*, /* BTree containing table to open */ int iTable, /* Index of root page */ int wrFlag, /* 1 for writing. 0 for read-only */ - struct KeyInfo*, /* First argument to compare function */ - BtCursor *pCursor /* Space to write cursor structure */ + int(*)(void*,int,const void*,int,const void*), /* Key comparison function */ + void*, /* First argument to compare function */ + BtCursor **ppCursor /* Returned cursor */ ); -SQLITE_PRIVATE int sqlite3BtreeCursorSize(void); SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*); -SQLITE_PRIVATE int sqlite3BtreeMoveto( - BtCursor*, - const void *pKey, - struct UnpackedRecord *pUnKey, - i64 nKey, - int bias, - int *pRes -); -SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*); +SQLITE_PRIVATE int sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes); SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*); SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey, const void *pData, int nData, @@ -7272,6 +4807,7 @@ SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *); #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int); SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); +SQLITE_PRIVATE int sqlite3BtreePageDump(Btree*, int, int recursive); #endif /* @@ -7282,36 +4818,24 @@ SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*); #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*); SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*); -#ifndef NDEBUG - /* This routine is used inside assert() statements only. */ SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*); -#endif SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*); SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*); SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*); -#ifndef NDEBUG - /* This routine is used inside assert() statements only. */ SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*); -#endif SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*); SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*); SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*); #else # define sqlite3BtreeEnter(X) # define sqlite3BtreeLeave(X) -#ifndef NDEBUG - /* This routine is used inside assert() statements only. */ # define sqlite3BtreeHoldsMutex(X) 1 -#endif # define sqlite3BtreeEnterCursor(X) # define sqlite3BtreeLeaveCursor(X) # define sqlite3BtreeEnterAll(X) # define sqlite3BtreeLeaveAll(X) -#ifndef NDEBUG - /* This routine is used inside assert() statements only. */ # define sqlite3BtreeHoldsAllMutexes(X) 1 -#endif # define sqlite3BtreeMutexArrayEnter(X) # define sqlite3BtreeMutexArrayLeave(X) # define sqlite3BtreeMutexArrayInsert(X,Y) @@ -7341,7 +4865,7 @@ SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*); ** or VDBE. The VDBE implements an abstract machine that runs a ** simple program to access and modify the underlying database. ** -** $Id: vdbe.h,v 1.134 2008/06/25 00:12:41 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef _SQLITE_VDBE_H_ #define _SQLITE_VDBE_H_ @@ -7353,14 +4877,6 @@ SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*); */ typedef struct Vdbe Vdbe; -/* -** The names of the following types declared in vdbeInt.h are required -** for the VdbeOp definition. -*/ -typedef struct VdbeFunc VdbeFunc; -typedef struct Mem Mem; -typedef struct UnpackedRecord UnpackedRecord; - /* ** A single instruction of the virtual machine has an opcode ** and as many as three operands. The instruction is recorded @@ -7368,32 +4884,13 @@ typedef struct UnpackedRecord UnpackedRecord; */ struct VdbeOp { u8 opcode; /* What operation to perform */ - signed char p4type; /* One of the P4_xxx constants for p4 */ - u8 opflags; /* Not currently used */ - u8 p5; /* Fifth parameter is an unsigned character */ int p1; /* First operand */ int p2; /* Second parameter (often the jump destination) */ - int p3; /* The third parameter */ - union { /* forth parameter */ - int i; /* Integer value if p4type==P4_INT32 */ - void *p; /* Generic pointer */ - char *z; /* Pointer to data for string (char array) types */ - i64 *pI64; /* Used when p4type is P4_INT64 */ - double *pReal; /* Used when p4type is P4_REAL */ - FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */ - VdbeFunc *pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */ - CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */ - Mem *pMem; /* Used when p4type is P4_MEM */ - sqlite3_vtab *pVtab; /* Used when p4type is P4_VTAB */ - KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */ - int *ai; /* Used when p4type is P4_INTARRAY */ - } p4; -#ifdef SQLITE_DEBUG - char *zComment; /* Comment to improve readability */ -#endif + char *p3; /* Third parameter */ + int p3type; /* One of the P3_xxx constants defined below */ #ifdef VDBE_PROFILE - int cnt; /* Number of times this instruction was executed */ - u64 cycles; /* Total time spent executing this instruction */ + int cnt; /* Number of times this instruction was executed */ + long long cycles; /* Total time spend executing this instruction */ #endif }; typedef struct VdbeOp VdbeOp; @@ -7405,39 +4902,36 @@ typedef struct VdbeOp VdbeOp; struct VdbeOpList { u8 opcode; /* What operation to perform */ signed char p1; /* First operand */ - signed char p2; /* Second parameter (often the jump destination) */ - signed char p3; /* Third parameter */ + short int p2; /* Second parameter (often the jump destination) */ + char *p3; /* Third parameter */ }; typedef struct VdbeOpList VdbeOpList; /* ** Allowed values of VdbeOp.p3type */ -#define P4_NOTUSED 0 /* The P4 parameter is not used */ -#define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ -#define P4_STATIC (-2) /* Pointer to a static string */ -#define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */ -#define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */ -#define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */ -#define P4_VDBEFUNC (-7) /* P4 is a pointer to a VdbeFunc structure */ -#define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */ -#define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */ -#define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */ -#define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */ -#define P4_REAL (-12) /* P4 is a 64-bit floating point value */ -#define P4_INT64 (-13) /* P4 is a 64-bit signed integer */ -#define P4_INT32 (-14) /* P4 is a 32-bit signed integer */ -#define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */ +#define P3_NOTUSED 0 /* The P3 parameter is not used */ +#define P3_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */ +#define P3_STATIC (-2) /* Pointer to a static string */ +#define P3_COLLSEQ (-4) /* P3 is a pointer to a CollSeq structure */ +#define P3_FUNCDEF (-5) /* P3 is a pointer to a FuncDef structure */ +#define P3_KEYINFO (-6) /* P3 is a pointer to a KeyInfo structure */ +#define P3_VDBEFUNC (-7) /* P3 is a pointer to a VdbeFunc structure */ +#define P3_MEM (-8) /* P3 is a pointer to a Mem* structure */ +#define P3_TRANSIENT (-9) /* P3 is a pointer to a transient string */ +#define P3_VTAB (-10) /* P3 is a pointer to an sqlite3_vtab structure */ +#define P3_MPRINTF (-11) /* P3 is a string obtained from sqlite3_mprintf() */ +#define P3_REAL (-12) /* P3 is a 64-bit floating point value */ +#define P3_INT64 (-13) /* P3 is a 64-bit signed integer */ -/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure +/* When adding a P3 argument using P3_KEYINFO, a copy of the KeyInfo structure ** is made. That copy is freed when the Vdbe is finalized. But if the -** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still +** argument is P3_KEYINFO_HANDOFF, the passed in pointer is used. It still ** gets freed when the Vdbe is finalized so it still should be obtained ** from a single sqliteMalloc(). But no copy is made and the calling ** function should *not* try to free the KeyInfo. */ -#define P4_KEYINFO_HANDOFF (-16) -#define P4_KEYINFO_STATIC (-17) +#define P3_KEYINFO_HANDOFF (-9) /* ** The Vdbe.aColName array contains 5n Mem structures, where n is the @@ -7448,15 +4942,7 @@ typedef struct VdbeOpList VdbeOpList; #define COLNAME_DATABASE 2 #define COLNAME_TABLE 3 #define COLNAME_COLUMN 4 -#ifdef SQLITE_ENABLE_COLUMN_METADATA -# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ -#else -# ifdef SQLITE_OMIT_DECLTYPE -# define COLNAME_N 1 /* Store only the name */ -# else -# define COLNAME_N 2 /* Store the name and decltype */ -# endif -#endif +#define COLNAME_N 5 /* Number of COLNAME_xxx symbols */ /* ** The following macro converts a relative address in the p2 field @@ -7474,181 +4960,162 @@ typedef struct VdbeOpList VdbeOpList; /************** Begin file opcodes.h *****************************************/ /* Automatically generated. Do not edit */ /* See the mkopcodeh.awk script for details */ -#define OP_VNext 1 -#define OP_Affinity 2 -#define OP_Column 3 -#define OP_SetCookie 4 -#define OP_Real 125 /* same as TK_FLOAT */ -#define OP_Sequence 5 -#define OP_MoveGt 6 -#define OP_Ge 72 /* same as TK_GE */ -#define OP_RowKey 7 -#define OP_SCopy 8 -#define OP_Eq 68 /* same as TK_EQ */ -#define OP_OpenWrite 9 -#define OP_NotNull 66 /* same as TK_NOTNULL */ -#define OP_If 10 -#define OP_ToInt 141 /* same as TK_TO_INT */ -#define OP_String8 88 /* same as TK_STRING */ -#define OP_VRowid 11 -#define OP_CollSeq 12 -#define OP_OpenRead 13 -#define OP_Expire 14 -#define OP_AutoCommit 15 -#define OP_Gt 69 /* same as TK_GT */ -#define OP_Pagecount 17 -#define OP_IntegrityCk 18 -#define OP_Sort 19 -#define OP_Copy 20 -#define OP_Trace 21 -#define OP_Function 22 -#define OP_IfNeg 23 -#define OP_And 61 /* same as TK_AND */ -#define OP_Subtract 79 /* same as TK_MINUS */ -#define OP_Noop 24 -#define OP_Return 25 -#define OP_Remainder 82 /* same as TK_REM */ -#define OP_NewRowid 26 -#define OP_Multiply 80 /* same as TK_STAR */ -#define OP_Variable 27 -#define OP_String 28 -#define OP_RealAffinity 29 -#define OP_VRename 30 -#define OP_ParseSchema 31 -#define OP_VOpen 32 -#define OP_Close 33 -#define OP_CreateIndex 34 -#define OP_IsUnique 35 -#define OP_NotFound 36 -#define OP_Int64 37 -#define OP_MustBeInt 38 -#define OP_Halt 39 -#define OP_Rowid 40 -#define OP_IdxLT 41 -#define OP_AddImm 42 -#define OP_Statement 43 -#define OP_RowData 44 -#define OP_MemMax 45 -#define OP_Or 60 /* same as TK_OR */ -#define OP_NotExists 46 -#define OP_Gosub 47 -#define OP_Divide 81 /* same as TK_SLASH */ -#define OP_Integer 48 -#define OP_ToNumeric 140 /* same as TK_TO_NUMERIC*/ -#define OP_Prev 49 -#define OP_Concat 83 /* same as TK_CONCAT */ -#define OP_BitAnd 74 /* same as TK_BITAND */ -#define OP_VColumn 50 -#define OP_CreateTable 51 -#define OP_Last 52 -#define OP_IsNull 65 /* same as TK_ISNULL */ -#define OP_IncrVacuum 53 -#define OP_IdxRowid 54 -#define OP_ShiftRight 77 /* same as TK_RSHIFT */ -#define OP_ResetCount 55 -#define OP_FifoWrite 56 -#define OP_ContextPush 57 -#define OP_Yield 58 -#define OP_DropTrigger 59 -#define OP_DropIndex 62 -#define OP_IdxGE 63 -#define OP_IdxDelete 64 -#define OP_Vacuum 73 -#define OP_MoveLe 84 -#define OP_IfNot 85 -#define OP_DropTable 86 -#define OP_MakeRecord 89 -#define OP_ToBlob 139 /* same as TK_TO_BLOB */ -#define OP_ResultRow 90 -#define OP_Delete 91 -#define OP_AggFinal 92 -#define OP_Compare 93 -#define OP_ShiftLeft 76 /* same as TK_LSHIFT */ -#define OP_Goto 94 -#define OP_TableLock 95 -#define OP_FifoRead 96 -#define OP_Clear 97 -#define OP_MoveLt 98 -#define OP_Le 70 /* same as TK_LE */ -#define OP_VerifyCookie 99 -#define OP_AggStep 100 -#define OP_ToText 138 /* same as TK_TO_TEXT */ -#define OP_Not 16 /* same as TK_NOT */ -#define OP_ToReal 142 /* same as TK_TO_REAL */ -#define OP_SetNumColumns 101 -#define OP_Transaction 102 -#define OP_VFilter 103 -#define OP_Ne 67 /* same as TK_NE */ -#define OP_VDestroy 104 -#define OP_ContextPop 105 -#define OP_BitOr 75 /* same as TK_BITOR */ -#define OP_Next 106 -#define OP_IdxInsert 107 +#define OP_ReadCookie 1 +#define OP_AutoCommit 2 +#define OP_Found 3 +#define OP_NullRow 4 #define OP_Lt 71 /* same as TK_LT */ -#define OP_Insert 108 -#define OP_Destroy 109 -#define OP_ReadCookie 110 -#define OP_ForceInt 111 -#define OP_LoadAnalysis 112 -#define OP_Explain 113 -#define OP_OpenPseudo 114 -#define OP_OpenEphemeral 115 -#define OP_Null 116 -#define OP_Move 117 -#define OP_Blob 118 +#define OP_MoveLe 5 +#define OP_Variable 6 +#define OP_Pull 7 +#define OP_RealAffinity 8 +#define OP_Sort 9 +#define OP_IfNot 10 +#define OP_Gosub 11 #define OP_Add 78 /* same as TK_PLUS */ -#define OP_Rewind 119 -#define OP_MoveGe 120 -#define OP_VBegin 121 -#define OP_VUpdate 122 -#define OP_IfZero 123 +#define OP_NotFound 12 +#define OP_IsNull 65 /* same as TK_ISNULL */ +#define OP_MoveLt 13 +#define OP_Rowid 14 +#define OP_CreateIndex 15 +#define OP_Push 17 +#define OP_Explain 18 +#define OP_Statement 19 +#define OP_Callback 20 +#define OP_MemLoad 21 +#define OP_DropIndex 22 +#define OP_Null 23 +#define OP_ToInt 141 /* same as TK_TO_INT */ +#define OP_Int64 24 +#define OP_LoadAnalysis 25 +#define OP_IdxInsert 26 +#define OP_VUpdate 27 +#define OP_Next 28 +#define OP_SetNumColumns 29 +#define OP_ToNumeric 140 /* same as TK_TO_NUMERIC*/ +#define OP_Ge 72 /* same as TK_GE */ #define OP_BitNot 87 /* same as TK_BITNOT */ -#define OP_VCreate 124 -#define OP_Found 126 -#define OP_IfPos 127 -#define OP_NullRow 128 -#define OP_Jump 129 -#define OP_Permutation 130 +#define OP_MemInt 30 +#define OP_Dup 31 +#define OP_Rewind 32 +#define OP_Multiply 80 /* same as TK_STAR */ +#define OP_ToReal 142 /* same as TK_TO_REAL */ +#define OP_Gt 69 /* same as TK_GT */ +#define OP_Last 33 +#define OP_MustBeInt 34 +#define OP_Ne 67 /* same as TK_NE */ +#define OP_MoveGe 35 +#define OP_IncrVacuum 36 +#define OP_String 37 +#define OP_VFilter 38 +#define OP_ForceInt 39 +#define OP_Close 40 +#define OP_AggFinal 41 +#define OP_AbsValue 42 +#define OP_RowData 43 +#define OP_IdxRowid 44 +#define OP_BitOr 75 /* same as TK_BITOR */ +#define OP_NotNull 66 /* same as TK_NOTNULL */ +#define OP_MoveGt 45 +#define OP_Not 16 /* same as TK_NOT */ +#define OP_OpenPseudo 46 +#define OP_Halt 47 +#define OP_MemMove 48 +#define OP_NewRowid 49 +#define OP_Real 125 /* same as TK_FLOAT */ +#define OP_IdxLT 50 +#define OP_Distinct 51 +#define OP_MemMax 52 +#define OP_Function 53 +#define OP_IntegrityCk 54 +#define OP_Remainder 82 /* same as TK_REM */ +#define OP_HexBlob 126 /* same as TK_BLOB */ +#define OP_ShiftLeft 76 /* same as TK_LSHIFT */ +#define OP_FifoWrite 55 +#define OP_BitAnd 74 /* same as TK_BITAND */ +#define OP_Or 60 /* same as TK_OR */ +#define OP_NotExists 56 +#define OP_VDestroy 57 +#define OP_MemStore 58 +#define OP_IdxDelete 59 +#define OP_Vacuum 62 +#define OP_If 63 +#define OP_Destroy 64 +#define OP_AggStep 73 +#define OP_Clear 84 +#define OP_Insert 86 +#define OP_VBegin 89 +#define OP_IdxGE 90 +#define OP_OpenEphemeral 91 +#define OP_Divide 81 /* same as TK_SLASH */ +#define OP_String8 88 /* same as TK_STRING */ +#define OP_IfMemZero 92 +#define OP_Concat 83 /* same as TK_CONCAT */ +#define OP_VRowid 93 +#define OP_MakeRecord 94 +#define OP_SetCookie 95 +#define OP_StackDepth 96 +#define OP_Prev 97 +#define OP_ContextPush 98 +#define OP_DropTrigger 99 +#define OP_IdxGT 100 +#define OP_MemNull 101 +#define OP_IfMemNeg 102 +#define OP_And 61 /* same as TK_AND */ +#define OP_VColumn 103 +#define OP_Return 104 +#define OP_OpenWrite 105 +#define OP_Integer 106 +#define OP_Transaction 107 +#define OP_CollSeq 108 +#define OP_VRename 109 +#define OP_ToBlob 139 /* same as TK_TO_BLOB */ +#define OP_Sequence 110 +#define OP_ContextPop 111 +#define OP_ShiftRight 77 /* same as TK_RSHIFT */ +#define OP_VCreate 112 +#define OP_CreateTable 113 +#define OP_AddImm 114 +#define OP_ToText 138 /* same as TK_TO_TEXT */ +#define OP_DropTable 115 +#define OP_IsUnique 116 +#define OP_VOpen 117 +#define OP_Noop 118 +#define OP_RowKey 119 +#define OP_Expire 120 +#define OP_FifoRead 121 +#define OP_Delete 122 +#define OP_IfMemPos 123 +#define OP_Subtract 79 /* same as TK_MINUS */ +#define OP_MemIncr 124 +#define OP_Blob 127 +#define OP_MakeIdxRec 128 +#define OP_Goto 129 +#define OP_Negative 85 /* same as TK_UMINUS */ +#define OP_ParseSchema 130 +#define OP_Eq 68 /* same as TK_EQ */ +#define OP_VNext 131 +#define OP_Pop 132 +#define OP_Le 70 /* same as TK_LE */ +#define OP_TableLock 133 +#define OP_VerifyCookie 134 +#define OP_Column 135 +#define OP_OpenRead 136 +#define OP_ResetCount 137 -/* The following opcode values are never used */ -#define OP_NotUsed_131 131 -#define OP_NotUsed_132 132 -#define OP_NotUsed_133 133 -#define OP_NotUsed_134 134 -#define OP_NotUsed_135 135 -#define OP_NotUsed_136 136 -#define OP_NotUsed_137 137 - - -/* Properties such as "out2" or "jump" that are specified in -** comments following the "case" for each opcode in the vdbe.c -** are encoded into bitvectors as follows: -*/ -#define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */ -#define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */ -#define OPFLG_IN1 0x0004 /* in1: P1 is an input */ -#define OPFLG_IN2 0x0008 /* in2: P2 is an input */ -#define OPFLG_IN3 0x0010 /* in3: P3 is an input */ -#define OPFLG_OUT3 0x0020 /* out3: P3 is an output */ -#define OPFLG_INITIALIZER {\ -/* 0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x02, 0x11, 0x00,\ -/* 8 */ 0x00, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00,\ -/* 16 */ 0x04, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05,\ -/* 24 */ 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00, 0x00,\ -/* 32 */ 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05, 0x00,\ -/* 40 */ 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11, 0x01,\ -/* 48 */ 0x02, 0x01, 0x00, 0x02, 0x01, 0x01, 0x02, 0x00,\ -/* 56 */ 0x04, 0x00, 0x00, 0x00, 0x2c, 0x2c, 0x00, 0x11,\ -/* 64 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ -/* 72 */ 0x15, 0x00, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\ -/* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x11, 0x05, 0x00, 0x04,\ -/* 88 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,\ -/* 96 */ 0x01, 0x00, 0x11, 0x00, 0x00, 0x00, 0x00, 0x01,\ -/* 104 */ 0x00, 0x00, 0x01, 0x08, 0x00, 0x02, 0x02, 0x05,\ -/* 112 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, 0x01,\ -/* 120 */ 0x11, 0x00, 0x00, 0x05, 0x00, 0x02, 0x11, 0x05,\ -/* 128 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ -/* 136 */ 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,} +/* Opcodes that are guaranteed to never push a value onto the stack +** contain a 1 their corresponding position of the following mask +** set. See the opcodeNoPush() function in vdbeaux.c */ +#define NOPUSH_MASK_0 0x3fbc +#define NOPUSH_MASK_1 0x3e5b +#define NOPUSH_MASK_2 0xe3df +#define NOPUSH_MASK_3 0xff9c +#define NOPUSH_MASK_4 0xfffe +#define NOPUSH_MASK_5 0x9ef7 +#define NOPUSH_MASK_6 0xbb5f +#define NOPUSH_MASK_7 0x1d7d +#define NOPUSH_MASK_8 0x7f7e +#define NOPUSH_MASK_9 0x0000 /************** End of opcodes.h *********************************************/ /************** Continuing where we left off in vdbe.h ***********************/ @@ -7658,19 +5125,14 @@ typedef struct VdbeOpList VdbeOpList; ** for a description of what each of these routines does. */ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); -SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int); +SQLITE_PRIVATE int sqlite3VdbeAddOp(Vdbe*,int,int,int); +SQLITE_PRIVATE int sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int); SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp); SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1); SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2); -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3); -SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5); SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr); SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N); -SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N); SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); @@ -7683,7 +5145,7 @@ SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*); #endif SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*); -SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*, int); +SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int); SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int); SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*); @@ -7691,22 +5153,11 @@ SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n); SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*); -#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT -SQLITE_PRIVATE int sqlite3VdbeReleaseMemory(int); -#endif -SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,void*,int); -SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*); -SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*); - - #ifndef NDEBUG SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...); # define VdbeComment(X) sqlite3VdbeComment X -SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); -# define VdbeNoopComment(X) sqlite3VdbeNoopComment X #else # define VdbeComment(X) -# define VdbeNoopComment(X) #endif #endif @@ -7730,25 +5181,17 @@ SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...); ** subsystem. The page cache subsystem reads and writes a file a page ** at a time and provides a journal for rollback. ** -** @(#) $Id: pager.h,v 1.76 2008/06/07 08:58:22 danielk1977 Exp $ +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef _PAGER_H_ #define _PAGER_H_ -/* -** If defined as non-zero, auto-vacuum is enabled by default. Otherwise -** it must be turned on for each database using "PRAGMA auto_vacuum = 1". -*/ -#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT - #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1 -#endif - /* ** The type used to represent a page number. The first page in a file ** is called page 1. 0 is used to represent "not a page". */ -typedef u32 Pgno; +typedef unsigned int Pgno; /* ** Each open file is managed by a separate instance of the "Pager" structure. @@ -7775,14 +5218,6 @@ typedef struct PgHdr DbPage; #define PAGER_LOCKINGMODE_NORMAL 0 #define PAGER_LOCKINGMODE_EXCLUSIVE 1 -/* -** Valid values for the second argument to sqlite3PagerJournalMode(). -*/ -#define PAGER_JOURNALMODE_QUERY -1 -#define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */ -#define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */ -#define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */ - /* ** See source code comments for a detailed description of the following ** routines: @@ -7802,10 +5237,11 @@ SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno); SQLITE_PRIVATE int sqlite3PagerRef(DbPage*); SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*); SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*); -SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*); +SQLITE_PRIVATE int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*); +SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*); SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno); SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag); -SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno, int); +SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno); SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*); SQLITE_PRIVATE int sqlite3PagerRollback(Pager*); SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*); @@ -7826,10 +5262,7 @@ SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno); SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int); -SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int); -SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64); SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*); -SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager); #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO) SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int); @@ -7847,7 +5280,7 @@ SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*); #ifdef SQLITE_TEST SQLITE_PRIVATE int *sqlite3PagerStats(Pager*); SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*); -SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*); + int pager3_refinfo_enable; #endif #ifdef SQLITE_TEST @@ -7863,6 +5296,63 @@ void enable_simulated_io_errors(void); /************** End of pager.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ + +/* +** Name of the master database table. The master database table +** is a special table that holds the names and attributes of all +** user tables and indices. +*/ +#define MASTER_NAME "sqlite_master" +#define TEMP_MASTER_NAME "sqlite_temp_master" + +/* +** The root-page of the master database table. +*/ +#define MASTER_ROOT 1 + +/* +** The name of the schema table. +*/ +#define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME) + +/* +** A convenience macro that returns the number of elements in +** an array. +*/ +#define ArraySize(X) (sizeof(X)/sizeof(X[0])) + +/* +** Forward references to structures +*/ +typedef struct AggInfo AggInfo; +typedef struct AuthContext AuthContext; +typedef struct CollSeq CollSeq; +typedef struct Column Column; +typedef struct Db Db; +typedef struct Schema Schema; +typedef struct Expr Expr; +typedef struct ExprList ExprList; +typedef struct FKey FKey; +typedef struct FuncDef FuncDef; +typedef struct IdList IdList; +typedef struct Index Index; +typedef struct KeyClass KeyClass; +typedef struct KeyInfo KeyInfo; +typedef struct Module Module; +typedef struct NameContext NameContext; +typedef struct Parse Parse; +typedef struct Select Select; +typedef struct SrcList SrcList; +typedef struct StrAccum StrAccum; +typedef struct Table Table; +typedef struct TableLock TableLock; +typedef struct Token Token; +typedef struct TriggerStack TriggerStack; +typedef struct TriggerStep TriggerStep; +typedef struct Trigger Trigger; +typedef struct WhereInfo WhereInfo; +typedef struct WhereLevel WhereLevel; + /************** Include os.h in the middle of sqliteInt.h ********************/ /************** Begin file os.h **********************************************/ /* @@ -7883,8 +5373,6 @@ void enable_simulated_io_errors(void); ** ** This header file is #include-ed by sqliteInt.h and thus ends up ** being included by every source file. -** -** $Id: os.h,v 1.105 2008/06/26 10:41:19 danielk1977 Exp $ */ #ifndef _SQLITE_OS_H_ #define _SQLITE_OS_H_ @@ -7892,66 +5380,56 @@ void enable_simulated_io_errors(void); /* ** Figure out if we are dealing with Unix, Windows, or some other ** operating system. After the following block of preprocess macros, -** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER -** will defined to either 1 or 0. One of the four will be 1. The other -** three will be 0. +** all of OS_UNIX, OS_WIN, OS_OS2, and OS_OTHER will defined to either +** 1 or 0. One of the four will be 1. The other three will be 0. */ -#if defined(SQLITE_OS_OTHER) -# if SQLITE_OS_OTHER==1 -# undef SQLITE_OS_UNIX -# define SQLITE_OS_UNIX 0 -# undef SQLITE_OS_WIN -# define SQLITE_OS_WIN 0 -# undef SQLITE_OS_OS2 -# define SQLITE_OS_OS2 0 +#if defined(OS_OTHER) +# if OS_OTHER==1 +# undef OS_UNIX +# define OS_UNIX 0 +# undef OS_WIN +# define OS_WIN 0 +# undef OS_OS2 +# define OS_OS2 0 # else -# undef SQLITE_OS_OTHER +# undef OS_OTHER # endif #endif -#if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER) -# define SQLITE_OS_OTHER 0 -# ifndef SQLITE_OS_WIN +#if !defined(OS_UNIX) && !defined(OS_OTHER) +# define OS_OTHER 0 +# ifndef OS_WIN # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) -# define SQLITE_OS_WIN 1 -# define SQLITE_OS_UNIX 0 -# define SQLITE_OS_OS2 0 +# define OS_WIN 1 +# define OS_UNIX 0 +# define OS_OS2 0 # elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__) -# define SQLITE_OS_WIN 0 -# define SQLITE_OS_UNIX 0 -# define SQLITE_OS_OS2 1 +# define OS_WIN 0 +# define OS_UNIX 0 +# define OS_OS2 1 # else -# define SQLITE_OS_WIN 0 -# define SQLITE_OS_UNIX 1 -# define SQLITE_OS_OS2 0 +# define OS_WIN 0 +# define OS_UNIX 1 +# define OS_OS2 0 # endif # else -# define SQLITE_OS_UNIX 0 -# define SQLITE_OS_OS2 0 +# define OS_UNIX 0 +# define OS_OS2 0 # endif #else -# ifndef SQLITE_OS_WIN -# define SQLITE_OS_WIN 0 +# ifndef OS_WIN +# define OS_WIN 0 # endif #endif -/* -** Determine if we are dealing with WindowsCE - which has a much -** reduced API. -*/ -#if defined(_WIN32_WCE) -# define SQLITE_OS_WINCE 1 -#else -# define SQLITE_OS_WINCE 0 -#endif /* ** Define the maximum size of a temporary filename */ -#if SQLITE_OS_WIN +#if OS_WIN # include # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50) -#elif SQLITE_OS_OS2 +#elif OS_OS2 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY) # include /* has to be included before os2.h for linking to work */ # endif @@ -7963,7 +5441,6 @@ void enable_simulated_io_errors(void); # define INCL_DOSMODULEMGR # define INCL_DOSSEMAPHORES # include -# include # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP) #else # define SQLITE_TEMPNAME_SIZE 200 @@ -8110,7 +5587,7 @@ SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize); SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int); SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int); -SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut); +SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*); SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id); SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); @@ -8120,14 +5597,13 @@ SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id); */ SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *); SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int); -SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut); +SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int); +SQLITE_PRIVATE int sqlite3OsGetTempname(sqlite3_vfs *, int, char *); SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *); -#ifndef SQLITE_OMIT_LOAD_EXTENSION SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *); SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *); SQLITE_PRIVATE void *sqlite3OsDlSym(sqlite3_vfs *, void *, const char *); SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *); -#endif /* SQLITE_OMIT_LOAD_EXTENSION */ SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *); SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int); SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*); @@ -8139,6 +5615,20 @@ SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*); SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*); SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); +/* +** Each OS-specific backend defines an instance of the following +** structure for returning a pointer to its sqlite3_vfs. If OS_OTHER +** is defined (meaning that the application-defined OS interface layer +** is used) then there is no default VFS. The application must +** register one or more VFS structures using sqlite3_vfs_register() +** before attempting to use SQLite. +*/ +#if OS_UNIX || OS_WIN || OS_OS2 +SQLITE_PRIVATE sqlite3_vfs *sqlite3OsDefaultVfs(void); +#else +# define sqlite3OsDefaultVfs(X) 0 +#endif + #endif /* _SQLITE_OS_H_ */ /************** End of os.h **************************************************/ @@ -8166,7 +5656,7 @@ SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); ** Source files should #include the sqliteInt.h file and let that file ** include this one indirectly. ** -** $Id: mutex.h,v 1.8 2008/06/26 10:41:19 danielk1977 Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ @@ -8200,15 +5690,15 @@ SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); # undef SQLITE_MUTEX_NOOP # define SQLITE_MUTEX_NOOP_DEBUG #endif -#if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_UNIX +#if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_UNIX # undef SQLITE_MUTEX_NOOP # define SQLITE_MUTEX_PTHREADS #endif -#if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_WIN +#if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_WIN # undef SQLITE_MUTEX_NOOP # define SQLITE_MUTEX_W32 #endif -#if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && SQLITE_OS_OS2 +#if defined(SQLITE_MUTEX_NOOP) && SQLITE_THREADSAFE && OS_OS2 # undef SQLITE_MUTEX_NOOP # define SQLITE_MUTEX_OS2 #endif @@ -8224,9 +5714,6 @@ SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); #define sqlite3_mutex_leave(X) #define sqlite3_mutex_held(X) 1 #define sqlite3_mutex_notheld(X) 1 -#define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8) -#define sqlite3MutexInit() SQLITE_OK -#define sqlite3MutexEnd() #endif #endif /* SQLITE_MUTEX_APPDEF */ @@ -8234,7 +5721,6 @@ SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *); /************** End of mutex.h ***********************************************/ /************** Continuing where we left off in sqliteInt.h ******************/ - /* ** Each database file to be accessed by the system is an instance ** of the following structure. There are normally two of these structures @@ -8302,11 +5788,6 @@ struct Schema { #define DB_UnresetViews 0x0002 /* Some views have defined column names */ #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */ -/* -** The number of different kinds of things that can be limited -** using the sqlite3_limit() interface. -*/ -#define SQLITE_N_LIMIT (SQLITE_LIMIT_VARIABLE_NUMBER+1) /* ** Each database is an instance of the following structure. @@ -8345,10 +5826,7 @@ struct sqlite3 { u8 autoCommit; /* The auto-commit flag. */ u8 temp_store; /* 1: file 2: memory 0: default */ u8 mallocFailed; /* True if we have seen a malloc failure */ - u8 dfltLockMode; /* Default locking-mode for attached dbs */ - u8 dfltJournalMode; /* Default journal mode for attached dbs */ - signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */ - int nextPagesize; /* Pagesize after VACUUM if >0 */ + char nextAutovac; /* Autovac setting after VACUUM if >=0 */ int nTable; /* Number of tables in the database */ CollSeq *pDfltColl; /* The default collating sequence (BINARY) */ i64 lastRowid; /* ROWID of most recent insert (see above) */ @@ -8357,7 +5835,6 @@ struct sqlite3 { int nChange; /* Value returned by sqlite3_changes() */ int nTotalChange; /* Value returned by sqlite3_total_changes() */ sqlite3_mutex *mutex; /* Connection mutex */ - int aLimit[SQLITE_N_LIMIT]; /* Limits */ struct sqlite3InitInfo { /* Information used during initialization */ int iDb; /* When back is being initialized */ int newTnum; /* Rootpage of table being initialized */ @@ -8411,6 +5888,7 @@ struct sqlite3 { #ifdef SQLITE_SSE sqlite3_stmt *pFetch; /* Used by SSE to fetch stored statements */ #endif + u8 dfltLockMode; /* Default locking-mode for attached dbs */ }; /* @@ -8457,7 +5935,6 @@ struct sqlite3 { */ #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */ #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */ -#define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */ #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */ #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */ @@ -8569,7 +6046,7 @@ struct CollSeq { ** ** But rather than start with 0 or 1, we begin with 'a'. That way, ** when multiple affinity types are concatenated into a string and -** used as the P4 operand, they will be more readable. +** used as the P3 operand, they will be more readable. ** ** Note also that the numeric types are grouped together so that testing ** for a numeric type is a single comparison. @@ -8582,19 +6059,6 @@ struct CollSeq { #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC) -/* -** The SQLITE_AFF_MASK values masks off the significant bits of an -** affinity value. -*/ -#define SQLITE_AFF_MASK 0x67 - -/* -** Additional bit values that can be ORed with an affinity without -** changing the affinity. -*/ -#define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */ -#define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */ - /* ** Each SQL table is represented in memory by an instance of the ** following structure. @@ -8936,7 +6400,8 @@ struct Expr { Select *pSelect; /* When the expression is a sub-select. Also the ** right side of " IN ( -** -** If this is the case, it may be possible to use an existing table -** or index instead of generating an epheremal table. -*/ -#ifndef SQLITE_OMIT_SUBQUERY -static int isCandidateForInOpt(Select *p){ - SrcList *pSrc; - ExprList *pEList; - Table *pTab; - if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */ - if( p==0 ) return 0; /* right-hand side of IN is SELECT */ - if( p->pPrior ) return 0; /* Not a compound SELECT */ - if( p->isDistinct ) return 0; /* No DISTINCT keyword */ - if( p->isAgg ) return 0; /* Contains no aggregate functions */ - if( p->pGroupBy ) return 0; /* Has no GROUP BY clause */ - if( p->pLimit ) return 0; /* Has no LIMIT clause */ - if( p->pOffset ) return 0; - if( p->pWhere ) return 0; /* Has no WHERE clause */ - pSrc = p->pSrc; - if( pSrc==0 ) return 0; /* A single table in the FROM clause */ - if( pSrc->nSrc!=1 ) return 0; - if( pSrc->a[0].pSelect ) return 0; /* FROM clause is not a subquery */ - pTab = pSrc->a[0].pTab; - if( pTab==0 ) return 0; - if( pTab->pSelect ) return 0; /* FROM clause is not a view */ - if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */ - pEList = p->pEList; - if( pEList->nExpr!=1 ) return 0; /* One column in the result set */ - if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */ - return 1; -} -#endif /* SQLITE_OMIT_SUBQUERY */ - /* ** This function is used by the implementation of the IN (...) operator. ** It's job is to find or create a b-tree structure that may be used @@ -51037,7 +45197,7 @@ static int isCandidateForInOpt(Select *p){ ** The returned value indicates the structure type, as follows: ** ** IN_INDEX_ROWID - The cursor was opened on a database table. -** IN_INDEX_INDEX - The cursor was opened on a database index. +** IN_INDEX_INDEX - The cursor was opened on a database indec. ** IN_INDEX_EPH - The cursor was opened on a specially created and ** populated epheremal table. ** @@ -51046,46 +45206,22 @@ static int isCandidateForInOpt(Select *p){ ** ** SELECT FROM
      ** -** If prNotFound parameter is 0, then the structure will be used to iterate -** through the set members, skipping any duplicates. In this case an -** epheremal table must be used unless the selected is guaranteed -** to be unique - either because it is an INTEGER PRIMARY KEY or it -** is unique by virtue of a constraint or implicit index. -** -** If the prNotFound parameter is not 0, then the structure will be used +** If the mustBeUnique parameter is false, the structure will be used ** for fast set membership tests. In this case an epheremal table must ** be used unless is an INTEGER PRIMARY KEY or an index can ** be found with as its left-most column. ** -** When the structure is being used for set membership tests, the user -** needs to know whether or not the structure contains an SQL NULL -** value in order to correctly evaluate expressions like "X IN (Y, Z)". -** If there is a chance that the structure may contain a NULL value at -** runtime, then a register is allocated and the register number written -** to *prNotFound. If there is no chance that the structure contains a -** NULL value, then *prNotFound is left unchanged. -** -** If a register is allocated and its location stored in *prNotFound, then -** its initial value is NULL. If the structure does not remain constant -** for the duration of the query (i.e. the set is a correlated sub-select), -** the value of the allocated register is reset to NULL each time the -** structure is repopulated. This allows the caller to use vdbe code -** equivalent to the following: -** -** if( register==NULL ){ -** has_null = -** register = 1 -** } -** -** in order to avoid running the -** test more often than is necessary. +** If mustBeUnique is true, then the structure will be used to iterate +** through the set members, skipping any duplicates. In this case an +** epheremal table must be used unless the selected is guaranteed +** to be unique - either because it is an INTEGER PRIMARY KEY or it +** is unique by virtue of a constraint or implicit index. */ #ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ +SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int mustBeUnique){ Select *p; int eType = 0; int iTab = pParse->nTab++; - int mustBeUnique = !prNotFound; /* The follwing if(...) expression is true if the SELECT is of the ** simple form: @@ -51095,8 +45231,14 @@ SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ ** If this is the case, it may be possible to use an existing table ** or index instead of generating an epheremal table. */ - p = pX->pSelect; - if( isCandidateForInOpt(p) ){ + if( sqlite3_enable_in_opt + && (p=pX->pSelect) && !p->pPrior + && !p->isDistinct && !p->isAgg && !p->pGroupBy + && p->pSrc && p->pSrc->nSrc==1 && !p->pSrc->a[0].pSelect + && !p->pSrc->a[0].pTab->pSelect + && p->pEList->nExpr==1 && p->pEList->a[0].pExpr->op==TK_COLUMN + && !p->pLimit && !p->pOffset && !p->pWhere + ){ sqlite3 *db = pParse->db; Index *pIdx; Expr *pExpr = p->pEList->a[0].pExpr; @@ -51109,14 +45251,15 @@ SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ */ assert(v); if( iCol<0 ){ - int iMem = ++pParse->nMem; + int iMem = pParse->nMem++; int iAddr; Table *pTab = p->pSrc->a[0].pTab; int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3VdbeUsesBtree(v, iDb); - iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem); + sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0); + iAddr = sqlite3VdbeAddOp(v, OP_If, 0, iMem); + sqlite3VdbeAddOp(v, OP_MemInt, 1, iMem); sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); eType = IN_INDEX_ROWID; @@ -51143,7 +45286,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None)) ){ int iDb; - int iMem = ++pParse->nMem; + int iMem = pParse->nMem++; int iAddr; char *pKey; @@ -51151,30 +45294,24 @@ SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ iDb = sqlite3SchemaToIndex(db, pIdx->pSchema); sqlite3VdbeUsesBtree(v, iDb); - iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem); + sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0); + iAddr = sqlite3VdbeAddOp(v, OP_If, 0, iMem); + sqlite3VdbeAddOp(v, OP_MemInt, 1, iMem); - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn); - sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb, - pKey,P4_KEYINFO_HANDOFF); - VdbeComment((v, "%s", pIdx->zName)); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + VdbeComment((v, "# %s", pIdx->zName)); + sqlite3VdbeOp3(v,OP_OpenRead,iTab,pIdx->tnum,pKey,P3_KEYINFO_HANDOFF); eType = IN_INDEX_INDEX; + sqlite3VdbeAddOp(v, OP_SetNumColumns, iTab, pIdx->nColumn); sqlite3VdbeJumpHere(v, iAddr); - if( prNotFound && !pTab->aCol[iCol].notNull ){ - *prNotFound = ++pParse->nMem; - } } } } } if( eType==0 ){ - int rMayHaveNull = 0; - if( prNotFound ){ - *prNotFound = rMayHaveNull = ++pParse->nMem; - } - sqlite3CodeSubselect(pParse, pX, rMayHaveNull); + sqlite3CodeSubselect(pParse, pX); eType = IN_INDEX_EPH; }else{ pX->iTable = iTab; @@ -51196,7 +45333,7 @@ SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){ ** operator or subquery. */ #ifndef SQLITE_OMIT_SUBQUERY -SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHaveNull){ +SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){ int testAddr = 0; /* One-time test address */ Vdbe *v = sqlite3GetVdbe(pParse); if( v==0 ) return; @@ -51213,10 +45350,11 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav ** save the results, and reuse the same result on subsequent invocations. */ if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){ - int mem = ++pParse->nMem; - sqlite3VdbeAddOp1(v, OP_If, mem); - testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem); + int mem = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0); + testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0); assert( testAddr>0 || pParse->db->mallocFailed ); + sqlite3VdbeAddOp(v, OP_MemInt, 1, mem); } switch( pExpr->op ){ @@ -51225,10 +45363,6 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav KeyInfo keyInfo; int addr; /* Address of OP_OpenEphemeral instruction */ - if( rMayHaveNull ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull); - } - affinity = sqlite3ExprAffinity(pExpr->pLeft); /* Whether this is an 'x IN(SELECT...)' or an 'x IN()' @@ -51245,9 +45379,10 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav ** is used. */ pExpr->iTable = pParse->nTab++; - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, 1); + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0); memset(&keyInfo, 0, sizeof(keyInfo)); keyInfo.nField = 1; + sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1); if( pExpr->pSelect ){ /* Case 1: expr IN (SELECT ...) @@ -51255,13 +45390,10 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav ** Generate code to write the results of the select into the temporary ** table allocated and opened above. */ - SelectDest dest; + int iParm = pExpr->iTable + (((int)affinity)<<16); ExprList *pEList; - - sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); - dest.affinity = (int)affinity; assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); - if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0) ){ + if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){ return; } pEList = pExpr->pSelect->pEList; @@ -51280,7 +45412,6 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav int i; ExprList *pList = pExpr->pList; struct ExprList_item *pItem; - int r1, r2, r3; if( !affinity ){ affinity = SQLITE_AFF_NONE; @@ -51288,8 +45419,6 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav keyInfo.aColl[0] = pExpr->pLeft->pColl; /* Loop through each expression in . */ - r1 = sqlite3GetTempReg(pParse); - r2 = sqlite3GetTempReg(pParse); for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ Expr *pE2 = pItem->pExpr; @@ -51298,24 +45427,18 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav ** this code only executes once. Because for a non-constant ** expression we need to rerun this code each time. */ - if( testAddr && !sqlite3ExprIsConstant(pE2) ){ - sqlite3VdbeChangeToNoop(v, testAddr-1, 2); + if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){ + sqlite3VdbeChangeToNoop(v, testAddr-1, 3); testAddr = 0; } /* Evaluate the expression and insert it into the temp table */ - pParse->disableColCache++; - r3 = sqlite3ExprCodeTarget(pParse, pE2, r1); - assert( pParse->disableColCache>0 ); - pParse->disableColCache--; - sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1); - sqlite3ExprCacheAffinityChange(pParse, r3, 1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2); + sqlite3ExprCode(pParse, pE2); + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); + sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0); } - sqlite3ReleaseTempReg(pParse, r1); - sqlite3ReleaseTempReg(pParse, r2); } - sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO); + sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO); break; } @@ -51327,31 +45450,31 @@ SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr, int rMayHav */ static const Token one = { (u8*)"1", 0, 1 }; Select *pSel; - SelectDest dest; + int iMem; + int sop; + pExpr->iColumn = iMem = pParse->nMem++; pSel = pExpr->pSelect; - sqlite3SelectDestInit(&dest, 0, ++pParse->nMem); if( pExpr->op==TK_SELECT ){ - dest.eDest = SRT_Mem; - sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm); - VdbeComment((v, "Init subquery result")); + sop = SRT_Mem; + sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0); + VdbeComment((v, "# Init subquery result")); }else{ - dest.eDest = SRT_Exists; - sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm); - VdbeComment((v, "Init EXISTS result")); + sop = SRT_Exists; + sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem); + VdbeComment((v, "# Init EXISTS result")); } sqlite3ExprDelete(pSel->pLimit); pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one); - if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0) ){ + if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){ return; } - pExpr->iColumn = dest.iParm; break; } } if( testAddr ){ - sqlite3VdbeJumpHere(v, testAddr-1); + sqlite3VdbeJumpHere(v, testAddr); } return; @@ -51371,60 +45494,51 @@ static char *dup8bytes(Vdbe *v, const char *in){ /* ** Generate an instruction that will put the floating point -** value described by z[0..n-1] into register iMem. +** value described by z[0..n-1] on the stack. ** ** The z[] string will probably not be zero-terminated. But the ** z[n] character is guaranteed to be something that does not look ** like the continuation of the number. */ -static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){ +static void codeReal(Vdbe *v, const char *z, int n, int negateFlag){ assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed ); if( z ){ double value; char *zV; assert( !isdigit(z[n]) ); sqlite3AtoF(z, &value); - if( sqlite3IsNaN(value) ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, iMem); - }else{ - if( negateFlag ) value = -value; - zV = dup8bytes(v, (char*)&value); - sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL); - } + if( negateFlag ) value = -value; + zV = dup8bytes(v, (char*)&value); + sqlite3VdbeOp3(v, OP_Real, 0, 0, zV, P3_REAL); } } /* ** Generate an instruction that will put the integer describe by -** text z[0..n-1] into register iMem. +** text z[0..n-1] on the stack. ** ** The z[] string will probably not be zero-terminated. But the ** z[n] character is guaranteed to be something that does not look ** like the continuation of the number. */ -static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){ - const char *z; - if( pExpr->flags & EP_IntValue ){ - int i = pExpr->iTable; - if( negFlag ) i = -i; - sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); - }else if( (z = (char*)pExpr->token.z)!=0 ){ +static void codeInteger(Vdbe *v, const char *z, int n, int negateFlag){ + assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed ); + if( z ){ int i; - int n = pExpr->token.n; assert( !isdigit(z[n]) ); if( sqlite3GetInt32(z, &i) ){ - if( negFlag ) i = -i; - sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); - }else if( sqlite3FitsIn64Bits(z, negFlag) ){ + if( negateFlag ) i = -i; + sqlite3VdbeAddOp(v, OP_Integer, i, 0); + }else if( sqlite3FitsIn64Bits(z, negateFlag) ){ i64 value; char *zV; sqlite3Atoi64(z, &value); - if( negFlag ) value = -value; + if( negateFlag ) value = -value; zV = dup8bytes(v, (char*)&value); - sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64); + sqlite3VdbeOp3(v, OP_Int64, 0, 0, zV, P3_INT64); }else{ - codeReal(v, z, n, negFlag, iMem); + codeReal(v, z, n, negateFlag); } } } @@ -51432,236 +45546,59 @@ static void codeInteger(Vdbe *v, Expr *pExpr, int negFlag, int iMem){ /* ** Generate code that will extract the iColumn-th column from -** table pTab and store the column value in a register. An effort -** is made to store the column value in register iReg, but this is -** not guaranteed. The location of the column value is returned. -** -** There must be an open cursor to pTab in iTable when this routine -** is called. If iColumn<0 then code is generated that extracts the rowid. -** -** This routine might attempt to reuse the value of the column that -** has already been loaded into a register. The value will always -** be used if it has not undergone any affinity changes. But if -** an affinity change has occurred, then the cached value will only be -** used if allowAffChng is true. +** table pTab and push that column value on the stack. There +** is an open cursor to pTab in iTable. If iColumn<0 then +** code is generated that extracts the rowid. */ -SQLITE_PRIVATE int sqlite3ExprCodeGetColumn( - Parse *pParse, /* Parsing and code generating context */ - Table *pTab, /* Description of the table we are reading from */ - int iColumn, /* Index of the table column */ - int iTable, /* The cursor pointing to the table */ - int iReg, /* Store results here */ - int allowAffChng /* True if prior affinity changes are OK */ -){ - Vdbe *v = pParse->pVdbe; - int i; - struct yColCache *p; - - for(i=0, p=pParse->aColCache; inColCache; i++, p++){ - if( p->iTable==iTable && p->iColumn==iColumn - && (!p->affChange || allowAffChng) ){ -#if 0 - sqlite3VdbeAddOp0(v, OP_Noop); - VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg)); -#endif - return p->iReg; - } - } - assert( v!=0 ); +SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){ if( iColumn<0 ){ int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid; - sqlite3VdbeAddOp2(v, op, iTable, iReg); + sqlite3VdbeAddOp(v, op, iTable, 0); }else if( pTab==0 ){ - sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg); + sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn); }else{ int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; - sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg); + sqlite3VdbeAddOp(v, op, iTable, iColumn); sqlite3ColumnDefault(v, pTab, iColumn); #ifndef SQLITE_OMIT_FLOATING_POINT if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); + sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0); } #endif } - if( pParse->disableColCache==0 ){ - i = pParse->iColCache; - p = &pParse->aColCache[i]; - p->iTable = iTable; - p->iColumn = iColumn; - p->iReg = iReg; - p->affChange = 0; - i++; - if( i>=ArraySize(pParse->aColCache) ) i = 0; - if( i>pParse->nColCache ) pParse->nColCache = i; - pParse->iColCache = i; - } - return iReg; -} - -/* -** Clear all column cache entries associated with the vdbe -** cursor with cursor number iTable. -*/ -SQLITE_PRIVATE void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){ - if( iTable<0 ){ - pParse->nColCache = 0; - pParse->iColCache = 0; - }else{ - int i; - for(i=0; inColCache; i++){ - if( pParse->aColCache[i].iTable==iTable ){ - testcase( i==pParse->nColCache-1 ); - pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache]; - pParse->iColCache = pParse->nColCache; - } - } - } -} - -/* -** Record the fact that an affinity change has occurred on iCount -** registers starting with iStart. -*/ -SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){ - int iEnd = iStart + iCount - 1; - int i; - for(i=0; inColCache; i++){ - int r = pParse->aColCache[i].iReg; - if( r>=iStart && r<=iEnd ){ - pParse->aColCache[i].affChange = 1; - } - } -} - -/* -** Generate code to move content from registers iFrom...iFrom+nReg-1 -** over to iTo..iTo+nReg-1. Keep the column cache up-to-date. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){ - int i; - if( iFrom==iTo ) return; - sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg); - for(i=0; inColCache; i++){ - int x = pParse->aColCache[i].iReg; - if( x>=iFrom && xaColCache[i].iReg += iTo-iFrom; - } - } -} - -/* -** Generate code to copy content from registers iFrom...iFrom+nReg-1 -** over to iTo..iTo+nReg-1. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){ - int i; - if( iFrom==iTo ) return; - for(i=0; ipVdbe, OP_Copy, iFrom+i, iTo+i); - } -} - -/* -** Return true if any register in the range iFrom..iTo (inclusive) -** is used as part of the column cache. -*/ -static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){ - int i; - for(i=0; inColCache; i++){ - int r = pParse->aColCache[i].iReg; - if( r>=iFrom && r<=iTo ) return 1; - } - return 0; -} - -/* -** Theres is a value in register iCurrent. We ultimately want -** the value to be in register iTarget. It might be that -** iCurrent and iTarget are the same register. -** -** We are going to modify the value, so we need to make sure it -** is not a cached register. If iCurrent is a cached register, -** then try to move the value over to iTarget. If iTarget is a -** cached register, then clear the corresponding cache line. -** -** Return the register that the value ends up in. -*/ -SQLITE_PRIVATE int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){ - int i; - assert( pParse->pVdbe!=0 ); - if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){ - return iCurrent; - } - if( iCurrent!=iTarget ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget); - } - for(i=0; inColCache; i++){ - if( pParse->aColCache[i].iReg==iTarget ){ - pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache]; - pParse->iColCache = pParse->nColCache; - } - } - return iTarget; -} - -/* -** If the last instruction coded is an ephemeral copy of any of -** the registers in the nReg registers beginning with iReg, then -** convert the last instruction from OP_SCopy to OP_Copy. -*/ -SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){ - int addr; - VdbeOp *pOp; - Vdbe *v; - - v = pParse->pVdbe; - addr = sqlite3VdbeCurrentAddr(v); - pOp = sqlite3VdbeGetOp(v, addr-1); - assert( pOp || pParse->db->mallocFailed ); - if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1opcode = OP_Copy; - } } /* ** Generate code into the current Vdbe to evaluate the given -** expression. Attempt to store the results in register "target". -** Return the register where results are stored. +** expression and leave the result on the top of stack. ** -** With this routine, there is no guaranteed that results will -** be stored in target. The result might be stored in some other -** register if it is convenient to do so. The calling function -** must check the return code and move the results to the desired -** register. +** This code depends on the fact that certain token values (ex: TK_EQ) +** are the same as opcode values (ex: OP_Eq) that implement the corresponding +** operation. Special comments in vdbe.c and the mkopcodeh.awk script in +** the make process cause these values to align. Assert()s in the code +** below verify that the numbers are aligned correctly. */ -SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){ - Vdbe *v = pParse->pVdbe; /* The VM under construction */ - int op; /* The opcode being coded */ - int inReg = target; /* Results stored in register inReg */ - int regFree1 = 0; /* If non-zero free this temporary register */ - int regFree2 = 0; /* If non-zero free this temporary register */ - int r1, r2, r3, r4; /* Various register numbers */ - - assert( v!=0 || pParse->db->mallocFailed ); - assert( target>0 && target<=pParse->nMem ); - if( v==0 ) return 0; +SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr){ + Vdbe *v = pParse->pVdbe; + int op; + int stackChng = 1; /* Amount of change to stack depth */ + if( v==0 ) return; if( pExpr==0 ){ - op = TK_NULL; - }else{ - op = pExpr->op; + sqlite3VdbeAddOp(v, OP_Null, 0, 0); + return; } + op = pExpr->op; switch( op ){ case TK_AGG_COLUMN: { AggInfo *pAggInfo = pExpr->pAggInfo; struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; if( !pAggInfo->directMode ){ - assert( pCol->iMem>0 ); - inReg = pCol->iMem; + sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0); break; }else if( pAggInfo->useSortingIdx ){ - sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx, - pCol->iSorterColumn, target); + sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx, + pCol->iSorterColumn); break; } /* Otherwise, fall thru into the TK_COLUMN case */ @@ -51669,66 +45606,61 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) case TK_COLUMN: { if( pExpr->iTable<0 ){ /* This only happens when coding check constraints */ - assert( pParse->ckBase>0 ); - inReg = pExpr->iColumn + pParse->ckBase; + assert( pParse->ckOffset>0 ); + sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1); }else{ - testcase( (pExpr->flags & EP_AnyAff)!=0 ); - inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab, - pExpr->iColumn, pExpr->iTable, target, - pExpr->flags & EP_AnyAff); + sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable); } break; } case TK_INTEGER: { - codeInteger(v, pExpr, 0, target); + codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0); break; } case TK_FLOAT: { - codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target); + codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0); break; } case TK_STRING: { sqlite3DequoteExpr(pParse->db, pExpr); - sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0, - (char*)pExpr->token.z, pExpr->token.n); + sqlite3VdbeOp3(v,OP_String8, 0, 0, (char*)pExpr->token.z, pExpr->token.n); break; } case TK_NULL: { - sqlite3VdbeAddOp2(v, OP_Null, 0, target); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); break; } #ifndef SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { int n; const char *z; - char *zBlob; - assert( pExpr->token.n>=3 ); - assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' ); - assert( pExpr->token.z[1]=='\'' ); - assert( pExpr->token.z[pExpr->token.n-1]=='\'' ); + assert( TK_BLOB==OP_HexBlob ); n = pExpr->token.n - 3; z = (char*)pExpr->token.z + 2; - zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); - sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); + assert( n>=0 ); + if( n==0 ){ + z = ""; + } + sqlite3VdbeOp3(v, op, 0, 0, z, n); break; } #endif case TK_VARIABLE: { - sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target); + sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0); if( pExpr->token.n>1 ){ - sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n); + sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n); } break; } case TK_REGISTER: { - inReg = pExpr->iTable; + sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0); break; } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ int aff, to_op; - inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + sqlite3ExprCode(pParse, pExpr->pLeft); aff = sqlite3AffinityType(&pExpr->token); to_op = aff - SQLITE_AFF_TEXT + OP_ToText; assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT ); @@ -51736,14 +45668,8 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC ); assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER ); assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL ); - testcase( to_op==OP_ToText ); - testcase( to_op==OP_ToBlob ); - testcase( to_op==OP_ToNumeric ); - testcase( to_op==OP_ToInt ); - testcase( to_op==OP_ToReal ); - sqlite3VdbeAddOp1(v, to_op, inReg); - testcase( usedAsColumnCache(pParse, inReg, inReg) ); - sqlite3ExprCacheAffinityChange(pParse, inReg, 1); + sqlite3VdbeAddOp(v, to_op, 0, 0); + stackChng = 0; break; } #endif /* SQLITE_OMIT_CAST */ @@ -51759,18 +45685,10 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( TK_GE==OP_Ge ); assert( TK_EQ==OP_Eq ); assert( TK_NE==OP_Ne ); - testcase( op==TK_LT ); - testcase( op==TK_LE ); - testcase( op==TK_GT ); - testcase( op==TK_GE ); - testcase( op==TK_EQ ); - testcase( op==TK_NE ); - codeCompareOperands(pParse, pExpr->pLeft, &r1, ®Free1, - pExpr->pRight, &r2, ®Free2); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, - r1, r2, inReg, SQLITE_STOREP2); - testcase( regFree1==0 ); - testcase( regFree2==0 ); + sqlite3ExprCode(pParse, pExpr->pLeft); + sqlite3ExprCode(pParse, pExpr->pRight); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0); + stackChng = -1; break; } case TK_AND: @@ -51796,69 +45714,46 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) assert( TK_LSHIFT==OP_ShiftLeft ); assert( TK_RSHIFT==OP_ShiftRight ); assert( TK_CONCAT==OP_Concat ); - testcase( op==TK_AND ); - testcase( op==TK_OR ); - testcase( op==TK_PLUS ); - testcase( op==TK_MINUS ); - testcase( op==TK_REM ); - testcase( op==TK_BITAND ); - testcase( op==TK_BITOR ); - testcase( op==TK_SLASH ); - testcase( op==TK_LSHIFT ); - testcase( op==TK_RSHIFT ); - testcase( op==TK_CONCAT ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); - sqlite3VdbeAddOp3(v, op, r2, r1, target); - testcase( regFree1==0 ); - testcase( regFree2==0 ); + sqlite3ExprCode(pParse, pExpr->pLeft); + sqlite3ExprCode(pParse, pExpr->pRight); + sqlite3VdbeAddOp(v, op, 0, 0); + stackChng = -1; break; } case TK_UMINUS: { Expr *pLeft = pExpr->pLeft; assert( pLeft ); if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){ + Token *p = &pLeft->token; if( pLeft->op==TK_FLOAT ){ - codeReal(v, (char*)pLeft->token.z, pLeft->token.n, 1, target); + codeReal(v, (char*)p->z, p->n, 1); }else{ - codeInteger(v, pLeft, 1, target); + codeInteger(v, (char*)p->z, p->n, 1); } - }else{ - regFree1 = r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_Integer, 0, r1); - r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2); - sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); - testcase( regFree2==0 ); + break; } - inReg = target; - break; + /* Fall through into TK_NOT */ } case TK_BITNOT: case TK_NOT: { assert( TK_BITNOT==OP_BitNot ); assert( TK_NOT==OP_Not ); - testcase( op==TK_BITNOT ); - testcase( op==TK_NOT ); - inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); - testcase( inReg==target ); - testcase( usedAsColumnCache(pParse, inReg, inReg) ); - inReg = sqlite3ExprWritableRegister(pParse, inReg, target); - sqlite3VdbeAddOp1(v, op, inReg); + sqlite3ExprCode(pParse, pExpr->pLeft); + sqlite3VdbeAddOp(v, op, 0, 0); + stackChng = 0; break; } case TK_ISNULL: case TK_NOTNULL: { - int addr; + int dest; assert( TK_ISNULL==OP_IsNull ); assert( TK_NOTNULL==OP_NotNull ); - testcase( op==TK_ISNULL ); - testcase( op==TK_NOTNULL ); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - testcase( regFree1==0 ); - addr = sqlite3VdbeAddOp1(v, op, r1); - sqlite3VdbeAddOp2(v, OP_AddImm, target, -1); - sqlite3VdbeJumpHere(v, addr); + sqlite3VdbeAddOp(v, OP_Integer, 1, 0); + sqlite3ExprCode(pParse, pExpr->pLeft); + dest = sqlite3VdbeCurrentAddr(v) + 2; + sqlite3VdbeAddOp(v, op, 1, dest); + sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); + stackChng = 0; break; } case TK_AGG_FUNCTION: { @@ -51867,7 +45762,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) sqlite3ErrorMsg(pParse, "misuse of aggregate: %T", &pExpr->span); }else{ - inReg = pInfo->aFunc[pExpr->iAgg].iMem; + sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0); } break; } @@ -51884,19 +45779,11 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) u8 enc = ENC(db); CollSeq *pColl = 0; - testcase( op==TK_CONST_FUNC ); - testcase( op==TK_FUNCTION ); zId = (char*)pExpr->token.z; nId = pExpr->token.n; pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0); assert( pDef!=0 ); - if( pList ){ - nExpr = pList->nExpr; - r1 = sqlite3GetTempRange(pParse, nExpr); - sqlite3ExprCodeExprList(pParse, pList, r1, 1); - }else{ - nExpr = r1 = 0; - } + nExpr = sqlite3ExprCodeExprList(pParse, pList); #ifndef SQLITE_OMIT_VIRTUALTABLE /* Possibly overload the function if the first argument is ** a virtual table column. @@ -51926,190 +45813,92 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) } if( pDef->needCollSeq ){ if( !pColl ) pColl = pParse->db->pDfltColl; - sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); + sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); } - sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target, - (char*)pDef, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, nExpr); - if( nExpr ){ - sqlite3ReleaseTempRange(pParse, r1, nExpr); - } - sqlite3ExprCacheAffinityChange(pParse, r1, nExpr); + sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF); + stackChng = 1-nExpr; break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_EXISTS: case TK_SELECT: { - testcase( op==TK_EXISTS ); - testcase( op==TK_SELECT ); if( pExpr->iColumn==0 ){ - sqlite3CodeSubselect(pParse, pExpr, 0); + sqlite3CodeSubselect(pParse, pExpr); } - inReg = pExpr->iColumn; + sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0); + VdbeComment((v, "# load subquery result")); break; } case TK_IN: { - int rNotFound = 0; - int rMayHaveNull = 0; - int j2, j3, j4, j5; + int addr; char affinity; + int ckOffset = pParse->ckOffset; int eType; + int iLabel = sqlite3VdbeMakeLabel(v); - VdbeNoopComment((v, "begin IN expr r%d", target)); - eType = sqlite3FindInIndex(pParse, pExpr, &rMayHaveNull); - if( rMayHaveNull ){ - rNotFound = ++pParse->nMem; - } + eType = sqlite3FindInIndex(pParse, pExpr, 0); /* Figure out the affinity to use to create a key from the results ** of the expression. affinityStr stores a static string suitable for - ** P4 of OP_MakeRecord. + ** P3 of OP_MakeRecord. */ affinity = comparisonAffinity(pExpr); + sqlite3VdbeAddOp(v, OP_Integer, 1, 0); + pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0); /* Code the from " IN (...)". The temporary table ** pExpr->iTable contains the values that make up the (...) set. */ - pParse->disableColCache++; - sqlite3ExprCode(pParse, pExpr->pLeft, target); - pParse->disableColCache--; - j2 = sqlite3VdbeAddOp1(v, OP_IsNull, target); + sqlite3ExprCode(pParse, pExpr->pLeft); + addr = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4); /* addr + 0 */ + sqlite3VdbeAddOp(v, OP_Pop, 2, 0); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, iLabel); if( eType==IN_INDEX_ROWID ){ - j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, target); - j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, target); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - j5 = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, j3); - sqlite3VdbeJumpHere(v, j4); - sqlite3VdbeAddOp2(v, OP_Integer, 0, target); + int iAddr = sqlite3VdbeCurrentAddr(v)+3; + sqlite3VdbeAddOp(v, OP_MustBeInt, 1, iAddr); + sqlite3VdbeAddOp(v, OP_NotExists, pExpr->iTable, iAddr); + sqlite3VdbeAddOp(v, OP_Goto, pExpr->iTable, iLabel); }else{ - r2 = regFree2 = sqlite3GetTempReg(pParse); - - /* Create a record and test for set membership. If the set contains - ** the value, then jump to the end of the test code. The target - ** register still contains the true (1) value written to it earlier. - */ - sqlite3VdbeAddOp4(v, OP_MakeRecord, target, 1, r2, &affinity, 1); - sqlite3VdbeAddOp2(v, OP_Integer, 1, target); - j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2); - - /* If the set membership test fails, then the result of the - ** "x IN (...)" expression must be either 0 or NULL. If the set - ** contains no NULL values, then the result is 0. If the set - ** contains one or more NULL values, then the result of the - ** expression is also NULL. - */ - if( rNotFound==0 ){ - /* This branch runs if it is known at compile time (now) that - ** the set contains no NULL values. This happens as the result - ** of a "NOT NULL" constraint in the database schema. No need - ** to test the data structure at runtime in this case. - */ - sqlite3VdbeAddOp2(v, OP_Integer, 0, target); - }else{ - /* This block populates the rNotFound register with either NULL - ** or 0 (an integer value). If the data structure contains one - ** or more NULLs, then set rNotFound to NULL. Otherwise, set it - ** to 0. If register rMayHaveNull is already set to some value - ** other than NULL, then the test has already been run and - ** rNotFound is already populated. - */ - static const char nullRecord[] = { 0x02, 0x00 }; - j3 = sqlite3VdbeAddOp1(v, OP_NotNull, rMayHaveNull); - sqlite3VdbeAddOp2(v, OP_Null, 0, rNotFound); - sqlite3VdbeAddOp4(v, OP_Blob, 2, rMayHaveNull, 0, - nullRecord, P4_STATIC); - j4 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, rMayHaveNull); - sqlite3VdbeAddOp2(v, OP_Integer, 0, rNotFound); - sqlite3VdbeJumpHere(v, j4); - sqlite3VdbeJumpHere(v, j3); - - /* Copy the value of register rNotFound (which is either NULL or 0) - ** into the target register. This will be the result of the - ** expression. - */ - sqlite3VdbeAddOp2(v, OP_Copy, rNotFound, target); - } + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); /* addr + 4 */ + sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, iLabel); } - sqlite3VdbeJumpHere(v, j2); - sqlite3VdbeJumpHere(v, j5); - VdbeComment((v, "end IN expr r%d", target)); + sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); /* addr + 6 */ + sqlite3VdbeResolveLabel(v, iLabel); + break; } #endif - /* - ** x BETWEEN y AND z - ** - ** This is equivalent to - ** - ** x>=y AND x<=z - ** - ** X is stored in pExpr->pLeft. - ** Y is stored in pExpr->pList->a[0].pExpr. - ** Z is stored in pExpr->pList->a[1].pExpr. - */ case TK_BETWEEN: { Expr *pLeft = pExpr->pLeft; struct ExprList_item *pLItem = pExpr->pList->a; Expr *pRight = pLItem->pExpr; - - codeCompareOperands(pParse, pLeft, &r1, ®Free1, - pRight, &r2, ®Free2); - testcase( regFree1==0 ); - testcase( regFree2==0 ); - r3 = sqlite3GetTempReg(pParse); - r4 = sqlite3GetTempReg(pParse); - codeCompare(pParse, pLeft, pRight, OP_Ge, - r1, r2, r3, SQLITE_STOREP2); + sqlite3ExprCode(pParse, pLeft); + sqlite3VdbeAddOp(v, OP_Dup, 0, 0); + sqlite3ExprCode(pParse, pRight); + codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0); + sqlite3VdbeAddOp(v, OP_Pull, 1, 0); pLItem++; pRight = pLItem->pExpr; - sqlite3ReleaseTempReg(pParse, regFree2); - r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); - testcase( regFree2==0 ); - codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2); - sqlite3VdbeAddOp3(v, OP_And, r3, r4, target); - sqlite3ReleaseTempReg(pParse, r3); - sqlite3ReleaseTempReg(pParse, r4); + sqlite3ExprCode(pParse, pRight); + codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0); + sqlite3VdbeAddOp(v, OP_And, 0, 0); break; } case TK_UPLUS: { - inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + sqlite3ExprCode(pParse, pExpr->pLeft); + stackChng = 0; break; } - - /* - ** Form A: - ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END - ** - ** Form B: - ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END - ** - ** Form A is can be transformed into the equivalent form B as follows: - ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ... - ** WHEN x=eN THEN rN ELSE y END - ** - ** X (if it exists) is in pExpr->pLeft. - ** Y is in pExpr->pRight. The Y is also optional. If there is no - ** ELSE clause and no other term matches, then the result of the - ** exprssion is NULL. - ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1]. - ** - ** The result of the expression is the Ri for the first matching Ei, - ** or if there is no matching Ei, the ELSE term Y, or if there is - ** no ELSE term, NULL. - */ case TK_CASE: { - int endLabel; /* GOTO label for end of CASE stmt */ - int nextCase; /* GOTO label for next WHEN clause */ - int nExpr; /* 2x number of WHEN terms */ - int i; /* Loop counter */ - ExprList *pEList; /* List of WHEN terms */ - struct ExprList_item *aListelem; /* Array of WHEN terms */ - Expr opCompare; /* The X==Ei expression */ - Expr cacheX; /* Cached expression X */ - Expr *pX; /* The X expression */ - Expr *pTest; /* X==Ei (form A) or just Ei (form B) */ + int expr_end_label; + int jumpInst; + int nExpr; + int i; + ExprList *pEList; + struct ExprList_item *aListelem; assert(pExpr->pList); assert((pExpr->pList->nExpr % 2) == 0); @@ -52117,42 +45906,33 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) pEList = pExpr->pList; aListelem = pEList->a; nExpr = pEList->nExpr; - endLabel = sqlite3VdbeMakeLabel(v); - if( (pX = pExpr->pLeft)!=0 ){ - cacheX = *pX; - testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER ); - cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, ®Free1); - testcase( regFree1==0 ); - cacheX.op = TK_REGISTER; - cacheX.iColumn = 0; - opCompare.op = TK_EQ; - opCompare.pLeft = &cacheX; - pTest = &opCompare; + expr_end_label = sqlite3VdbeMakeLabel(v); + if( pExpr->pLeft ){ + sqlite3ExprCode(pParse, pExpr->pLeft); } - pParse->disableColCache++; for(i=0; ipLeft ){ + sqlite3VdbeAddOp(v, OP_Dup, 1, 1); + jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr, + OP_Ne, 0, 1); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); }else{ - pTest = aListelem[i].pExpr; + jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0); } - nextCase = sqlite3VdbeMakeLabel(v); - testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER ); - sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); - testcase( aListelem[i+1].pExpr->op==TK_COLUMN ); - testcase( aListelem[i+1].pExpr->op==TK_REGISTER ); - sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); - sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel); - sqlite3VdbeResolveLabel(v, nextCase); + sqlite3ExprCode(pParse, aListelem[i+1].pExpr); + sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label); + sqlite3VdbeJumpHere(v, jumpInst); + } + if( pExpr->pLeft ){ + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); } if( pExpr->pRight ){ - sqlite3ExprCode(pParse, pExpr->pRight, target); + sqlite3ExprCode(pParse, pExpr->pRight); }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, target); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); } - sqlite3VdbeResolveLabel(v, endLabel); - assert( pParse->disableColCache>0 ); - pParse->disableColCache--; + sqlite3VdbeResolveLabel(v, expr_end_label); break; } #ifndef SQLITE_OMIT_TRIGGER @@ -52160,231 +45940,78 @@ SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target) if( !pParse->trigStack ){ sqlite3ErrorMsg(pParse, "RAISE() may only be used within a trigger-program"); - return 0; + return; } if( pExpr->iColumn!=OE_Ignore ){ assert( pExpr->iColumn==OE_Rollback || pExpr->iColumn == OE_Abort || pExpr->iColumn == OE_Fail ); sqlite3DequoteExpr(pParse->db, pExpr); - sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0, + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, (char*)pExpr->token.z, pExpr->token.n); } else { assert( pExpr->iColumn == OE_Ignore ); - sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0); - sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump); - VdbeComment((v, "raise(IGNORE)")); + sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump); + VdbeComment((v, "# raise(IGNORE)")); } + stackChng = 0; break; } #endif } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); - return inReg; -} -/* -** Generate code to evaluate an expression and store the results -** into a register. Return the register number where the results -** are stored. -** -** If the register is a temporary register that can be deallocated, -** then write its number into *pReg. If the result register is not -** a temporary, then set *pReg to zero. -*/ -SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){ - int r1 = sqlite3GetTempReg(pParse); - int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); - if( r2==r1 ){ - *pReg = r1; - }else{ - sqlite3ReleaseTempReg(pParse, r1); - *pReg = 0; + if( pParse->ckOffset ){ + pParse->ckOffset += stackChng; + assert( pParse->ckOffset ); } - return r2; } +#ifndef SQLITE_OMIT_TRIGGER /* -** Generate code that will evaluate expression pExpr and store the -** results in register target. The results are guaranteed to appear -** in register target. -*/ -SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){ - int inReg; - - assert( target>0 && target<=pParse->nMem ); - inReg = sqlite3ExprCodeTarget(pParse, pExpr, target); - assert( pParse->pVdbe || pParse->db->mallocFailed ); - if( inReg!=target && pParse->pVdbe ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target); - } - return target; -} - -/* -** Generate code that evalutes the given expression and puts the result -** in register target. +** Generate code that evalutes the given expression and leaves the result +** on the stack. See also sqlite3ExprCode(). ** -** Also make a copy of the expression results into another "cache" register -** and modify the expression so that the next time it is evaluated, -** the result is a copy of the cache register. -** -** This routine is used for expressions that are used multiple -** times. They are evaluated once and the results of the expression -** are reused. +** This routine might also cache the result and modify the pExpr tree +** so that it will make use of the cached result on subsequent evaluations +** rather than evaluate the whole expression again. Trivial expressions are +** not cached. If the expression is cached, its result is stored in a +** memory location. */ -SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ +SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){ Vdbe *v = pParse->pVdbe; - int inReg; - inReg = sqlite3ExprCode(pParse, pExpr, target); - assert( target>0 ); - if( pExpr->op!=TK_REGISTER ){ - int iMem; - iMem = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem); - pExpr->iTable = iMem; - pExpr->iColumn = pExpr->op; + VdbeOp *pOp; + int iMem; + int addr1, addr2; + if( v==0 ) return; + addr1 = sqlite3VdbeCurrentAddr(v); + sqlite3ExprCode(pParse, pExpr); + addr2 = sqlite3VdbeCurrentAddr(v); + if( addr2>addr1+1 + || ((pOp = sqlite3VdbeGetOp(v, addr1))!=0 && pOp->opcode==OP_Function) ){ + iMem = pExpr->iTable = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0); pExpr->op = TK_REGISTER; } - return inReg; } - -/* -** Return TRUE if pExpr is an constant expression that is appropriate -** for factoring out of a loop. Appropriate expressions are: -** -** * Any expression that evaluates to two or more opcodes. -** -** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, -** or OP_Variable that does not need to be placed in a -** specific register. -** -** There is no point in factoring out single-instruction constant -** expressions that need to be placed in a particular register. -** We could factor them out, but then we would end up adding an -** OP_SCopy instruction to move the value into the correct register -** later. We might as well just use the original instruction and -** avoid the OP_SCopy. -*/ -static int isAppropriateForFactoring(Expr *p){ - if( !sqlite3ExprIsConstantNotJoin(p) ){ - return 0; /* Only constant expressions are appropriate for factoring */ - } - if( (p->flags & EP_FixedDest)==0 ){ - return 1; /* Any constant without a fixed destination is appropriate */ - } - while( p->op==TK_UPLUS ) p = p->pLeft; - switch( p->op ){ -#ifndef SQLITE_OMIT_BLOB_LITERAL - case TK_BLOB: #endif - case TK_VARIABLE: - case TK_INTEGER: - case TK_FLOAT: - case TK_NULL: - case TK_STRING: { - testcase( p->op==TK_BLOB ); - testcase( p->op==TK_VARIABLE ); - testcase( p->op==TK_INTEGER ); - testcase( p->op==TK_FLOAT ); - testcase( p->op==TK_NULL ); - testcase( p->op==TK_STRING ); - /* Single-instruction constants with a fixed destination are - ** better done in-line. If we factor them, they will just end - ** up generating an OP_SCopy to move the value to the destination - ** register. */ - return 0; - } - case TK_UMINUS: { - if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){ - return 0; - } - break; - } - default: { - break; - } - } - return 1; -} - -/* -** If pExpr is a constant expression that is appropriate for -** factoring out of a loop, then evaluate the expression -** into a register and convert the expression into a TK_REGISTER -** expression. -*/ -static int evalConstExpr(void *pArg, Expr *pExpr){ - Parse *pParse = (Parse*)pArg; - switch( pExpr->op ){ - case TK_REGISTER: { - return 1; - } - case TK_FUNCTION: - case TK_AGG_FUNCTION: - case TK_CONST_FUNC: { - /* The arguments to a function have a fixed destination. - ** Mark them this way to avoid generated unneeded OP_SCopy - ** instructions. - */ - ExprList *pList = pExpr->pList; - if( pList ){ - int i = pList->nExpr; - struct ExprList_item *pItem = pList->a; - for(; i>0; i--, pItem++){ - if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest; - } - } - break; - } - } - if( isAppropriateForFactoring(pExpr) ){ - int r1 = ++pParse->nMem; - int r2; - r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1); - if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1); - pExpr->iColumn = pExpr->op; - pExpr->op = TK_REGISTER; - pExpr->iTable = r2; - return 1; - } - return 0; -} - -/* -** Preevaluate constant subexpressions within pExpr and store the -** results in registers. Modify pExpr so that the constant subexpresions -** are TK_REGISTER opcodes that refer to the precomputed values. -*/ -SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){ - walkExprTree(pExpr, evalConstExpr, pParse); -} - /* ** Generate code that pushes the value of every element of the given -** expression list into a sequence of registers beginning at target. +** expression list onto the stack. ** -** Return the number of elements evaluated. +** Return the number of elements pushed onto the stack. */ SQLITE_PRIVATE int sqlite3ExprCodeExprList( Parse *pParse, /* Parsing context */ - ExprList *pList, /* The expression list to be coded */ - int target, /* Where to write results */ - int doHardCopy /* Call sqlite3ExprHardCopy on each element if true */ + ExprList *pList /* The expression list to be coded */ ){ struct ExprList_item *pItem; int i, n; - assert( pList!=0 || pParse->db->mallocFailed ); - if( pList==0 ){ - return 0; - } - assert( target>0 ); + if( pList==0 ) return 0; n = pList->nExpr; - for(pItem=pList->a, i=0; ipExpr, target+i); - if( doHardCopy ) sqlite3ExprHardCopy(pParse, target, n); + for(pItem=pList->a, i=n; i>0; i--, pItem++){ + sqlite3ExprCode(pParse, pItem->pExpr); } return n; } @@ -52395,7 +46022,7 @@ SQLITE_PRIVATE int sqlite3ExprCodeExprList( ** continues straight thru if the expression is false. ** ** If the expression evaluates to NULL (neither true nor false), then -** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. +** take the jump if the jumpIfNull flag is true. ** ** This code depends on the fact that certain token values (ex: TK_EQ) ** are the same as opcode values (ex: OP_Eq) that implement the corresponding @@ -52406,38 +46033,23 @@ SQLITE_PRIVATE int sqlite3ExprCodeExprList( SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; - int regFree1 = 0; - int regFree2 = 0; - int r1, r2; - - assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); + int ckOffset = pParse->ckOffset; if( v==0 || pExpr==0 ) return; op = pExpr->op; switch( op ){ case TK_AND: { int d2 = sqlite3VdbeMakeLabel(v); - testcase( jumpIfNull==0 ); - testcase( pParse->disableColCache==0 ); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); - pParse->disableColCache++; + sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull); sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - assert( pParse->disableColCache>0 ); - pParse->disableColCache--; sqlite3VdbeResolveLabel(v, d2); break; } case TK_OR: { - testcase( jumpIfNull==0 ); - testcase( pParse->disableColCache==0 ); sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull); - pParse->disableColCache++; sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); - assert( pParse->disableColCache>0 ); - pParse->disableColCache--; break; } case TK_NOT: { - testcase( jumpIfNull==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); break; } @@ -52453,74 +46065,50 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int assert( TK_GE==OP_Ge ); assert( TK_EQ==OP_Eq ); assert( TK_NE==OP_Ne ); - testcase( op==TK_LT ); - testcase( op==TK_LE ); - testcase( op==TK_GT ); - testcase( op==TK_GE ); - testcase( op==TK_EQ ); - testcase( op==TK_NE ); - testcase( jumpIfNull==0 ); - codeCompareOperands(pParse, pExpr->pLeft, &r1, ®Free1, - pExpr->pRight, &r2, ®Free2); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, - r1, r2, dest, jumpIfNull); - testcase( regFree1==0 ); - testcase( regFree2==0 ); + sqlite3ExprCode(pParse, pExpr->pLeft); + sqlite3ExprCode(pParse, pExpr->pRight); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull); break; } case TK_ISNULL: case TK_NOTNULL: { assert( TK_ISNULL==OP_IsNull ); assert( TK_NOTNULL==OP_NotNull ); - testcase( op==TK_ISNULL ); - testcase( op==TK_NOTNULL ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - sqlite3VdbeAddOp2(v, op, r1, dest); - testcase( regFree1==0 ); + sqlite3ExprCode(pParse, pExpr->pLeft); + sqlite3VdbeAddOp(v, op, 1, dest); break; } case TK_BETWEEN: { - /* x BETWEEN y AND z + /* The expression "x BETWEEN y AND z" is implemented as: ** - ** Is equivalent to - ** - ** x>=y AND x<=z - ** - ** Code it as such, taking care to do the common subexpression - ** elementation of x. + ** 1 IF (x < y) GOTO 3 + ** 2 IF (x <= z) GOTO + ** 3 ... */ - Expr exprAnd; - Expr compLeft; - Expr compRight; - Expr exprX; + int addr; + Expr *pLeft = pExpr->pLeft; + Expr *pRight = pExpr->pList->a[0].pExpr; + sqlite3ExprCode(pParse, pLeft); + sqlite3VdbeAddOp(v, OP_Dup, 0, 0); + sqlite3ExprCode(pParse, pRight); + addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull); - exprX = *pExpr->pLeft; - exprAnd.op = TK_AND; - exprAnd.pLeft = &compLeft; - exprAnd.pRight = &compRight; - compLeft.op = TK_GE; - compLeft.pLeft = &exprX; - compLeft.pRight = pExpr->pList->a[0].pExpr; - compRight.op = TK_LE; - compRight.pLeft = &exprX; - compRight.pRight = pExpr->pList->a[1].pExpr; - exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, ®Free1); - testcase( regFree1==0 ); - exprX.op = TK_REGISTER; - testcase( jumpIfNull==0 ); - sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull); + pRight = pExpr->pList->a[1].pExpr; + sqlite3ExprCode(pParse, pRight); + codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull); + + sqlite3VdbeAddOp(v, OP_Integer, 0, 0); + sqlite3VdbeJumpHere(v, addr); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); break; } default: { - r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); - sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); - testcase( regFree1==0 ); - testcase( jumpIfNull==0 ); + sqlite3ExprCode(pParse, pExpr); + sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest); break; } } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); + pParse->ckOffset = ckOffset; } /* @@ -52529,17 +46117,12 @@ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int ** continues straight thru if the expression is true. ** ** If the expression evaluates to NULL (neither true nor false) then -** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull -** is 0. +** jump if jumpIfNull is true or fall through if jumpIfNull is false. */ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; - int regFree1 = 0; - int regFree2 = 0; - int r1, r2; - - assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); + int ckOffset = pParse->ckOffset; if( v==0 || pExpr==0 ) return; /* The value of pExpr->op and op are related as follows: @@ -52575,24 +46158,14 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int switch( pExpr->op ){ case TK_AND: { - testcase( jumpIfNull==0 ); - testcase( pParse->disableColCache==0 ); sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull); - pParse->disableColCache++; sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - assert( pParse->disableColCache>0 ); - pParse->disableColCache--; break; } case TK_OR: { int d2 = sqlite3VdbeMakeLabel(v); - testcase( jumpIfNull==0 ); - testcase( pParse->disableColCache==0 ); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); - pParse->disableColCache++; + sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull); sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); - assert( pParse->disableColCache>0 ); - pParse->disableColCache--; sqlite3VdbeResolveLabel(v, d2); break; } @@ -52606,72 +46179,47 @@ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int case TK_GE: case TK_NE: case TK_EQ: { - testcase( op==TK_LT ); - testcase( op==TK_LE ); - testcase( op==TK_GT ); - testcase( op==TK_GE ); - testcase( op==TK_EQ ); - testcase( op==TK_NE ); - testcase( jumpIfNull==0 ); - codeCompareOperands(pParse, pExpr->pLeft, &r1, ®Free1, - pExpr->pRight, &r2, ®Free2); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, - r1, r2, dest, jumpIfNull); - testcase( regFree1==0 ); - testcase( regFree2==0 ); + sqlite3ExprCode(pParse, pExpr->pLeft); + sqlite3ExprCode(pParse, pExpr->pRight); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull); break; } case TK_ISNULL: case TK_NOTNULL: { - testcase( op==TK_ISNULL ); - testcase( op==TK_NOTNULL ); - r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); - sqlite3VdbeAddOp2(v, op, r1, dest); - testcase( regFree1==0 ); + sqlite3ExprCode(pParse, pExpr->pLeft); + sqlite3VdbeAddOp(v, op, 1, dest); break; } case TK_BETWEEN: { - /* x BETWEEN y AND z + /* The expression is "x BETWEEN y AND z". It is implemented as: ** - ** Is equivalent to - ** - ** x>=y AND x<=z - ** - ** Code it as such, taking care to do the common subexpression - ** elementation of x. + ** 1 IF (x >= y) GOTO 3 + ** 2 GOTO + ** 3 IF (x > z) GOTO */ - Expr exprAnd; - Expr compLeft; - Expr compRight; - Expr exprX; + int addr; + Expr *pLeft = pExpr->pLeft; + Expr *pRight = pExpr->pList->a[0].pExpr; + sqlite3ExprCode(pParse, pLeft); + sqlite3VdbeAddOp(v, OP_Dup, 0, 0); + sqlite3ExprCode(pParse, pRight); + addr = sqlite3VdbeCurrentAddr(v); + codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull); - exprX = *pExpr->pLeft; - exprAnd.op = TK_AND; - exprAnd.pLeft = &compLeft; - exprAnd.pRight = &compRight; - compLeft.op = TK_GE; - compLeft.pLeft = &exprX; - compLeft.pRight = pExpr->pList->a[0].pExpr; - compRight.op = TK_LE; - compRight.pLeft = &exprX; - compRight.pRight = pExpr->pList->a[1].pExpr; - exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, ®Free1); - testcase( regFree1==0 ); - exprX.op = TK_REGISTER; - testcase( jumpIfNull==0 ); - sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, dest); + pRight = pExpr->pList->a[1].pExpr; + sqlite3ExprCode(pParse, pRight); + codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull); break; } default: { - r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); - sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); - testcase( regFree1==0 ); - testcase( jumpIfNull==0 ); + sqlite3ExprCode(pParse, pExpr); + sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest); break; } } - sqlite3ReleaseTempReg(pParse, regFree1); - sqlite3ReleaseTempReg(pParse, regFree2); + pParse->ckOffset = ckOffset; } /* @@ -52802,7 +46350,7 @@ static int analyzeAggregate(void *pArg, Expr *pExpr){ pCol->pTab = pExpr->pTab; pCol->iTable = pExpr->iTable; pCol->iColumn = pExpr->iColumn; - pCol->iMem = ++pParse->nMem; + pCol->iMem = pParse->nMem++; pCol->iSorterColumn = -1; pCol->pExpr = pExpr; if( pAggInfo->pGroupBy ){ @@ -52858,7 +46406,7 @@ static int analyzeAggregate(void *pArg, Expr *pExpr){ if( i>=0 ){ pItem = &pAggInfo->aFunc[i]; pItem->pExpr = pExpr; - pItem->iMem = ++pParse->nMem; + pItem->iMem = pParse->nMem++; pItem->pFunc = sqlite3FindFunction(pParse->db, (char*)pExpr->token.z, pExpr->token.n, pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0); @@ -52897,9 +46445,14 @@ static int analyzeAggregate(void *pArg, Expr *pExpr){ ** ** This routine should only be called after the expression has been ** analyzed by sqlite3ExprResolveNames(). +** +** If errors are seen, leave an error message in zErrMsg and return +** the number of errors. */ -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ +SQLITE_PRIVATE int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ + int nErr = pNC->pParse->nErr; walkExprTree(pExpr, analyzeAggregate, pNC); + return pNC->pParse->nErr - nErr; } /* @@ -52908,53 +46461,16 @@ SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ ** ** If an error is found, the analysis is cut short. */ -SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ +SQLITE_PRIVATE int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ struct ExprList_item *pItem; int i; + int nErr = 0; if( pList ){ - for(pItem=pList->a, i=0; inExpr; i++, pItem++){ - sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); + for(pItem=pList->a, i=0; nErr==0 && inExpr; i++, pItem++){ + nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); } } -} - -/* -** Allocate or deallocate temporary use registers during code generation. -*/ -SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ - if( pParse->nTempReg==0 ){ - return ++pParse->nMem; - } - return pParse->aTempReg[--pParse->nTempReg]; -} -SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ - if( iReg && pParse->nTempRegaTempReg) ){ - sqlite3ExprWritableRegister(pParse, iReg, iReg); - pParse->aTempReg[pParse->nTempReg++] = iReg; - } -} - -/* -** Allocate or deallocate a block of nReg consecutive registers -*/ -SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ - int i, n; - i = pParse->iRangeReg; - n = pParse->nRangeReg; - if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){ - pParse->iRangeReg += nReg; - pParse->nRangeReg -= nReg; - }else{ - i = pParse->nMem+1; - pParse->nMem += nReg; - } - return i; -} -SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ - if( nReg>pParse->nRangeReg ){ - pParse->nRangeReg = nReg; - pParse->iRangeReg = iReg; - } + return nErr; } /************** End of expr.c ************************************************/ @@ -52973,7 +46489,7 @@ SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){ ** This file contains C code routines that used to generate VDBE code ** that implements the ALTER TABLE command. ** -** $Id: alter.c,v 1.46 2008/07/15 14:47:19 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* @@ -53010,11 +46526,11 @@ static void renameTableFunc( int len = 0; char *zRet; - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); /* The principle used to locate the table name in the CREATE TABLE - ** statement is that the table name is the first non-space token that - ** is immediately followed by a TK_LP or TK_USING token. + ** statement is that the table name is the first token that is immediatedly + ** followed by a left parenthesis - TK_LP - or "USING" TK_USING. */ if( zSql ){ do { @@ -53033,11 +46549,11 @@ static void renameTableFunc( do { zCsr += len; len = sqlite3GetToken(zCsr, &token); - } while( token==TK_SPACE || token==TK_COMMENT ); + } while( token==TK_SPACE ); assert( len>0 ); } while( token!=TK_LP && token!=TK_USING ); - zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, + zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql, zTableName, tname.z+tname.n); sqlite3_result_text(context, zRet, -1, sqlite3_free); } @@ -53066,7 +46582,7 @@ static void renameTriggerFunc( int len = 0; char *zRet; - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); /* The principle used to locate the table name in the CREATE TRIGGER ** statement is that the table name is the first token that is immediatedly @@ -53112,7 +46628,7 @@ static void renameTriggerFunc( /* Variable tname now contains the token that is the old table-name ** in the CREATE TRIGGER statement. */ - zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", tname.z - zSql, zSql, + zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql, zTableName, tname.z+tname.n); sqlite3_result_text(context, zRet, -1, sqlite3_free); } @@ -53123,12 +46639,22 @@ static void renameTriggerFunc( ** Register built-in functions used to help implement ALTER TABLE */ SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){ - sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0, - renameTableFunc, 0, 0); + static const struct { + char *zName; + signed char nArg; + void (*xFunc)(sqlite3_context*,int,sqlite3_value **); + } aFuncs[] = { + { "sqlite_rename_table", 2, renameTableFunc}, #ifndef SQLITE_OMIT_TRIGGER - sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0, - renameTriggerFunc, 0, 0); + { "sqlite_rename_trigger", 2, renameTriggerFunc}, #endif + }; + int i; + + for(i=0; ipTrigger; pTrig; pTrig=pTrig->pNext){ int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); assert( iTrigDb==iDb || iTrigDb==1 ); - sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0); + sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0); } #endif /* Drop the table and index from the internal schema */ - sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); + sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0); /* Reload the table, index and permanent trigger schemas. */ zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); if( !zWhere ) return; - sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC); + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC); #ifndef SQLITE_OMIT_TRIGGER /* Now, if the table is not stored in the temp database, reload any temp ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. */ if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ - sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC); + sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC); } #endif } @@ -53240,7 +46766,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable( assert( pSrc->nSrc==1 ); assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase); + pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase); if( !pTab ) goto exit_rename_table; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); zDb = db->aDb[iDb].zName; @@ -53302,7 +46828,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable( goto exit_rename_table; } sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb); - sqlite3ChangeCookie(pParse, iDb); + sqlite3ChangeCookie(db, v, iDb); /* If this is a virtual table, invoke the xRename() function if ** one is defined. The xRename() callback will modify the names @@ -53311,9 +46837,8 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable( */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( isVirtualRename ){ - int i = ++pParse->nMem; - sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0); - sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB); + sqlite3VdbeOp3(v, OP_String8, 0, 0, zName, 0); + sqlite3VdbeOp3(v, OP_VRename, 0, 0, (const char*)pTab->pVtab, P3_VTAB); } #endif @@ -53352,7 +46877,7 @@ SQLITE_PRIVATE void sqlite3AlterRenameTable( */ if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ sqlite3NestedParse(pParse, - "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", + "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q", zDb, zName, pTab->zName); } #endif @@ -53471,7 +46996,7 @@ SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ *zEnd-- = '\0'; } sqlite3NestedParse(pParse, - "UPDATE \"%w\".%s SET " + "UPDATE %Q.%s SET " "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " "WHERE type = 'table' AND name = %Q", zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1, @@ -53518,7 +47043,7 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ assert( pParse->pNewTable==0 ); assert( sqlite3BtreeHoldsAllMutexes(db) ); if( db->mallocFailed ) goto exit_begin_add_column; - pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase); + pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase); if( !pTab ) goto exit_begin_add_column; #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -53570,7 +47095,7 @@ SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ sqlite3BeginWriteOperation(pParse, 0, iDb); v = sqlite3GetVdbe(pParse); if( !v ) goto exit_begin_add_column; - sqlite3ChangeCookie(pParse, iDb); + sqlite3ChangeCookie(db, v, iDb); exit_begin_add_column: sqlite3SrcListDelete(pSrc); @@ -53593,7 +47118,7 @@ exit_begin_add_column: ************************************************************************* ** This file contains code associated with the ANALYZE command. ** -** @(#) $Id: analyze.c,v 1.42 2008/03/25 09:47:35 danielk1977 Exp $ +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef SQLITE_OMIT_ANALYZE @@ -53614,7 +47139,6 @@ static void openStatTable( sqlite3 *db = pParse->db; Db *pDb; int iRootPage; - int createStat1 = 0; Table *pStat; Vdbe *v = sqlite3GetVdbe(pParse); @@ -53625,14 +47149,13 @@ static void openStatTable( if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){ /* The sqlite_stat1 tables does not exist. Create it. ** Note that a side-effect of the CREATE TABLE statement is to leave - ** the rootpage of the new table in register pParse->regRoot. This is + ** the rootpage of the new table on the top of the stack. This is ** important because the OpenWrite opcode below will be needing it. */ sqlite3NestedParse(pParse, "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)", pDb->zName ); - iRootPage = pParse->regRoot; - createStat1 = 1; /* Cause rootpage to be taken from top of stack */ + iRootPage = 0; /* Cause rootpage to be taken from top of stack */ }else if( zWhere ){ /* The sqlite_stat1 table exists. Delete all entries associated with ** the table zWhere. */ @@ -53644,7 +47167,7 @@ static void openStatTable( }else{ /* The sqlite_stat1 table already exists. Delete all rows. */ iRootPage = pStat->tnum; - sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb); + sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb); } /* Open the sqlite_stat1 table for writing. Unless it was created @@ -53652,12 +47175,12 @@ static void openStatTable( ** If this vdbe did create the sqlite_stat1 table, then it must have ** already obtained a schema-lock, making the write-lock redundant. */ - if( !createStat1 ){ + if( iRootPage>0 ){ sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1"); } - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3); - sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb); - sqlite3VdbeChangeP5(v, createStat1); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage); + sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3); } /* @@ -53701,27 +47224,19 @@ static void analyzeOneTable( iIdxCur = pParse->nTab; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); - int regFields; /* Register block for building records */ - int regRec; /* Register holding completed record */ - int regTemp; /* Temporary use register */ - int regCol; /* Content of a column from the table being analyzed */ - int regRowid; /* Rowid for the inserted record */ - int regF2; /* Open a cursor to the index to be analyzed */ assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) ); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + VdbeComment((v, "# %s", pIdx->zName)); + sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, + (char *)pKey, P3_KEYINFO_HANDOFF); nCol = pIdx->nColumn; - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1); - sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb, - (char *)pKey, P4_KEYINFO_HANDOFF); - VdbeComment((v, "%s", pIdx->zName)); - regFields = iMem+nCol*2; - regTemp = regRowid = regCol = regFields+3; - regRec = regCol+1; - if( regRec>pParse->nMem ){ - pParse->nMem = regRec; + if( iMem+nCol*2>=pParse->nMem ){ + pParse->nMem = iMem+nCol*2+1; } + sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, nCol+1); /* Memory cells are used as follows: ** @@ -53737,33 +47252,33 @@ static void analyzeOneTable( ** are initialized to NULL. */ for(i=0; i<=nCol; i++){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i); + sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem+i); } for(i=0; i0 then it is always the case the D>0 so division by zero ** is never possible. */ - addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem); - sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0); - sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0); - regF2 = regFields+2; - sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2); + sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0); + addr = sqlite3VdbeAddOp(v, OP_IfNot, 0, 0); + sqlite3VdbeAddOp(v, OP_NewRowid, iStatCur, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0); + sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, " ", 0); for(i=0; inTab++; openStatTable(pParse, iDb, iStatCur, 0); - iMem = pParse->nMem+1; + iMem = pParse->nMem; for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ Table *pTab = (Table*)sqliteHashData(k); analyzeOneTable(pParse, pTab, iStatCur, iMem); @@ -53851,7 +47371,7 @@ static void analyzeTable(Parse *pParse, Table *pTab){ sqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab++; openStatTable(pParse, iDb, iStatCur, pTab->zName); - analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1); + analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem); loadAnalysis(pParse, iDb); } @@ -53896,7 +47416,7 @@ SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ }else{ z = sqlite3NameFromToken(db, pName1); if( z ){ - pTab = sqlite3LocateTable(pParse, 0, z, 0); + pTab = sqlite3LocateTable(pParse, z, 0); sqlite3_free(z); if( pTab ){ analyzeTable(pParse, pTab); @@ -53910,7 +47430,7 @@ SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){ zDb = db->aDb[iDb].zName; z = sqlite3NameFromToken(db, pTableName); if( z ){ - pTab = sqlite3LocateTable(pParse, 0, z, zDb); + pTab = sqlite3LocateTable(pParse, z, zDb); sqlite3_free(z); if( pTab ){ analyzeTable(pParse, pTab); @@ -53995,9 +47515,9 @@ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ /* Load new statistics out of the sqlite_stat1 table */ zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase); - (void)sqlite3SafetyOff(db); + sqlite3SafetyOff(db); rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); - (void)sqlite3SafetyOn(db); + sqlite3SafetyOn(db); sqlite3_free(zSql); return rc; } @@ -54020,7 +47540,7 @@ SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){ ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. ** -** $Id: attach.c,v 1.76 2008/06/15 02:51:47 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef SQLITE_OMIT_ATTACH @@ -54077,7 +47597,7 @@ static void attachFunc( ){ int i; int rc = 0; - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); const char *zName; const char *zFile; Db *aNew; @@ -54095,10 +47615,10 @@ static void attachFunc( ** * Transaction currently open ** * Specified database name already being used. */ - if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){ + if( db->nDb>=SQLITE_MAX_ATTACHED+2 ){ sqlite3_snprintf( sizeof(zErr), zErr, "too many attached databases - max %d", - db->aLimit[SQLITE_LIMIT_ATTACHED] + SQLITE_MAX_ATTACHED ); goto attach_error; } @@ -54120,12 +47640,18 @@ static void attachFunc( ** hash tables. */ if( db->aDb==db->aDbStatic ){ - aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 ); - if( aNew==0 ) return; + aNew = sqlite3_malloc( sizeof(db->aDb[0])*3 ); + if( aNew==0 ){ + db->mallocFailed = 1; + return; + } memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2); }else{ - aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); - if( aNew==0 ) return; + aNew = sqlite3_realloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) ); + if( aNew==0 ){ + db->mallocFailed = 1; + return; + } } db->aDb = aNew; aNew = &db->aDb[db->nDb++]; @@ -54139,7 +47665,6 @@ static void attachFunc( db->openFlags | SQLITE_OPEN_MAIN_DB, &aNew->pBt); if( rc==SQLITE_OK ){ - Pager *pPager; aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt); if( !aNew->pSchema ){ rc = SQLITE_NOMEM; @@ -54148,9 +47673,7 @@ static void attachFunc( "attached databases must use the same text encoding as main database"); goto attach_error; } - pPager = sqlite3BtreePager(aNew->pBt); - sqlite3PagerLockingMode(pPager, db->dfltLockMode); - sqlite3PagerJournalMode(pPager, db->dfltJournalMode); + sqlite3PagerLockingMode(sqlite3BtreePager(aNew->pBt), db->dfltLockMode); } aNew->zName = sqlite3DbStrDup(db, zName); aNew->safety_level = 3; @@ -54191,11 +47714,11 @@ static void attachFunc( ** we found it. */ if( rc==SQLITE_OK ){ - (void)sqlite3SafetyOn(db); + sqlite3SafetyOn(db); sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, &zErrDyn); sqlite3BtreeLeaveAll(db); - (void)sqlite3SafetyOff(db); + sqlite3SafetyOff(db); } if( rc ){ int iDb = db->nDb - 1; @@ -54227,7 +47750,6 @@ attach_error: zErr[sizeof(zErr)-1] = 0; sqlite3_result_error(context, zErr, -1); } - if( rc ) sqlite3_result_error_code(context, rc); } /* @@ -54244,7 +47766,7 @@ static void detachFunc( sqlite3_value **argv ){ const char *zName = (const char *)sqlite3_value_text(argv[0]); - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); int i; Db *pDb = 0; char zErr[128]; @@ -54303,7 +47825,6 @@ static void codeAttach( Vdbe *v; FuncDef *pFunc; sqlite3* db = pParse->db; - int regArgs; #ifndef SQLITE_OMIT_AUTHORIZATION assert( db->mallocFailed || pAuthArg ); @@ -54333,23 +47854,21 @@ static void codeAttach( } v = sqlite3GetVdbe(pParse); - regArgs = sqlite3GetTempRange(pParse, 4); - sqlite3ExprCode(pParse, pFilename, regArgs); - sqlite3ExprCode(pParse, pDbname, regArgs+1); - sqlite3ExprCode(pParse, pKey, regArgs+2); + sqlite3ExprCode(pParse, pFilename); + sqlite3ExprCode(pParse, pDbname); + sqlite3ExprCode(pParse, pKey); assert( v || db->mallocFailed ); if( v ){ - sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-nFunc, regArgs+3); - sqlite3VdbeChangeP5(v, nFunc); + sqlite3VdbeAddOp(v, OP_Function, 0, nFunc); pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0); - sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF); + sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF); /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this ** statement only). For DETACH, set it to false (expire all existing ** statements). */ - sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); + sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0); } attach_end: @@ -54383,8 +47902,8 @@ SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *p SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){ #ifndef SQLITE_OMIT_ATTACH static const int enc = SQLITE_UTF8; - sqlite3CreateFunc(db, "sqlite_attach", 3, enc, 0, attachFunc, 0, 0); - sqlite3CreateFunc(db, "sqlite_detach", 1, enc, 0, detachFunc, 0, 0); + sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0); + sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0); #endif } @@ -54549,7 +48068,7 @@ SQLITE_PRIVATE int sqlite3FixTriggerStep( ** systems that do not need this facility may omit it by recompiling ** the library with -DSQLITE_OMIT_AUTHORIZATION=1 ** -** $Id: auth.c,v 1.29 2007/09/18 15:55:07 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* @@ -54793,7 +48312,7 @@ SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){ ** COMMIT ** ROLLBACK ** -** $Id: build.c,v 1.490 2008/07/08 23:40:20 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* @@ -54880,8 +48399,10 @@ static void codeTableLocks(Parse *pParse){ for(i=0; inTableLock; i++){ TableLock *p = &pParse->aTableLock[i]; int p1 = p->iDb; - sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock, - p->zName, P4_STATIC); + if( p->isWriteLock ){ + p1 = -1*(p1+1); + } + sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC); } } #else @@ -54905,7 +48426,6 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ db = pParse->db; if( db->mallocFailed ) return; if( pParse->nested ) return; - if( pParse->nErr ) return; if( !pParse->pVdbe ){ if( pParse->rc==SQLITE_OK && pParse->nErr ){ pParse->rc = SQLITE_ERROR; @@ -54918,7 +48438,7 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ */ v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp0(v, OP_Halt); + sqlite3VdbeAddOp(v, OP_Halt, 0, 0); /* The cookie mask contains one bit for each database file open. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are @@ -54933,17 +48453,13 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ for(iDb=0, mask=1; iDbnDb; mask<<=1, iDb++){ if( (mask & pParse->cookieMask)==0 ) continue; sqlite3VdbeUsesBtree(v, iDb); - sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); - sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); + sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0); + sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); } #ifndef SQLITE_OMIT_VIRTUALTABLE - { - int i; - for(i=0; inVtabLock; i++){ - char *vtab = (char *)pParse->apVtabLock[i]->pVtab; - sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); - } - pParse->nVtabLock = 0; + if( pParse->pVirtualLock ){ + char *vtab = (char *)pParse->pVirtualLock->pVtab; + sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB); } #endif @@ -54952,19 +48468,17 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ ** shared-cache feature is enabled. */ codeTableLocks(pParse); - sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); + sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto); } #ifndef SQLITE_OMIT_TRACE - if( !db->init.busy ){ - /* Change the P4 argument of the first opcode (which will always be - ** an OP_Trace) to be the complete text of the current SQL statement. - */ - VdbeOp *pOp = sqlite3VdbeGetOp(v, 0); - if( pOp && pOp->opcode==OP_Trace ){ - sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql); - } - } + /* Add a No-op that contains the complete text of the compiled SQL + ** statement as its P3 argument. This does not change the functionality + ** of the program. + ** + ** This is used to implement sqlite3_trace(). + */ + sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql); #endif /* SQLITE_OMIT_TRACE */ } @@ -54976,7 +48490,6 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0; sqlite3VdbeTrace(v, trace); #endif - assert( pParse->disableColCache==0 ); /* Disables and re-enables match */ sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3, pParse->nTab+3, pParse->explain); pParse->rc = SQLITE_DONE; @@ -55007,7 +48520,6 @@ SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ va_list ap; char *zSql; - char *zErrMsg = 0; # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar)) char saveBuf[SAVE_SZ]; @@ -55023,8 +48535,7 @@ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ pParse->nested++; memcpy(saveBuf, &pParse->nVar, SAVE_SZ); memset(&pParse->nVar, 0, SAVE_SZ); - sqlite3RunParser(pParse, zSql, &zErrMsg); - sqlite3_free(zErrMsg); + sqlite3RunParser(pParse, zSql, 0); sqlite3_free(zSql); memcpy(&pParse->nVar, saveBuf, SAVE_SZ); pParse->nested--; @@ -55045,13 +48556,11 @@ SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){ Table *p = 0; int i; - int nName; assert( zName!=0 ); - nName = sqlite3Strlen(db, zName) + 1; for(i=OMIT_TEMPDB; inDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue; - p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName); + p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1); if( p ) break; } return p; @@ -55067,12 +48576,7 @@ SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const cha ** routine leaves an error message in pParse->zErrMsg where ** sqlite3FindTable() does not. */ -SQLITE_PRIVATE Table *sqlite3LocateTable( - Parse *pParse, /* context in which to report errors */ - int isView, /* True if looking for a VIEW rather than a TABLE */ - const char *zName, /* Name of the table we are looking for */ - const char *zDbase /* Name of the database. Might be NULL */ -){ +SQLITE_PRIVATE Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){ Table *p; /* Read the database schema. If an error occurs, leave an error message @@ -55083,11 +48587,10 @@ SQLITE_PRIVATE Table *sqlite3LocateTable( p = sqlite3FindTable(pParse->db, zName, zDbase); if( p==0 ){ - const char *zMsg = isView ? "no such view" : "no such table"; if( zDbase ){ - sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); + sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName); }else{ - sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); + sqlite3ErrorMsg(pParse, "no such table: %s", zName); } pParse->checkSchema = 1; } @@ -55109,14 +48612,13 @@ SQLITE_PRIVATE Table *sqlite3LocateTable( SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){ Index *p = 0; int i; - int nName = sqlite3Strlen(db, zName)+1; for(i=OMIT_TEMPDB; inDb; i++){ int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */ Schema *pSchema = db->aDb[j].pSchema; if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue; assert( pSchema || (j==1 && !db->aDb[1].pBt) ); if( pSchema ){ - p = sqlite3HashFind(&pSchema->idxHash, zName, nName); + p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1); } if( p ) break; } @@ -55143,7 +48645,7 @@ static void sqliteDeleteIndex(Index *p){ Index *pOld; const char *zName = p->zName; - pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0); + pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0); assert( pOld==0 || pOld==p ); freeIndex(p); } @@ -55159,7 +48661,7 @@ SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char int len; Hash *pHash = &db->aDb[iDb].pSchema->idxHash; - len = sqlite3Strlen(db, zIdxName); + len = strlen(zIdxName); pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0); if( pIndex ){ if( pIndex->pTable->pIndex==pIndex ){ @@ -55385,8 +48887,9 @@ SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){ SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ Vdbe *v = sqlite3GetVdbe(p); sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb)); - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */ - sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT); + sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */ } /* @@ -55623,33 +49126,30 @@ SQLITE_PRIVATE void sqlite3StartTable( ** now. */ if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ - int j1; + int lbl; int fileFormat; - int reg1, reg2, reg3; sqlite3BeginWriteOperation(pParse, 0, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( isVirtual ){ - sqlite3VdbeAddOp0(v, OP_VBegin); + sqlite3VdbeAddOp(v, OP_VBegin, 0, 0); } #endif /* If the file format and encoding in the database have not been set, ** set them now. */ - reg1 = pParse->regRowid = ++pParse->nMem; - reg2 = pParse->regRoot = ++pParse->nMem; - reg3 = ++pParse->nMem; - sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */ + sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */ sqlite3VdbeUsesBtree(v, iDb); - j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); + lbl = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp(v, OP_If, 0, lbl); fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 1 : SQLITE_MAX_FILE_FORMAT; - sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3); - sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3); - sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0); + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1); + sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0); + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4); + sqlite3VdbeResolveLabel(v, lbl); /* This just creates a place-holder record in the sqlite_master table. ** The record created does not contain anything yet. It will be replaced @@ -55661,18 +49161,19 @@ SQLITE_PRIVATE void sqlite3StartTable( */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) if( isView || isVirtual ){ - sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); + sqlite3VdbeAddOp(v, OP_Integer, 0, 0); }else #endif { - sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); + sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0); } sqlite3OpenMasterTable(pParse, iDb); - sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1); - sqlite3VdbeAddOp2(v, OP_Null, 0, reg3); - sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3VdbeAddOp0(v, OP_Close); + sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0); + sqlite3VdbeAddOp(v, OP_Dup, 0, 0); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); + sqlite3VdbeAddOp(v, OP_Insert, 0, OPFLAG_APPEND); + sqlite3VdbeAddOp(v, OP_Close, 0, 0); + sqlite3VdbeAddOp(v, OP_Pull, 1, 0); } /* Normal (non-error) return. */ @@ -55710,14 +49211,11 @@ SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){ int i; char *z; Column *pCol; - sqlite3 *db = pParse->db; if( (p = pParse->pNewTable)==0 ) return; -#if SQLITE_MAX_COLUMN - if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + if( p->nCol+1>SQLITE_MAX_COLUMN ){ sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName); return; } -#endif z = sqlite3NameFromToken(pParse->db, pName); if( z==0 ) return; for(i=0; inCol; i++){ @@ -56037,7 +49535,7 @@ SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, i pColl = sqlite3GetCollSeq(db, pColl, zName, nName); if( !pColl ){ if( nName<0 ){ - nName = sqlite3Strlen(db, zName); + nName = strlen(zName); } sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName); pColl = 0; @@ -56064,13 +49562,9 @@ SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, i ** and the probability of hitting the same cookie value is only ** 1 chance in 2^32. So we're safe enough. */ -SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){ - int r1 = sqlite3GetTempReg(pParse); - sqlite3 *db = pParse->db; - Vdbe *v = pParse->pVdbe; - sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1); - sqlite3ReleaseTempReg(pParse, r1); +SQLITE_PRIVATE void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){ + sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0); + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0); } /* @@ -56117,7 +49611,7 @@ static void identPut(char *z, int *pIdx, char *zSignedIdent){ ** table. Memory to hold the text of the statement is obtained ** from sqliteMalloc() and must be freed by the calling function. */ -static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){ +static char *createTableStmt(Table *p, int isTemp){ int i, k, n; char *zStmt; char *zSep, *zSep2, *zEnd, *z; @@ -56141,11 +49635,8 @@ static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){ zEnd = "\n)"; } n += 35 + 6*p->nCol; - zStmt = sqlite3Malloc( n ); - if( zStmt==0 ){ - db->mallocFailed = 1; - return 0; - } + zStmt = sqlite3_malloc( n ); + if( zStmt==0 ) return 0; sqlite3_snprintf(n, zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE "); k = strlen(zStmt); @@ -56256,7 +49747,7 @@ SQLITE_PRIVATE void sqlite3EndTable( v = sqlite3GetVdbe(pParse); if( v==0 ) return; - sqlite3VdbeAddOp1(v, OP_Close, 0); + sqlite3VdbeAddOp(v, OP_Close, 0, 0); /* Create the rootpage for the new table and push it onto the stack. ** A view has no rootpage, so just push a zero onto the stack for @@ -56288,15 +49779,13 @@ SQLITE_PRIVATE void sqlite3EndTable( ** be redundant. */ if( pSelect ){ - SelectDest dest; Table *pSelTab; - - sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); - sqlite3VdbeChangeP5(v, 1); + sqlite3VdbeAddOp(v, OP_Dup, 0, 0); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0); pParse->nTab = 2; - sqlite3SelectDestInit(&dest, SRT_Table, 1); - sqlite3Select(pParse, pSelect, &dest, 0, 0, 0); - sqlite3VdbeAddOp1(v, OP_Close, 1); + sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0); + sqlite3VdbeAddOp(v, OP_Close, 1, 0); if( pParse->nErr==0 ){ pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect); if( pSelTab==0 ) return; @@ -56311,7 +49800,7 @@ SQLITE_PRIVATE void sqlite3EndTable( /* Compute the complete text of the CREATE statement */ if( pSelect ){ - zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema); + zStmt = createTableStmt(p, p->pSchema==db->aDb[1].pSchema); }else{ n = pEnd->z - pParse->sNameToken.z + 1; zStmt = sqlite3MPrintf(db, @@ -56327,18 +49816,16 @@ SQLITE_PRIVATE void sqlite3EndTable( */ sqlite3NestedParse(pParse, "UPDATE %Q.%s " - "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " - "WHERE rowid=#%d", + "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q " + "WHERE rowid=#1", db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zType, p->zName, p->zName, - pParse->regRoot, - zStmt, - pParse->regRowid + zStmt ); sqlite3_free(zStmt); - sqlite3ChangeCookie(pParse, iDb); + sqlite3ChangeCookie(db, v, iDb); #ifndef SQLITE_OMIT_AUTOINCREMENT /* Check to see if we need to create an sqlite_sequence table for @@ -56356,8 +49843,8 @@ SQLITE_PRIVATE void sqlite3EndTable( #endif /* Reparse everything to update our internal data structures */ - sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, - sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC); + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, + sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P3_DYNAMIC); } @@ -56633,22 +50120,20 @@ SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){ */ static void destroyRootPage(Parse *pParse, int iTable, int iDb){ Vdbe *v = sqlite3GetVdbe(pParse); - int r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); + sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb); #ifndef SQLITE_OMIT_AUTOVACUUM - /* OP_Destroy stores an in integer r1. If this integer + /* OP_Destroy pushes an integer onto the stack. If this integer ** is non-zero, then it is the root page number of a table moved to ** location iTable. The following code modifies the sqlite_master table to ** reflect this. ** - ** The "#%d" in the SQL is a special constant that means whatever value + ** The "#0" in the SQL is a special constant that means whatever value ** is on the top of the stack. See sqlite3RegisterExpr(). */ sqlite3NestedParse(pParse, - "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", - pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); + "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0", + pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable); #endif - sqlite3ReleaseTempReg(pParse, r1); } /* @@ -56724,8 +50209,7 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, goto exit_drop_table; } assert( pName->nSrc==1 ); - pTab = sqlite3LocateTable(pParse, isView, - pName->a[0].zName, pName->a[0].zDatabase); + pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase); if( pTab==0 ){ if( noErr ){ @@ -56809,7 +50293,7 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, if( IsVirtual(pTab) ){ Vdbe *v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp0(v, OP_VBegin); + sqlite3VdbeAddOp(v, OP_VBegin, 0, 0); } } #endif @@ -56850,14 +50334,6 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'", pDb->zName, SCHEMA_TABLE(iDb), pTab->zName); - - /* Drop any statistics from the sqlite_stat1 table, if it exists */ - if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName - ); - } - if( !isView && !IsVirtual(pTab) ){ destroyTable(pParse, pTab); } @@ -56866,10 +50342,10 @@ SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, ** the schema cookie. */ if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); + sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0); } - sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); - sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0); + sqlite3ChangeCookie(db, v, iDb); } sqliteViewResetAll(db, iDb); @@ -57018,7 +50494,7 @@ SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){ ** content of an index in response to a REINDEX command. ** ** if memRootPage is not negative, it means that the index is newly -** created. The register specified by memRootPage contains the +** created. The memory cell specified by memRootPage contains the ** root page number of the index. If memRootPage is negative, then ** the index already exists and must be cleared before being refilled and ** the root page number of the index is taken from pIndex->tnum. @@ -57031,8 +50507,6 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ int tnum; /* Root page of index */ Vdbe *v; /* Generate code into this virtual machine */ KeyInfo *pKey; /* KeyInfo for index */ - int regIdxKey; /* Registers containing the index key */ - int regRecord; /* Register holding assemblied index record */ sqlite3 *db = pParse->db; /* The database connection */ int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); @@ -57049,40 +50523,34 @@ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ v = sqlite3GetVdbe(pParse); if( v==0 ) return; if( memRootPage>=0 ){ - tnum = memRootPage; + sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0); + tnum = 0; }else{ tnum = pIndex->tnum; - sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); + sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb); } + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); pKey = sqlite3IndexKeyinfo(pParse, pIndex); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, - (char *)pKey, P4_KEYINFO_HANDOFF); - if( memRootPage>=0 ){ - sqlite3VdbeChangeP5(v, 1); - } + sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF); sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); - regRecord = sqlite3GetTempReg(pParse); - regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1); + addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0); + sqlite3GenerateIndexKey(v, pIndex, iTab); if( pIndex->onError!=OE_None ){ - int j1, j2; - int regRowid; - - regRowid = regIdxKey + pIndex->nColumn; - j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn); - j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, - 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32); - sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0, - "indexed columns are not unique", P4_STATIC); - sqlite3VdbeJumpHere(v, j1); - sqlite3VdbeJumpHere(v, j2); + int curaddr = sqlite3VdbeCurrentAddr(v); + int addr2 = curaddr+4; + sqlite3VdbeChangeP2(v, curaddr-1, addr2); + sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0); + sqlite3VdbeAddOp(v, OP_AddImm, 1, 0); + sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2); + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, + "indexed columns are not unique", P3_STATIC); + assert( db->mallocFailed || addr2==sqlite3VdbeCurrentAddr(v) ); } - sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); + sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0); + sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1); sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp1(v, OP_Close, iTab); - sqlite3VdbeAddOp1(v, OP_Close, iIdx); + sqlite3VdbeAddOp(v, OP_Close, iTab, 0); + sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); } /* @@ -57163,7 +50631,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( ** sqlite3FixSrcList can never fail. */ assert(0); } - pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, + pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName, pTblName->a[0].zDatabase); if( !pTab ) goto exit_create_index; assert( db->aDb[iDb].pSchema==pTab->pSchema ); @@ -57227,11 +50695,15 @@ SQLITE_PRIVATE void sqlite3CreateIndex( goto exit_create_index; } }else{ + char zBuf[30]; int n; Index *pLoop; for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){} - zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n); + sqlite3_snprintf(sizeof(zBuf),zBuf,"_%d",n); + zName = 0; + sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0); if( zName==0 ){ + db->mallocFailed = 1; goto exit_create_index; } } @@ -57444,7 +50916,7 @@ SQLITE_PRIVATE void sqlite3CreateIndex( else if( db->init.busy==0 ){ Vdbe *v; char *zStmt; - int iMem = ++pParse->nMem; + int iMem = pParse->nMem++; v = sqlite3GetVdbe(pParse); if( v==0 ) goto exit_create_index; @@ -57453,7 +50925,8 @@ SQLITE_PRIVATE void sqlite3CreateIndex( /* Create the rootpage for the index */ sqlite3BeginWriteOperation(pParse, 1, iDb); - sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); + sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0); + sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0); /* Gather the complete text of the CREATE INDEX statement into ** the zStmt variable @@ -57473,13 +50946,13 @@ SQLITE_PRIVATE void sqlite3CreateIndex( /* Add an entry in sqlite_master for this index */ sqlite3NestedParse(pParse, - "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);", + "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);", db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName, pTab->zName, - iMem, zStmt ); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); sqlite3_free(zStmt); /* Fill the index with data and reparse the schema. Code an OP_Expire @@ -57487,10 +50960,10 @@ SQLITE_PRIVATE void sqlite3CreateIndex( */ if( pTblName ){ sqlite3RefillIndex(pParse, pIndex, iMem); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, - sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC); - sqlite3VdbeAddOp1(v, OP_Expire, 0); + sqlite3ChangeCookie(db, v, iDb); + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, + sqlite3MPrintf(db, "name='%q'", pIndex->zName), P3_DYNAMIC); + sqlite3VdbeAddOp(v, OP_Expire, 0, 0); } } @@ -57534,17 +51007,12 @@ SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minForm Vdbe *v; v = sqlite3GetVdbe(pParse); if( v ){ - int r1 = sqlite3GetTempReg(pParse); - int r2 = sqlite3GetTempReg(pParse); - int j1; - sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1); + sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); sqlite3VdbeUsesBtree(v, iDb); - sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2); - j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2); - sqlite3VdbeJumpHere(v, j1); - sqlite3ReleaseTempReg(pParse, r1); - sqlite3ReleaseTempReg(pParse, r2); + sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0); + sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3); + sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0); + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1); } } @@ -57639,15 +51107,9 @@ SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName ); - if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){ - sqlite3NestedParse(pParse, - "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q", - db->aDb[iDb].zName, pIndex->zName - ); - } - sqlite3ChangeCookie(pParse, iDb); + sqlite3ChangeCookie(db, v, iDb); destroyRootPage(pParse, pIndex->tnum, iDb); - sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); + sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0); } exit_drop_index: @@ -57943,11 +51405,11 @@ SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){ if( !v ) return; if( type!=TK_DEFERRED ){ for(i=0; inDb; i++){ - sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); + sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); sqlite3VdbeUsesBtree(v, i); } } - sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); + sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0); } /* @@ -57963,7 +51425,7 @@ SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){ v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); + sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0); } } @@ -57980,7 +51442,7 @@ SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){ v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); + sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1); } } @@ -58007,10 +51469,16 @@ SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){ pParse->rc = rc; return 1; } - assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit ); + if( db->flags & !db->autoCommit ){ + rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1); + if( rc!=SQLITE_OK ){ + sqlite3ErrorMsg(pParse, "unable to get a write lock on " + "the temporary database file"); + pParse->rc = rc; + return 1; + } + } assert( db->aDb[1].pSchema ); - sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt), - db->dfltJournalMode); } return 0; } @@ -58046,7 +51514,7 @@ SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){ if( v==0 ) return; /* This only happens if there was a prior error */ db = pParse->db; if( pParse->cookieGoto==0 ){ - pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; + pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1; } if( iDb>=0 ){ assert( iDbnDb ); @@ -58087,7 +51555,7 @@ SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, sqlite3CodeVerifySchema(pParse, iDb); pParse->writeMask |= 1<nested==0 ){ - sqlite3VdbeAddOp1(v, OP_Statement, iDb); + sqlite3VdbeAddOp(v, OP_Statement, iDb, 0); } if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){ sqlite3BeginWriteOperation(pParse, setStatement, 1); @@ -58275,7 +51743,7 @@ SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ ** This file contains functions used to access the internal hash tables ** of user defined functions and collation sequences. ** -** $Id: callback.c,v 1.25 2008/07/08 14:52:10 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ @@ -58286,7 +51754,7 @@ SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){ */ static void callCollNeeded(sqlite3 *db, const char *zName, int nName){ assert( !db->xCollNeeded || !db->xCollNeeded16 ); - if( nName<0 ) nName = sqlite3Strlen(db, zName); + if( nName<0 ) nName = strlen(zName); if( db->xCollNeeded ){ char *zExternal = sqlite3DbStrNDup(db, zName, nName); if( !zExternal ) return; @@ -58419,7 +51887,7 @@ static CollSeq *findCollSeqEntry( int create ){ CollSeq *pColl; - if( nName<0 ) nName = sqlite3Strlen(db, zName); + if( nName<0 ) nName = strlen(zName); pColl = sqlite3HashFind(&db->aCollSeq, zName, nName); if( 0==pColl && create ){ @@ -58589,8 +52057,6 @@ SQLITE_PRIVATE FuncDef *sqlite3FindFunction( ** at a Schema struct. This function does not call sqlite3_free() on the ** pointer itself, it just cleans up subsiduary resources (i.e. the contents ** of the schema hash tables). -** -** The Schema.cache_size variable is not cleared. */ SQLITE_PRIVATE void sqlite3SchemaFree(void *p){ Hash temp1; @@ -58656,7 +52122,7 @@ SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){ ** This file contains C code routines that are called by the parser ** in order to generate code for DELETE FROM statements. ** -** $Id: delete.c,v 1.170 2008/07/08 23:40:20 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* @@ -58669,7 +52135,7 @@ SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ int i; struct SrcList_item *pItem; for(i=0, pItem=pSrc->a; inSrc; i++, pItem++){ - pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); + pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase); sqlite3DeleteTable(pItem->pTab); pItem->pTab = pTab; if( pTab ){ @@ -58718,43 +52184,13 @@ SQLITE_PRIVATE void sqlite3OpenTable( v = sqlite3GetVdbe(p); assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), pTab->zName); - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); - sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); - VdbeComment((v, "%s", pTab->zName)); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + VdbeComment((v, "# %s", pTab->zName)); + sqlite3VdbeAddOp(v, opcode, iCur, pTab->tnum); + sqlite3VdbeAddOp(v, OP_SetNumColumns, iCur, pTab->nCol); } -#if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) -/* -** Evaluate a view and store its result in an ephemeral table. The -** pWhere argument is an optional WHERE clause that restricts the -** set of rows in the view that are to be added to the ephemeral table. -*/ -SQLITE_PRIVATE void sqlite3MaterializeView( - Parse *pParse, /* Parsing context */ - Select *pView, /* View definition */ - Expr *pWhere, /* Optional WHERE clause to be added */ - int iCur /* Cursor number for ephemerial table */ -){ - SelectDest dest; - Select *pDup; - sqlite3 *db = pParse->db; - - pDup = sqlite3SelectDup(db, pView); - if( pWhere ){ - SrcList *pFrom; - - pWhere = sqlite3ExprDup(db, pWhere); - pFrom = sqlite3SrcListAppendFromTerm(pParse, 0, 0, 0, 0, pDup, 0, 0); - pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0); - } - sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); - sqlite3Select(pParse, pDup, &dest, 0, 0, 0); - sqlite3SelectDelete(pDup); -} -#endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */ - - /* ** Generate code for a DELETE FROM statement. ** @@ -58786,11 +52222,6 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( int isView; /* True if attempting to delete from a view */ int triggers_exist = 0; /* True if any triggers exist */ #endif - int iBeginAfterTrigger; /* Address of after trigger program */ - int iEndAfterTrigger; /* Exit of after trigger program */ - int iBeginBeforeTrigger; /* Address of before trigger program */ - int iEndBeforeTrigger; /* Exit of before trigger program */ - u32 old_col_mask = 0; /* Mask of OLD.* columns in use */ sContext.pParse = 0; db = pParse->db; @@ -58844,12 +52275,15 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( oldIdx = pParse->nTab++; } - /* Assign cursor number to the table and all its indices. + /* Resolve the column names in the WHERE clause. */ assert( pTabList->nSrc==1 ); iCur = pTabList->a[0].iCursor = pParse->nTab++; - for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - pParse->nTab++; + memset(&sNC, 0, sizeof(sNC)); + sNC.pParse = pParse; + sNC.pSrcList = pTabList; + if( sqlite3ExprResolveNames(&sNC, pWhere) ){ + goto delete_from_cleanup; } /* Start the view context @@ -58867,46 +52301,21 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, triggers_exist, iDb); - if( triggers_exist ){ - int orconf = ((pParse->trigStack)?pParse->trigStack->orconf:OE_Default); - int iGoto = sqlite3VdbeAddOp0(v, OP_Goto); - addr = sqlite3VdbeMakeLabel(v); - - iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v); - (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab, - -1, oldIdx, orconf, addr, &old_col_mask, 0); - iEndBeforeTrigger = sqlite3VdbeAddOp0(v, OP_Goto); - - iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v); - (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1, - oldIdx, orconf, addr, &old_col_mask, 0); - iEndAfterTrigger = sqlite3VdbeAddOp0(v, OP_Goto); - - sqlite3VdbeJumpHere(v, iGoto); - } - /* If we are trying to delete from a view, realize that view into ** a ephemeral table. */ if( isView ){ - sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, iCur); - } - - /* Resolve the column names in the WHERE clause. - */ - memset(&sNC, 0, sizeof(sNC)); - sNC.pParse = pParse; - sNC.pSrcList = pTabList; - if( sqlite3ExprResolveNames(&sNC, pWhere) ){ - goto delete_from_cleanup; + Select *pView = sqlite3SelectDup(db, pTab->pSelect); + sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0); + sqlite3SelectDelete(pView); } /* Initialize the counter of the number of rows deleted, if ** we are counting rows. */ if( db->flags & SQLITE_CountRows ){ - memCnt = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); + memCnt = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt); } /* Special case: A DELETE without a WHERE clause deletes everything. @@ -58921,19 +52330,19 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( if( !isView ){ sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); } - sqlite3VdbeAddOp2(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2); - addr2 = sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); - sqlite3VdbeAddOp2(v, OP_Next, iCur, addr2); - sqlite3VdbeAddOp1(v, OP_Close, iCur); + sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2); + addr2 = sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt); + sqlite3VdbeAddOp(v, OP_Next, iCur, addr2); + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); } if( !isView ){ - sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb); + sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, iDb); if( !pParse->nested ){ - sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); + sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC); } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); + sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, iDb); } } } @@ -58941,19 +52350,17 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( ** the table and pick which records to delete. */ else{ - int iRowid = ++pParse->nMem; /* Used for storing rowid values. */ - /* Begin the database scan */ - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); if( pWInfo==0 ) goto delete_from_cleanup; /* Remember the rowid of every item to be deleted. */ - sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid); - sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid); + sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0); + sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0); if( db->flags & SQLITE_CountRows ){ - sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); + sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt); } /* End the database scan loop. @@ -58963,8 +52370,8 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( /* Open the pseudo-table used to store OLD if there are triggers. */ if( triggers_exist ){ - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); - sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx); + sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0); + sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol); } /* Delete every item whose key was written to the list during the @@ -58973,53 +52380,58 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( */ end = sqlite3VdbeMakeLabel(v); - if( !isView ){ - /* Open cursors for the table we are deleting from and - ** all its indices. - */ - sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite); - } - - /* This is the beginning of the delete loop. If a trigger encounters - ** an IGNORE constraint, it jumps back to here. + /* This is the beginning of the delete loop when there are + ** row triggers. */ if( triggers_exist ){ - sqlite3VdbeResolveLabel(v, addr); - } - addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end); - - if( triggers_exist ){ - int iData = ++pParse->nMem; /* For storing row data of OLD table */ - - /* If the record is no longer present in the table, jump to the - ** next iteration of the loop through the contents of the fifo. - */ - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, iRowid); - - /* Populate the OLD.* pseudo-table */ - if( old_col_mask ){ - sqlite3VdbeAddOp2(v, OP_RowData, iCur, iData); - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, iData); + int mem1 = pParse->nMem++; + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end); + sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); + sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0); + if( !isView ){ + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); + } + sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr); + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); + sqlite3VdbeAddOp(v, OP_RowData, iCur, 0); + sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0); + if( !isView ){ + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); } - sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid); - /* Jump back and run the BEFORE triggers */ - sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger); - sqlite3VdbeJumpHere(v, iEndBeforeTrigger); + (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_BEFORE, pTab, + -1, oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default, + addr); + if( !isView ){ + sqlite3VdbeAddOp(v, OP_MemLoad, mem1, 0); + } } if( !isView ){ + /* Open cursors for the table we are deleting from and all its + ** indices. If there are row triggers, this happens inside the + ** OP_FifoRead loop because the cursor have to all be closed + ** before the trigger fires. If there are no row triggers, the + ** cursors are opened only once on the outside the loop. + */ + sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite); + + /* This is the beginning of the delete loop when there are no + ** row triggers */ + if( !triggers_exist ){ + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end); + sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); + } + /* Delete the row */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ - const char *pVtab = (const char *)pTab->pVtab; - sqlite3VtabMakeWritable(pParse, pTab); - sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB); + pParse->pVirtualLock = pTab; + sqlite3VdbeOp3(v, OP_VUpdate, 0, 1, (const char*)pTab->pVtab, P3_VTAB); }else #endif { - sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0); + sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0); } } @@ -59027,21 +52439,27 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( ** the AFTER triggers */ if( triggers_exist ){ - /* Jump back and run the AFTER triggers */ - sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger); - sqlite3VdbeJumpHere(v, iEndAfterTrigger); + if( !isView ){ + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ + sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum); + } + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); + } + (void)sqlite3CodeRowTrigger(pParse, TK_DELETE, 0, TRIGGER_AFTER, pTab, -1, + oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default, + addr); } /* End of the delete loop */ - sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + sqlite3VdbeAddOp(v, OP_Goto, 0, addr); sqlite3VdbeResolveLabel(v, end); /* Close the cursors after the loop if there are no row triggers */ - if( !isView && !IsVirtual(pTab) ){ + if( !triggers_exist && !IsVirtual(pTab) ){ for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ - sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum); + sqlite3VdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum); } - sqlite3VdbeAddOp1(v, OP_Close, iCur); + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); } } @@ -59051,9 +52469,10 @@ SQLITE_PRIVATE void sqlite3DeleteFrom( ** invoke the callback function. */ if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); + sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P3_STATIC); } delete_from_cleanup: @@ -59076,29 +52495,26 @@ delete_from_cleanup: ** 2. Read/write cursors for all indices of pTab must be open as ** cursor number base+i for the i-th index. ** -** 3. The record number of the row to be deleted must be stored in -** memory cell iRowid. +** 3. The record number of the row to be deleted must be on the top +** of the stack. ** ** This routine pops the top of the stack to remove the record number ** and then generates code to remove both the table record and all index ** entries that point to that record. */ SQLITE_PRIVATE void sqlite3GenerateRowDelete( - Parse *pParse, /* Parsing context */ + sqlite3 *db, /* The database containing the index */ + Vdbe *v, /* Generate code into this VDBE */ Table *pTab, /* Table containing the row to be deleted */ int iCur, /* Cursor number for the table */ - int iRowid, /* Memory cell that contains the rowid to delete */ int count /* Increment the row change counter */ ){ int addr; - Vdbe *v; - - v = pParse->pVdbe; - addr = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowid); - sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0); - sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0)); + addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0); + sqlite3GenerateRowIndexDelete(v, pTab, iCur, 0); + sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0)); if( count ){ - sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); + sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC); } sqlite3VdbeJumpHere(v, addr); } @@ -59120,72 +52536,49 @@ SQLITE_PRIVATE void sqlite3GenerateRowDelete( ** deleted. */ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( - Parse *pParse, /* Parsing and code generating context */ + Vdbe *v, /* Generate code into this VDBE */ Table *pTab, /* Table containing the row to be deleted */ int iCur, /* Cursor number for the table */ - int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ + char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */ ){ int i; Index *pIdx; - int r1; for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ - if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue; - r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0); - sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1); + if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue; + sqlite3GenerateIndexKey(v, pIdx, iCur); + sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0); } } /* -** Generate code that will assemble an index key and put it in register -** regOut. The key with be for index pIdx which is an index on pTab. +** Generate code that will assemble an index key and put it on the top +** of the tack. The key with be for index pIdx which is an index on pTab. ** iCur is the index of a cursor open on the pTab table and pointing to ** the entry that needs indexing. -** -** Return a register number which is the first in a block of -** registers that holds the elements of the index key. The -** block of registers has already been deallocated by the time -** this routine returns. */ -SQLITE_PRIVATE int sqlite3GenerateIndexKey( - Parse *pParse, /* Parsing context */ +SQLITE_PRIVATE void sqlite3GenerateIndexKey( + Vdbe *v, /* Generate code into this VDBE */ Index *pIdx, /* The index for which to generate a key */ - int iCur, /* Cursor number for the pIdx->pTable table */ - int regOut, /* Write the new index key to this register */ - int doMakeRec /* Run the OP_MakeRecord instruction if true */ + int iCur /* Cursor number for the pIdx->pTable table */ ){ - Vdbe *v = pParse->pVdbe; int j; Table *pTab = pIdx->pTable; - int regBase; - int nCol; - nCol = pIdx->nColumn; - regBase = sqlite3GetTempRange(pParse, nCol+1); - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol); - for(j=0; jnColumn; j++){ int idx = pIdx->aiColumn[j]; if( idx==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j); + sqlite3VdbeAddOp(v, OP_Dup, j, 0); }else{ - sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j); + sqlite3VdbeAddOp(v, OP_Column, iCur, idx); sqlite3ColumnDefault(v, pTab, idx); } } - if( doMakeRec ){ - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut); - sqlite3IndexAffinityStr(v, pIdx); - sqlite3ExprCacheAffinityChange(pParse, regBase, nCol+1); - } - sqlite3ReleaseTempRange(pParse, regBase, nCol+1); - return regBase; + sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0); + sqlite3IndexAffinityStr(v, pIdx); } -/* Make sure "isView" gets undefined in case this file becomes part of -** the amalgamation - so that subsequent files do not see isView as a -** macro. */ -#undef isView - /************** End of delete.c **********************************************/ /************** Begin file func.c ********************************************/ /* @@ -59206,7 +52599,7 @@ SQLITE_PRIVATE int sqlite3GenerateIndexKey( ** sqliteRegisterBuildinFunctions() found at the bottom of the file. ** All other code has file scope. ** -** $Id: func.c,v 1.195 2008/07/08 22:28:49 shane Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ @@ -59373,7 +52766,7 @@ static void substrFunc( if( argc==3 ){ p2 = sqlite3_value_int(argv[2]); }else{ - p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH]; + p2 = SQLITE_MAX_LENGTH; } if( p1<0 ){ p1 += len; @@ -59428,16 +52821,10 @@ static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ ** allocation fails, call sqlite3_result_error_nomem() to notify ** the database handle that malloc() has failed. */ -static void *contextMalloc(sqlite3_context *context, i64 nByte){ - char *z; - if( nByte>sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH] ){ - sqlite3_result_error_toobig(context); - z = 0; - }else{ - z = sqlite3Malloc(nByte); - if( !z && nByte>0 ){ - sqlite3_result_error_nomem(context); - } +static void *contextMalloc(sqlite3_context *context, int nByte){ + char *z = sqlite3_malloc(nByte); + if( !z && nByte>0 ){ + sqlite3_result_error_nomem(context); } return z; } @@ -59455,7 +52842,7 @@ static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ /* Verify that the call to _bytes() does not invalidate the _text() pointer */ assert( z2==(char*)sqlite3_value_text(argv[0]) ); if( z2 ){ - z1 = contextMalloc(context, ((i64)n)+1); + z1 = contextMalloc(context, n+1); if( z1 ){ memcpy(z1, z2, n+1); for(i=0; z1[i]; i++){ @@ -59475,7 +52862,7 @@ static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ /* Verify that the call to _bytes() does not invalidate the _text() pointer */ assert( z2==(char*)sqlite3_value_text(argv[0]) ); if( z2 ){ - z1 = contextMalloc(context, ((i64)n)+1); + z1 = contextMalloc(context, n+1); if( z1 ){ memcpy(z1, z2, n+1); for(i=0; z1[i]; i++){ @@ -59514,7 +52901,7 @@ static void randomFunc( sqlite3_value **argv ){ sqlite_int64 r; - sqlite3_randomness(sizeof(r), &r); + sqlite3Randomness(sizeof(r), &r); if( (r<<1)==0 ) r = 0; /* Prevent 0x8000.... as the result so that we */ /* can always do abs() of the result */ sqlite3_result_int64(context, r); @@ -59536,9 +52923,13 @@ static void randomBlob( if( n<1 ){ n = 1; } + if( n>SQLITE_MAX_LENGTH ){ + sqlite3_result_error_toobig(context); + return; + } p = contextMalloc(context, n); if( p ){ - sqlite3_randomness(n, p); + sqlite3Randomness(n, p); sqlite3_result_blob(context, (char*)p, n, sqlite3_free); } } @@ -59552,7 +52943,7 @@ static void last_insert_rowid( int arg, sqlite3_value **argv ){ - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); sqlite3_result_int64(context, sqlite3_last_insert_rowid(db)); } @@ -59565,7 +52956,7 @@ static void changes( int arg, sqlite3_value **argv ){ - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); sqlite3_result_int(context, sqlite3_changes(db)); } @@ -59578,7 +52969,7 @@ static void total_changes( int arg, sqlite3_value **argv ){ - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); sqlite3_result_int(context, sqlite3_total_changes(db)); } @@ -59778,7 +53169,6 @@ static void likeFunc( ){ const unsigned char *zA, *zB; int escape = 0; - sqlite3 *db = sqlite3_context_db_handle(context); zB = sqlite3_value_text(argv[0]); zA = sqlite3_value_text(argv[1]); @@ -59786,8 +53176,7 @@ static void likeFunc( /* Limit the length of the LIKE or GLOB pattern to avoid problems ** of deep recursion and N*N behavior in patternCompare(). */ - if( sqlite3_value_bytes(argv[0]) > - db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){ + if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){ sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1); return; } @@ -59879,7 +53268,12 @@ static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){ char const *zBlob = sqlite3_value_blob(argv[0]); int nBlob = sqlite3_value_bytes(argv[0]); assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ - zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); + + if( 2*nBlob+4>SQLITE_MAX_LENGTH ){ + sqlite3_result_error_toobig(context); + return; + } + zText = (char *)contextMalloc(context, (2*nBlob)+4); if( zText ){ int i; for(i=0; iSQLITE_MAX_LENGTH ){ + sqlite3_result_error_toobig(context); + return; + } + z = contextMalloc(context, i+n+3); if( z ){ z[0] = '\''; for(i=0, j=1; zArg[i]; i++){ @@ -59935,8 +53333,12 @@ static void hexFunc( assert( argc==1 ); pBlob = sqlite3_value_blob(argv[0]); n = sqlite3_value_bytes(argv[0]); + if( n*2+1>SQLITE_MAX_LENGTH ){ + sqlite3_result_error_toobig(context); + return; + } assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */ - z = zHex = contextMalloc(context, ((i64)n)*2 + 1); + z = zHex = contextMalloc(context, n*2 + 1); if( zHex ){ for(i=0; i=db->aLimit[SQLITE_LIMIT_LENGTH] ){ + if( nOut>=SQLITE_MAX_LENGTH ){ sqlite3_result_error_toobig(context); sqlite3_free(zOut); return; @@ -60080,7 +53481,7 @@ static void trimFunc( SQLITE_SKIP_UTF8(z); } if( nChar>0 ){ - azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1)); + azChar = contextMalloc(context, nChar*(sizeof(char*)+1)); if( azChar==0 ){ return; } @@ -60093,7 +53494,7 @@ static void trimFunc( } } if( nChar>0 ){ - flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context)); + flags = (int)sqlite3_user_data(context); if( flags & 1 ){ while( nIn>0 ){ int len; @@ -60182,7 +53583,7 @@ static void soundexFunc( static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ const char *zFile = (const char *)sqlite3_value_text(argv[0]); const char *zProc; - sqlite3 *db = sqlite3_context_db_handle(context); + sqlite3 *db = sqlite3_user_data(context); char *zErrMsg = 0; if( argc==2 ){ @@ -60197,6 +53598,168 @@ static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){ } #endif +#ifdef SQLITE_TEST +/* +** This function generates a string of random characters. Used for +** generating test data. +*/ +static void randStr(sqlite3_context *context, int argc, sqlite3_value **argv){ + static const unsigned char zSrc[] = + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + ".-!,:*^+=_|?/<> "; + int iMin, iMax, n, r, i; + unsigned char zBuf[1000]; + + /* It used to be possible to call randstr() with any number of arguments, + ** but now it is registered with SQLite as requiring exactly 2. + */ + assert(argc==2); + + iMin = sqlite3_value_int(argv[0]); + if( iMin<0 ) iMin = 0; + if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1; + iMax = sqlite3_value_int(argv[1]); + if( iMax=sizeof(zBuf) ) iMax = sizeof(zBuf)-1; + n = iMin; + if( iMax>iMin ){ + sqlite3Randomness(sizeof(r), &r); + r &= 0x7fffffff; + n += r%(iMax + 1 - iMin); + } + assert( nuseMalloc = 1; - pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH]; if( pAccum->nChar ){ - if( argc>1 ){ - zSep = (char*)sqlite3_value_text(argv[argc-1]); - nSep = sqlite3_value_bytes(argv[argc-1]); + if( argc==2 ){ + zSep = (char*)sqlite3_value_text(argv[1]); + nSep = sqlite3_value_bytes(argv[1]); }else{ zSep = ","; nSep = 1; } sqlite3StrAccumAppend(pAccum, zSep, nSep); } - i = 0; - do{ - zVal = (char*)sqlite3_value_text(argv[i]); - nVal = sqlite3_value_bytes(argv[i]); - sqlite3StrAccumAppend(pAccum, zVal, nVal); - i++; - }while( izColAff ){ @@ -60631,22 +54197,21 @@ SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ int n; Table *pTab = pIdx->pTable; sqlite3 *db = sqlite3VdbeDb(v); - pIdx->zColAff = (char *)sqlite3DbMallocRaw(db, pIdx->nColumn+2); + pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1); if( !pIdx->zColAff ){ return; } for(n=0; nnColumn; n++){ pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; } - pIdx->zColAff[n++] = SQLITE_AFF_NONE; - pIdx->zColAff[n] = 0; + pIdx->zColAff[pIdx->nColumn] = '\0'; } - sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0); + sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0); } /* -** Set P4 of the most recently inserted opcode to a column affinity +** Set P3 of the most recently inserted opcode to a column affinity ** string for table pTab. A column affinity string has one character ** for each column indexed by the index, according to the affinity of the ** column: @@ -60672,7 +54237,7 @@ SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ int i; sqlite3 *db = sqlite3VdbeDb(v); - zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1); + zColAff = (char *)sqlite3DbMallocZero(db, pTab->nCol+1); if( !zColAff ){ return; } @@ -60685,7 +54250,7 @@ SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){ pTab->zColAff = zColAff; } - sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0); + sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0); } /* @@ -60701,22 +54266,27 @@ static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){ for(i=iStartAddr; iopcode==OP_OpenRead && pOp->p3==iDb ){ - Index *pIndex; + if( pOp->opcode==OP_OpenRead ){ + VdbeOp *pPrior = &pOp[-1]; int tnum = pOp->p2; - if( tnum==pTab->tnum ){ - return 1; - } - for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ - if( tnum==pIndex->tnum ){ + assert( i>iStartAddr ); + assert( pPrior->opcode==OP_Integer ); + if( pPrior->p1==iDb ){ + Index *pIndex; + if( tnum==pTab->tnum ){ return 1; } + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ + if( tnum==pIndex->tnum ){ + return 1; + } + } } } #ifndef SQLITE_OMIT_VIRTUALTABLE - if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pTab->pVtab ){ - assert( pOp->p4.pVtab!=0 ); - assert( pOp->p4type==P4_VTAB ); + if( pOp->opcode==OP_VOpen && pOp->p3==(const char*)pTab->pVtab ){ + assert( pOp->p3!=0 ); + assert( pOp->p3type==P3_VTAB ); return 1; } #endif @@ -60728,49 +54298,45 @@ static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){ /* ** Write out code to initialize the autoincrement logic. This code ** looks up the current autoincrement value in the sqlite_sequence -** table and stores that value in a register. Code generated by -** autoIncStep() will keep that register holding the largest +** table and stores that value in a memory cell. Code generated by +** autoIncStep() will keep that memory cell holding the largest ** rowid value. Code generated by autoIncEnd() will write the new ** largest value of the counter back into the sqlite_sequence table. ** ** This routine returns the index of the mem[] cell that contains ** the maximum rowid counter. ** -** Three consecutive registers are allocated by this routine. The -** first two hold the name of the target table and the maximum rowid -** inserted into the target table, respectively. -** The third holds the rowid in sqlite_sequence where we will -** write back the revised maximum rowid. This routine returns the -** index of the second of these three registers. +** Two memory cells are allocated. The next memory cell after the +** one returned holds the rowid in sqlite_sequence where we will +** write back the revised maximum rowid. */ static int autoIncBegin( Parse *pParse, /* Parsing context */ int iDb, /* Index of the database holding pTab */ Table *pTab /* The table we are writing to */ ){ - int memId = 0; /* Register holding maximum rowid */ + int memId = 0; if( pTab->autoInc ){ Vdbe *v = pParse->pVdbe; Db *pDb = &pParse->db->aDb[iDb]; int iCur = pParse->nTab; - int addr; /* Address of the top of the loop */ + int addr; assert( v ); - pParse->nMem++; /* Holds name of table */ - memId = ++pParse->nMem; - pParse->nMem++; - sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead); addr = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0); - sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+9); - sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, memId); - sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); - sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, memId+1); - sqlite3VdbeAddOp3(v, OP_Column, iCur, 1, memId); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9); - sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2); - sqlite3VdbeAddOp2(v, OP_Integer, 0, memId); - sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); + memId = pParse->nMem+1; + pParse->nMem += 2; + sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenRead); + sqlite3VdbeAddOp(v, OP_Rewind, iCur, addr+13); + sqlite3VdbeAddOp(v, OP_Column, iCur, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0); + sqlite3VdbeAddOp(v, OP_Ne, 0x100, addr+12); + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); + sqlite3VdbeAddOp(v, OP_MemStore, memId-1, 1); + sqlite3VdbeAddOp(v, OP_Column, iCur, 1); + sqlite3VdbeAddOp(v, OP_MemStore, memId, 1); + sqlite3VdbeAddOp(v, OP_Goto, 0, addr+13); + sqlite3VdbeAddOp(v, OP_Next, iCur, addr+4); + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); } return memId; } @@ -60783,15 +54349,15 @@ static int autoIncBegin( ** larger than the maximum rowid in the memId memory cell, then the ** memory cell is updated. The stack is unchanged. */ -static void autoIncStep(Parse *pParse, int memId, int regRowid){ +static void autoIncStep(Parse *pParse, int memId){ if( memId>0 ){ - sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); + sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0); } } /* ** After doing one or more inserts, the maximum rowid is stored -** in reg[memId]. Generate code to write this value back into the +** in mem[memId]. Generate code to write this value back into the ** the sqlite_sequence table. */ static void autoIncEnd( @@ -60804,18 +54370,19 @@ static void autoIncEnd( int iCur = pParse->nTab; Vdbe *v = pParse->pVdbe; Db *pDb = &pParse->db->aDb[iDb]; - int j1; - int iRec = ++pParse->nMem; /* Memory cell used for record */ - + int addr; assert( v ); + addr = sqlite3VdbeCurrentAddr(v); sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); - j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); - sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1); - sqlite3VdbeJumpHere(v, j1); - sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec); - sqlite3VdbeAddOp3(v, OP_Insert, iCur, iRec, memId+1); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3VdbeAddOp1(v, OP_Close, iCur); + sqlite3VdbeAddOp(v, OP_MemLoad, memId-1, 0); + sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+7); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + sqlite3VdbeAddOp(v, OP_NewRowid, iCur, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0); + sqlite3VdbeAddOp(v, OP_MemLoad, memId, 0); + sqlite3VdbeAddOp(v, OP_MakeRecord, 2, 0); + sqlite3VdbeAddOp(v, OP_Insert, iCur, OPFLAG_APPEND); + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); } } #else @@ -60824,7 +54391,7 @@ static void autoIncEnd( ** above are all no-ops */ # define autoIncBegin(A,B,C) (0) -# define autoIncStep(A,B,C) +# define autoIncStep(A,B) # define autoIncEnd(A,B,C,D) #endif /* SQLITE_OMIT_AUTOINCREMENT */ @@ -60855,8 +54422,7 @@ static int xferOptimization( ** ** The code generated follows one of four templates. For a simple ** select with data coming from a VALUES clause, the code executes -** once straight down through. Pseudo-code follows (we call this -** the "1st template"): +** once straight down through. The template looks like this: ** ** open write cursor to
      and its indices ** puts VALUES clause expressions onto the stack @@ -60874,7 +54440,7 @@ static int xferOptimization( ** schemas, including all the same indices, then a special optimization ** is invoked that copies raw records from over to . ** See the xferOptimization() function for the implementation of this -** template. This is the 2nd template. +** template. This is the second template. ** ** open a write cursor to
      ** open read cursor on @@ -60887,58 +54453,45 @@ static int xferOptimization( ** close cursors ** end foreach ** -** The 3rd template is for when the second template does not apply +** The third template is for when the second template does not apply ** and the SELECT clause does not read from
      at any time. ** The generated code follows this template: ** -** EOF <- 0 -** X <- A ** goto B ** A: setup for the SELECT ** loop over the rows in the SELECT -** load values into registers R..R+n -** yield X +** gosub C ** end loop ** cleanup after the SELECT -** EOF <- 1 -** yield X -** goto A +** goto D ** B: open write cursor to
      and its indices -** C: yield X -** if EOF goto D -** insert the select result into
      from R..R+n -** goto C +** goto A +** C: insert the select result into
      +** return ** D: cleanup ** -** The 4th template is used if the insert statement takes its +** The fourth template is used if the insert statement takes its ** values from a SELECT but the data is being inserted into a table ** that is also read as part of the SELECT. In the third form, ** we have to use a intermediate table to store the results of ** the select. The template is like this: ** -** EOF <- 0 -** X <- A ** goto B ** A: setup for the SELECT ** loop over the tables in the SELECT -** load value into register R..R+n -** yield X +** gosub C ** end loop ** cleanup after the SELECT -** EOF <- 1 -** yield X -** halt-error -** B: open temp table -** L: yield X -** if EOF goto M -** insert row from R..R+n into temp table -** goto L -** M: open write cursor to
      and its indices -** rewind temp table -** C: loop over rows of intermediate table +** goto D +** C: insert the select result into the intermediate table +** return +** B: open a cursor to an intermediate table +** goto A +** D: open write cursor to
      and its indices +** loop over the intermediate table ** transfer values form intermediate table into
      -** end loop -** D: cleanup +** end the loop +** cleanup */ SQLITE_PRIVATE void sqlite3Insert( Parse *pParse, /* Parser context */ @@ -60948,40 +54501,31 @@ SQLITE_PRIVATE void sqlite3Insert( IdList *pColumn, /* Column names corresponding to IDLIST. */ int onError /* How to handle constraint errors */ ){ - sqlite3 *db; /* The main database structure */ - Table *pTab; /* The table to insert into. aka TABLE */ + Table *pTab; /* The table to insert into */ char *zTab; /* Name of the table into which we are inserting */ const char *zDb; /* Name of the database holding this table */ int i, j, idx; /* Loop counters */ Vdbe *v; /* Generate code into this virtual machine */ Index *pIdx; /* For looping over indices of the table */ int nColumn; /* Number of columns in the data */ - int nHidden = 0; /* Number of hidden columns if TABLE is virtual */ - int baseCur = 0; /* VDBE Cursor number for pTab */ + int base = 0; /* VDBE Cursor number for pTab */ + int iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */ + sqlite3 *db; /* The main database structure */ int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */ int endOfLoop; /* Label for the end of the insertion loop */ int useTempTable = 0; /* Store SELECT results in intermediate table */ int srcTab = 0; /* Data comes from this temporary cursor if >=0 */ - int addrInsTop = 0; /* Jump to label "D" */ - int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */ - int addrSelect = 0; /* Address of coroutine that implements the SELECT */ - SelectDest dest; /* Destination for SELECT on rhs of INSERT */ - int newIdx = -1; /* Cursor for the NEW pseudo-table */ - int iDb; /* Index of database holding TABLE */ + int iSelectLoop = 0; /* Address of code that implements the SELECT */ + int iCleanup = 0; /* Address of the cleanup code */ + int iInsertBlock = 0; /* Address of the subroutine used to insert data */ + int iCntMem = 0; /* Memory cell used for the row counter */ + int newIdx = -1; /* Cursor for the NEW table */ Db *pDb; /* The database containing table being inserted into */ + int counterMem = 0; /* Memory cell holding AUTOINCREMENT counter */ int appendFlag = 0; /* True if the insert is likely to be an append */ + int iDb; - /* Register allocations */ - int regFromSelect; /* Base register for data coming from SELECT */ - int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */ - int regRowCount = 0; /* Memory cell used for the row counter */ - int regIns; /* Block of regs holding rowid+data being inserted */ - int regRowid; /* registers holding insert rowid */ - int regData; /* register holding first column to insert */ - int regRecord; /* Holds the assemblied row record */ - int regEof; /* Register recording end of SELECT data */ - int *aRegIdx = 0; /* One register allocated to each index */ - + int nHidden = 0; #ifndef SQLITE_OMIT_TRIGGER int isView; /* True if attempting to insert into a view */ @@ -61061,8 +54605,6 @@ SQLITE_PRIVATE void sqlite3Insert( ** ** Then special optimizations can be applied that make the transfer ** very fast and which reduce fragmentation of indices. - ** - ** This is the 2nd template. */ if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){ assert( !triggers_exist ); @@ -61072,108 +54614,75 @@ SQLITE_PRIVATE void sqlite3Insert( #endif /* SQLITE_OMIT_XFER_OPT */ /* If this is an AUTOINCREMENT table, look up the sequence number in the - ** sqlite_sequence table and store it in memory cell regAutoinc. + ** sqlite_sequence table and store it in memory cell counterMem. Also + ** remember the rowid of the sqlite_sequence table entry in memory cell + ** counterRowid. */ - regAutoinc = autoIncBegin(pParse, iDb, pTab); + counterMem = autoIncBegin(pParse, iDb, pTab); /* Figure out how many columns of data are supplied. If the data - ** is coming from a SELECT statement, then generate a co-routine that - ** produces a single row of the SELECT on each invocation. The - ** co-routine is the common header to the 3rd and 4th templates. + ** is coming from a SELECT statement, then this step also generates + ** all the code to implement the SELECT statement and invoke a subroutine + ** to process each row of the result. (Template 2.) If the SELECT + ** statement uses the the table that is being inserted into, then the + ** subroutine is also coded here. That subroutine stores the SELECT + ** results in a temporary table. (Template 3.) */ if( pSelect ){ /* Data is coming from a SELECT. Generate code to implement that SELECT - ** as a co-routine. The code is common to both the 3rd and 4th - ** templates: - ** - ** EOF <- 0 - ** X <- A - ** goto B - ** A: setup for the SELECT - ** loop over the tables in the SELECT - ** load value into register R..R+n - ** yield X - ** end loop - ** cleanup after the SELECT - ** EOF <- 1 - ** yield X - ** halt-error - ** - ** On each invocation of the co-routine, it puts a single row of the - ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1. - ** (These output registers are allocated by sqlite3Select().) When - ** the SELECT completes, it sets the EOF flag stored in regEof. */ - int rc, j1; - - regEof = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */ - VdbeComment((v, "SELECT eof flag")); - sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem); - addrSelect = sqlite3VdbeCurrentAddr(v)+2; - sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm); - j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); - VdbeComment((v, "Jump over SELECT coroutine")); + int rc, iInitCode; + iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); + iSelectLoop = sqlite3VdbeCurrentAddr(v); + iInsertBlock = sqlite3VdbeMakeLabel(v); /* Resolve the expressions in the SELECT statement and execute it. */ - rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0); + rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0); if( rc || pParse->nErr || db->mallocFailed ){ goto insert_cleanup; } - sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */ - sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); /* yield X */ - sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort); - VdbeComment((v, "End of SELECT coroutine")); - sqlite3VdbeJumpHere(v, j1); /* label B: */ - regFromSelect = dest.iMem; + iCleanup = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup); assert( pSelect->pEList ); nColumn = pSelect->pEList->nExpr; - assert( dest.nMem==nColumn ); /* Set useTempTable to TRUE if the result of the SELECT statement - ** should be written into a temporary table (template 4). Set to - ** FALSE if each* row of the SELECT can be written directly into - ** the destination table (template 3). + ** should be written into a temporary table. Set to FALSE if each + ** row of the SELECT can be written directly into the result table. ** ** A temp table must be used if the table being updated is also one ** of the tables being read by the SELECT statement. Also use a ** temp table in the case of row triggers. */ - if( triggers_exist || readsTable(v, addrSelect, iDb, pTab) ){ + if( triggers_exist || readsTable(v, iSelectLoop, iDb, pTab) ){ useTempTable = 1; } if( useTempTable ){ - /* Invoke the coroutine to extract information from the SELECT - ** and add it to a transient table srcTab. The code generated - ** here is from the 4th template: - ** - ** B: open temp table - ** L: yield X - ** if EOF goto M - ** insert row from R..R+n into temp table - ** goto L - ** M: ... + /* Generate the subroutine that SELECT calls to process each row of + ** the result. Store the result in a temporary table */ - int regRec; /* Register to hold packed record */ - int regRowid; /* Register to hold temp table ROWID */ - int addrTop; /* Label "L" */ - int addrIf; /* Address of jump to M */ - srcTab = pParse->nTab++; - regRec = sqlite3GetTempReg(pParse); - regRowid = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn); - addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); - addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); - sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop); - sqlite3VdbeJumpHere(v, addrIf); - sqlite3ReleaseTempReg(pParse, regRec); - sqlite3ReleaseTempReg(pParse, regRowid); + sqlite3VdbeResolveLabel(v, iInsertBlock); + sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); + sqlite3VdbeAddOp(v, OP_NewRowid, srcTab, 0); + sqlite3VdbeAddOp(v, OP_Pull, 1, 0); + sqlite3VdbeAddOp(v, OP_Insert, srcTab, OPFLAG_APPEND); + sqlite3VdbeAddOp(v, OP_Return, 0, 0); + + /* The following code runs first because the GOTO at the very top + ** of the program jumps to it. Create the temporary table, then jump + ** back up and execute the SELECT code above. + */ + sqlite3VdbeJumpHere(v, iInitCode); + sqlite3VdbeAddOp(v, OP_OpenEphemeral, srcTab, 0); + sqlite3VdbeAddOp(v, OP_SetNumColumns, srcTab, nColumn); + sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop); + sqlite3VdbeResolveLabel(v, iCleanup); + }else{ + sqlite3VdbeJumpHere(v, iInitCode); } }else{ /* This is the case if the data for the INSERT is coming from a VALUES @@ -61260,79 +54769,42 @@ SQLITE_PRIVATE void sqlite3Insert( /* Open the temp table for FOR EACH ROW triggers */ if( triggers_exist ){ - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); - sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); + sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0); + sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol); } /* Initialize the count of rows to be inserted */ if( db->flags & SQLITE_CountRows ){ - regRowCount = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + iCntMem = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem); } - /* If this is not a view, open the table and and all indices */ - if( !isView ){ - int nIdx; - int i; - - baseCur = pParse->nTab; - nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite); - aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1)); - if( aRegIdx==0 ){ - goto insert_cleanup; - } - for(i=0; inMem; - } + /* Open tables and indices if there are no row triggers */ + if( !triggers_exist ){ + base = pParse->nTab; + sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite); } - /* This is the top of the main insertion loop */ - if( useTempTable ){ - /* This block codes the top of loop only. The complete loop is the - ** following pseudocode (template 4): - ** - ** rewind temp table - ** C: loop over rows of intermediate table - ** transfer values form intermediate table into
      - ** end loop - ** D: ... - */ - addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); - addrCont = sqlite3VdbeCurrentAddr(v); - }else if( pSelect ){ - /* This block codes the top of loop only. The complete loop is the - ** following pseudocode (template 3): - ** - ** C: yield X - ** if EOF goto D - ** insert the select result into
      from R..R+n - ** goto C - ** D: ... - */ - addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm); - addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof); - } - - /* Allocate registers for holding the rowid of the new row, - ** the content of the new row, and the assemblied row record. + /* If the data source is a temporary table, then we have to create + ** a loop because there might be multiple rows of data. If the data + ** source is a subroutine call from the SELECT statement, then we need + ** to launch the SELECT statement processing. */ - regRecord = ++pParse->nMem; - regRowid = regIns = pParse->nMem+1; - pParse->nMem += pTab->nCol + 1; - if( IsVirtual(pTab) ){ - regRowid++; - pParse->nMem++; + if( useTempTable ){ + iBreak = sqlite3VdbeMakeLabel(v); + sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak); + iCont = sqlite3VdbeCurrentAddr(v); + }else if( pSelect ){ + sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop); + sqlite3VdbeResolveLabel(v, iInsertBlock); + sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); } - regData = regRowid+1; /* Run the BEFORE and INSTEAD OF triggers, if there are any */ endOfLoop = sqlite3VdbeMakeLabel(v); if( triggers_exist & TRIGGER_BEFORE ){ - int regRowid; - int regCols; - int regRec; /* build the NEW.* reference row. Note that if there is an INTEGER ** PRIMARY KEY into which a NULL is being inserted, that NULL will be @@ -61340,19 +54812,17 @@ SQLITE_PRIVATE void sqlite3Insert( ** we do not know what the unique ID will be (because the insert has ** not happened yet) so we substitute a rowid of -1 */ - regRowid = sqlite3GetTempReg(pParse); if( keyColumn<0 ){ - sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); + sqlite3VdbeAddOp(v, OP_Integer, -1, 0); }else if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); + sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); }else{ - int j1; assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); - j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); - sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); - sqlite3VdbeJumpHere(v, j1); - sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr); + sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + sqlite3VdbeAddOp(v, OP_Integer, -1, 0); + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); } /* Cannot have triggers on a virtual table. If it were possible, @@ -61362,7 +54832,6 @@ SQLITE_PRIVATE void sqlite3Insert( /* Create the new column data */ - regCols = sqlite3GetTempRange(pParse, pTab->nCol); for(i=0; inCol; i++){ if( pColumn==0 ){ j = i; @@ -61372,16 +54841,15 @@ SQLITE_PRIVATE void sqlite3Insert( } } if( pColumn && j>=pColumn->nId ){ - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); }else if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); + sqlite3VdbeAddOp(v, OP_Column, srcTab, j); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i); + sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr); } } - regRec = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec); + sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, ** do not attempt any conversions before assembling the record. @@ -61391,18 +54859,23 @@ SQLITE_PRIVATE void sqlite3Insert( if( !isView ){ sqlite3TableAffinityStr(v, pTab); } - sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); - sqlite3ReleaseTempReg(pParse, regRec); - sqlite3ReleaseTempReg(pParse, regRowid); - sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol); + sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); /* Fire BEFORE or INSTEAD OF triggers */ if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, - newIdx, -1, onError, endOfLoop, 0, 0) ){ + newIdx, -1, onError, endOfLoop) ){ goto insert_cleanup; } } + /* If any triggers exists, the opening of tables and indices is deferred + ** until now. + */ + if( triggers_exist && !isView ){ + base = pParse->nTab; + sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite); + } + /* Push the record number for the new entry onto the stack. The ** record number is a randomly generate integer created by NewRowid ** except when the table has an INTEGER PRIMARY KEY column, in which @@ -61410,61 +54883,53 @@ SQLITE_PRIVATE void sqlite3Insert( */ if( !isView ){ if( IsVirtual(pTab) ){ - /* The row that the VUpdate opcode will delete: none */ - sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); + /* The row that the VUpdate opcode will delete: none */ + sqlite3VdbeAddOp(v, OP_Null, 0, 0); } if( keyColumn>=0 ){ if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); + sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); }else if( pSelect ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); + sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1); }else{ VdbeOp *pOp; - sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr); pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1); - if( pOp && pOp->opcode==OP_Null && !IsVirtual(pTab) ){ + if( pOp && pOp->opcode==OP_Null ){ appendFlag = 1; pOp->opcode = OP_NewRowid; - pOp->p1 = baseCur; - pOp->p2 = regRowid; - pOp->p3 = regAutoinc; + pOp->p1 = base; + pOp->p2 = counterMem; } } /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid ** to generate a unique primary key value. */ if( !appendFlag ){ - int j1; - if( !IsVirtual(pTab) ){ - j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); - sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); - sqlite3VdbeJumpHere(v, j1); - }else{ - j1 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); - } - sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); + sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem); + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); } }else if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); }else{ - sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem); appendFlag = 1; } - autoIncStep(pParse, regAutoinc, regRowid); + autoIncStep(pParse, counterMem); /* Push onto the stack, data for all columns of the new entry, beginning ** with the first column. */ nHidden = 0; for(i=0; inCol; i++){ - int iRegStore = regRowid+1+i; if( i==pTab->iPKey ){ /* The value of the INTEGER PRIMARY KEY column is always a NULL. ** Whenever this column is read, the record number will be substituted ** in its place. So will fill this column with a NULL to avoid ** taking up data space with information that will never be used. */ - sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); continue; } if( pColumn==0 ){ @@ -61481,13 +54946,13 @@ SQLITE_PRIVATE void sqlite3Insert( } } if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); }else if( useTempTable ){ - sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); + sqlite3VdbeAddOp(v, OP_Column, srcTab, j); }else if( pSelect ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); + sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1); }else{ - sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); + sqlite3ExprCode(pParse, pList->a[j].pExpr); } } @@ -61496,77 +54961,68 @@ SQLITE_PRIVATE void sqlite3Insert( */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ - sqlite3VtabMakeWritable(pParse, pTab); - sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, - (const char*)pTab->pVtab, P4_VTAB); + pParse->pVirtualLock = pTab; + sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2, + (const char*)pTab->pVtab, P3_VTAB); }else #endif { - sqlite3GenerateConstraintChecks( - pParse, - pTab, - baseCur, - regIns, - aRegIdx, - keyColumn>=0, - 0, - onError, - endOfLoop - ); - sqlite3CompleteInsertion( - pParse, - pTab, - baseCur, - regIns, - aRegIdx, - 0, - 0, - (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1, - appendFlag - ); + sqlite3GenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0, + 0, onError, endOfLoop); + sqlite3CompleteInsertion(pParse, pTab, base, 0,0,0, + (triggers_exist & TRIGGER_AFTER)!=0 ? newIdx : -1, + appendFlag); } } /* Update the count of rows that are inserted */ if( (db->flags & SQLITE_CountRows)!=0 ){ - sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem); } if( triggers_exist ){ + /* Close all tables opened */ + if( !isView ){ + sqlite3VdbeAddOp(v, OP_Close, base, 0); + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ + sqlite3VdbeAddOp(v, OP_Close, idx+base, 0); + } + } + /* Code AFTER triggers */ if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_AFTER, pTab, - newIdx, -1, onError, endOfLoop, 0, 0) ){ + newIdx, -1, onError, endOfLoop) ){ goto insert_cleanup; } } - /* The bottom of the main insertion loop, if the data source - ** is a SELECT statement. + /* The bottom of the loop, if the data source is a SELECT statement */ sqlite3VdbeResolveLabel(v, endOfLoop); if( useTempTable ){ - sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); - sqlite3VdbeJumpHere(v, addrInsTop); - sqlite3VdbeAddOp1(v, OP_Close, srcTab); + sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont); + sqlite3VdbeResolveLabel(v, iBreak); + sqlite3VdbeAddOp(v, OP_Close, srcTab, 0); }else if( pSelect ){ - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont); - sqlite3VdbeJumpHere(v, addrInsTop); + sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); + sqlite3VdbeAddOp(v, OP_Return, 0, 0); + sqlite3VdbeResolveLabel(v, iCleanup); } - if( !IsVirtual(pTab) && !isView ){ + if( !triggers_exist && !IsVirtual(pTab) ){ /* Close all tables opened */ - sqlite3VdbeAddOp1(v, OP_Close, baseCur); + sqlite3VdbeAddOp(v, OP_Close, base, 0); for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ - sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur); + sqlite3VdbeAddOp(v, OP_Close, idx+base, 0); } } /* Update the sqlite_sequence table by storing the content of the - ** counter value in memory regAutoinc back into the sqlite_sequence + ** counter value in memory counterMem back into the sqlite_sequence ** table. */ - autoIncEnd(pParse, iDb, pTab, regAutoinc); + autoIncEnd(pParse, iDb, pTab, counterMem); /* ** Return the number of rows inserted. If this routine is @@ -61574,9 +55030,10 @@ SQLITE_PRIVATE void sqlite3Insert( ** invoke the callback function. */ if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC); } insert_cleanup: @@ -61584,17 +55041,17 @@ insert_cleanup: sqlite3ExprListDelete(pList); sqlite3SelectDelete(pSelect); sqlite3IdListDelete(pColumn); - sqlite3_free(aRegIdx); } /* -** Generate code to do constraint checks prior to an INSERT or an UPDATE. +** Generate code to do a constraint check prior to an INSERT or an UPDATE. ** -** The input is a range of consecutive registers as follows: +** When this routine is called, the stack contains (from bottom to top) +** the following values: ** ** 1. The rowid of the row to be updated before the update. This ** value is omitted unless we are doing an UPDATE that involves a -** change to the record number or writing to a virtual table. +** change to the record number. ** ** 2. The rowid of the row after the update. ** @@ -61604,20 +55061,15 @@ insert_cleanup: ** ** N. The data in the last column of the entry after the update. ** -** The regRowid parameter is the index of the register containing (2). -** ** The old rowid shown as entry (1) above is omitted unless both isUpdate ** and rowidChng are 1. isUpdate is true for UPDATEs and false for -** INSERTs. RowidChng means that the new rowid is explicitly specified by -** the update or insert statement. If rowidChng is false, it means that -** the rowid is computed automatically in an insert or that the rowid value -** is not modified by the update. +** INSERTs and rowidChng is true if the record number is being changed. ** -** The code generated by this routine store new index entries into -** registers identified by aRegIdx[]. No index entry is created for -** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is -** the same as the order of indices on the linked list of indices -** attached to the table. +** The code generated by this routine pushes additional entries onto +** the stack which are the keys for new index entries for the new record. +** The order of index keys is the same as the order of the indices on +** the pTable->pIndex list. A key is only created for index i if +** aIdxUsed!=0 and aIdxUsed[i]!=0. ** ** This routine also generates code to check constraints. NOT NULL, ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, @@ -61659,18 +55111,23 @@ insert_cleanup: ** for the constraint is used. ** ** The calling routine must open a read/write cursor for pTab with -** cursor number "baseCur". All indices of pTab must also have open -** read/write cursors with cursor number baseCur+i for the i-th cursor. +** cursor number "base". All indices of pTab must also have open +** read/write cursors with cursor number base+i for the i-th cursor. ** Except, if there is no possibility of a REPLACE action then -** cursors do not need to be open for indices where aRegIdx[i]==0. +** cursors do not need to be open for indices where aIdxUsed[i]==0. +** +** If the isUpdate flag is true, it means that the "base" cursor is +** initially pointing to an entry that is being updated. The isUpdate +** flag causes extra code to be generated so that the "base" cursor +** is still pointing at the same entry after the routine returns. +** Without the isUpdate flag, the "base" cursor might be moved. */ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ - int baseCur, /* Index of a read/write cursor pointing at pTab */ - int regRowid, /* Index of the range of input registers */ - int *aRegIdx, /* Register used by each index. 0 for unused indices */ - int rowidChng, /* True if the rowid might collide with existing entry */ + int base, /* Index of a read/write cursor pointing at pTab */ + char *aIdxUsed, /* Which indices are used. NULL means all are used */ + int rowidChng, /* True if the record number will change */ int isUpdate, /* True for UPDATE, False for INSERT */ int overrideError, /* Override onError to this if not OE_Default */ int ignoreDest /* Jump to this label on an OE_Ignore resolution */ @@ -61679,19 +55136,18 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( Vdbe *v; int nCol; int onError; - int j1, j2, j3; /* Addresses of jump instructions */ - int regData; /* Register containing first data column */ + int addr; + int extra; int iCur; Index *pIdx; int seenReplace = 0; + int jumpInst1=0, jumpInst2; int hasTwoRowids = (isUpdate && rowidChng); v = sqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ nCol = pTab->nCol; - regData = regRowid + 1; - /* Test all NOT NULL constraints. */ @@ -61709,30 +55165,33 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ onError = OE_Abort; } - j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); + sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1); + addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0); assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail || onError==OE_Ignore || onError==OE_Replace ); switch( onError ){ case OE_Rollback: case OE_Abort: case OE_Fail: { - char *zMsg; - sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); - zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL", - pTab->zName, pTab->aCol[i].zName); - sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); + char *zMsg = 0; + sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError); + sqlite3SetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName, + " may not be NULL", (char*)0); + sqlite3VdbeChangeP3(v, -1, zMsg, P3_DYNAMIC); break; } case OE_Ignore: { - sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); break; } case OE_Replace: { - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); + sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0); break; } } - sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeJumpHere(v, addr); } /* Test all CHECK constraints @@ -61740,13 +55199,17 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( #ifndef SQLITE_OMIT_CHECK if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ int allOk = sqlite3VdbeMakeLabel(v); - pParse->ckBase = regData; - sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); + assert( pParse->ckOffset==0 ); + pParse->ckOffset = nCol; + sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1); + assert( pParse->ckOffset==nCol ); + pParse->ckOffset = 0; onError = overrideError!=OE_Default ? overrideError : OE_Abort; if( onError==OE_Ignore ){ - sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); }else{ - sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); + sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError); } sqlite3VdbeResolveLabel(v, allOk); } @@ -61764,38 +55227,46 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( onError = OE_Abort; } - if( onError!=OE_Replace || pTab->pIndex ){ - if( isUpdate ){ - j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1); + if( isUpdate ){ + sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); + sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); + jumpInst1 = sqlite3VdbeAddOp(v, OP_Eq, 0, 0); + } + sqlite3VdbeAddOp(v, OP_Dup, nCol, 1); + jumpInst2 = sqlite3VdbeAddOp(v, OP_NotExists, base, 0); + switch( onError ){ + default: { + onError = OE_Abort; + /* Fall thru into the next case */ } - j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid); - switch( onError ){ - default: { - onError = OE_Abort; - /* Fall thru into the next case */ - } - case OE_Rollback: - case OE_Abort: - case OE_Fail: { - sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, - "PRIMARY KEY must be unique", P4_STATIC); - break; - } - case OE_Replace: { - sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0); - seenReplace = 1; - break; - } - case OE_Ignore: { - assert( seenReplace==0 ); - sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); - break; - } + case OE_Rollback: + case OE_Abort: + case OE_Fail: { + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, + "PRIMARY KEY must be unique", P3_STATIC); + break; } - sqlite3VdbeJumpHere(v, j3); - if( isUpdate ){ - sqlite3VdbeJumpHere(v, j2); + case OE_Replace: { + sqlite3GenerateRowIndexDelete(v, pTab, base, 0); + if( isUpdate ){ + sqlite3VdbeAddOp(v, OP_Dup, nCol+hasTwoRowids, 1); + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); + } + seenReplace = 1; + break; } + case OE_Ignore: { + assert( seenReplace==0 ); + sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); + break; + } + } + sqlite3VdbeJumpHere(v, jumpInst2); + if( isUpdate ){ + sqlite3VdbeJumpHere(v, jumpInst1); + sqlite3VdbeAddOp(v, OP_Dup, nCol+1, 1); + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); } } @@ -61803,27 +55274,23 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( ** index and making sure that duplicate entries do not already exist. ** Add the new records to the indices as we go. */ + extra = -1; for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){ - int regIdx; - int regR; - - if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ + if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */ + extra++; /* Create a key for accessing the index entry */ - regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); + sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1); for(i=0; inColumn; i++){ int idx = pIdx->aiColumn[i]; if( idx==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1); }else{ - sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); + sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1); } } - sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); + jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0); sqlite3IndexAffinityStr(v, pIdx); - sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1); - sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); /* Find out what action to take in case there is an indexing conflict */ onError = pIdx->onError; @@ -61840,12 +55307,8 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( /* Check to see if the new index entry will be unique */ - j2 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdx, 0, pIdx->nColumn); - regR = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_SCopy, regRowid-hasTwoRowids, regR); - j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0, - regR, SQLITE_INT_TO_PTR(aRegIdx[iCur]), - P4_INT32); + sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1); + jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0); /* Generate code that executes if the new index entry is not unique */ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail @@ -61877,31 +55340,38 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( } sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], pIdx->nColumn>1 ? " are not unique" : " is not unique"); - sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0); + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0); break; } case OE_Ignore: { assert( seenReplace==0 ); - sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); break; } case OE_Replace: { - sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0); + sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0); + if( isUpdate ){ + sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1); + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); + } seenReplace = 1; break; } } - sqlite3VdbeJumpHere(v, j2); - sqlite3VdbeJumpHere(v, j3); - sqlite3ReleaseTempReg(pParse, regR); +#if NULL_DISTINCT_FOR_UNIQUE + sqlite3VdbeJumpHere(v, jumpInst1); +#endif + sqlite3VdbeJumpHere(v, jumpInst2); } } /* ** This routine generates code to finish the INSERT or UPDATE operation ** that was started by a prior call to sqlite3GenerateConstraintChecks. -** A consecutive range of registers starting at regRowid contains the -** rowid and the content to be inserted. +** The stack must contain keys for all active indices followed by data +** and the rowid for the new entry. This routine creates the new +** entries in all indices and in the main table. ** ** The arguments to this routine should be the same as the first six ** arguments to sqlite3GenerateConstraintChecks. @@ -61909,9 +55379,8 @@ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( SQLITE_PRIVATE void sqlite3CompleteInsertion( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ - int baseCur, /* Index of a read/write cursor pointing at pTab */ - int regRowid, /* Range of content */ - int *aRegIdx, /* Register used by each index. 0 for unused indices */ + int base, /* Index of a read/write cursor pointing at pTab */ + char *aIdxUsed, /* Which indices are used. NULL means all are used */ int rowidChng, /* True if the record number will change */ int isUpdate, /* True for UPDATE, False for INSERT */ int newIdx, /* Index of NEW table for triggers. -1 if none */ @@ -61922,25 +55391,22 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion( int nIdx; Index *pIdx; int pik_flags; - int regData; - int regRec; v = sqlite3GetVdbe(pParse); assert( v!=0 ); assert( pTab->pSelect==0 ); /* This table is not a VIEW */ for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} for(i=nIdx-1; i>=0; i--){ - if( aRegIdx[i]==0 ) continue; - sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); + if( aIdxUsed && aIdxUsed[i]==0 ) continue; + sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0); } - regData = regRowid + 1; - regRec = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); + sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); sqlite3TableAffinityStr(v, pTab); - sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol); #ifndef SQLITE_OMIT_TRIGGER if( newIdx>=0 ){ - sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); + sqlite3VdbeAddOp(v, OP_Dup, 1, 0); + sqlite3VdbeAddOp(v, OP_Dup, 1, 0); + sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); } #endif if( pParse->nested ){ @@ -61952,24 +55418,25 @@ SQLITE_PRIVATE void sqlite3CompleteInsertion( if( appendBias ){ pik_flags |= OPFLAG_APPEND; } - sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); + sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags); if( !pParse->nested ){ - sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); + sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC); + } + + if( isUpdate && rowidChng ){ + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); } - sqlite3VdbeChangeP5(v, pik_flags); } /* ** Generate code that will open cursors for a table and for all -** indices of that table. The "baseCur" parameter is the cursor number used +** indices of that table. The "base" parameter is the cursor number used ** for the table. Indices are opened on subsequent cursors. -** -** Return the number of indices on the table. */ -SQLITE_PRIVATE int sqlite3OpenTableAndIndices( +SQLITE_PRIVATE void sqlite3OpenTableAndIndices( Parse *pParse, /* Parsing context */ Table *pTab, /* Table to be opened */ - int baseCur, /* Cursor number assigned to the table */ + int base, /* Cursor number assigned to the table */ int op /* OP_OpenRead or OP_OpenWrite */ ){ int i; @@ -61977,22 +55444,21 @@ SQLITE_PRIVATE int sqlite3OpenTableAndIndices( Index *pIdx; Vdbe *v; - if( IsVirtual(pTab) ) return 0; + if( IsVirtual(pTab) ) return; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); v = sqlite3GetVdbe(pParse); assert( v!=0 ); - sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); + sqlite3OpenTable(pParse, base, iDb, pTab, op); for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); assert( pIdx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, - (char*)pKey, P4_KEYINFO_HANDOFF); - VdbeComment((v, "%s", pIdx->zName)); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + VdbeComment((v, "# %s", pIdx->zName)); + sqlite3VdbeOp3(v, op, i+base, pIdx->tnum, (char*)pKey, P3_KEYINFO_HANDOFF); } - if( pParse->nTab<=baseCur+i ){ - pParse->nTab = baseCur+i; + if( pParse->nTab<=base+i ){ + pParse->nTab = base+i; } - return i-1; } @@ -62050,7 +55516,7 @@ static int xferCompatibleIndex(Index *pDest, Index *pSrc){ return 0; /* Different sort orders */ } if( pSrc->azColl[i]!=pDest->azColl[i] ){ - return 0; /* Different collating sequences */ + return 0; /* Different sort orders */ } } @@ -62108,9 +55574,8 @@ static int xferOptimization( int emptySrcTest; /* Address of test for empty pSrc */ Vdbe *v; /* The VDBE we are building */ KeyInfo *pKey; /* Key information for an index */ - int regAutoinc; /* Memory register used by AUTOINC */ + int counterMem; /* Memory register used by AUTOINC */ int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */ - int regData, regRowid; /* Registers holding data and rowid */ if( pSelect==0 ){ return 0; /* Must be of the form INSERT INTO ... SELECT ... */ @@ -62172,7 +55637,7 @@ static int xferOptimization( ** we have to check the semantics. */ pItem = pSelect->pSrc->a; - pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); + pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase); if( pSrc==0 ){ return 0; /* FROM clause does not contain a real table */ } @@ -62237,7 +55702,7 @@ static int xferOptimization( sqlite3CodeVerifySchema(pParse, iDbSrc); iSrc = pParse->nTab++; iDest = pParse->nTab++; - regAutoinc = autoIncBegin(pParse, iDbDest, pDest); + counterMem = autoIncBegin(pParse, iDbDest, pDest); sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite); if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){ /* If tables do not have an INTEGER PRIMARY KEY and there @@ -62250,65 +55715,64 @@ static int xferOptimization( ** insure that all entries in the union of DEST and SRC will be ** unique. */ - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); - emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); + addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0); + emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); sqlite3VdbeJumpHere(v, addr1); }else{ emptyDestTest = 0; } sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); - emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); - regData = sqlite3GetTempReg(pParse); - regRowid = sqlite3GetTempReg(pParse); + emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0); if( pDest->iPKey>=0 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); - addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid); - sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, - "PRIMARY KEY must be unique", P4_STATIC); + addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0); + sqlite3VdbeAddOp(v, OP_Dup, 0, 0); + addr2 = sqlite3VdbeAddOp(v, OP_NotExists, iDest, 0); + sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, + "PRIMARY KEY must be unique", P3_STATIC); sqlite3VdbeJumpHere(v, addr2); - autoIncStep(pParse, regAutoinc, regRowid); + autoIncStep(pParse, counterMem); }else if( pDest->pIndex==0 ){ - addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); + addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0); }else{ - addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); + addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0); assert( pDest->autoInc==0 ); } - sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData); - sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid); - sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND); - sqlite3VdbeChangeP4(v, -1, pDest->zName, 0); - sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); - autoIncEnd(pParse, iDbDest, pDest, regAutoinc); + sqlite3VdbeAddOp(v, OP_RowData, iSrc, 0); + sqlite3VdbeOp3(v, OP_Insert, iDest, + OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND, + pDest->zName, 0); + sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1); + autoIncEnd(pParse, iDbDest, pDest, counterMem); for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } assert( pSrcIdx ); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + sqlite3VdbeAddOp(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp(v, OP_Close, iDest, 0); + sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0); pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); - sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, - (char*)pKey, P4_KEYINFO_HANDOFF); - VdbeComment((v, "%s", pSrcIdx->zName)); + VdbeComment((v, "# %s", pSrcIdx->zName)); + sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, + (char*)pKey, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0); pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest, - (char*)pKey, P4_KEYINFO_HANDOFF); - VdbeComment((v, "%s", pDestIdx->zName)); - addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData); - sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1); - sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); + VdbeComment((v, "# %s", pDestIdx->zName)); + sqlite3VdbeOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, + (char*)pKey, P3_KEYINFO_HANDOFF); + addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0); + sqlite3VdbeAddOp(v, OP_RowKey, iSrc, 0); + sqlite3VdbeAddOp(v, OP_IdxInsert, iDest, 1); + sqlite3VdbeAddOp(v, OP_Next, iSrc, addr1+1); sqlite3VdbeJumpHere(v, addr1); } sqlite3VdbeJumpHere(v, emptySrcTest); - sqlite3ReleaseTempReg(pParse, regRowid); - sqlite3ReleaseTempReg(pParse, regData); - sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + sqlite3VdbeAddOp(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp(v, OP_Close, iDest, 0); if( emptyDestTest ){ - sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); + sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0); sqlite3VdbeJumpHere(v, emptyDestTest); - sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); + sqlite3VdbeAddOp(v, OP_Close, iDest, 0); return 0; }else{ return 1; @@ -62316,11 +55780,6 @@ static int xferOptimization( } #endif /* SQLITE_OMIT_XFER_OPT */ -/* Make sure "isView" gets undefined in case this file becomes part of -** the amalgamation - so that subsequent files do not see isView as a -** macro. */ -#undef isView - /************** End of insert.c **********************************************/ /************** Begin file legacy.c ******************************************/ /* @@ -62339,7 +55798,7 @@ static int xferOptimization( ** other files are for internal use by SQLite and should not be ** accessed by users of the library. ** -** $Id: legacy.c,v 1.27 2008/06/15 02:51:47 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ @@ -62368,10 +55827,9 @@ SQLITE_API int sqlite3_exec( int nRetry = 0; int nCallback; - if( zSql==0 ) zSql = ""; + if( zSql==0 ) return SQLITE_OK; sqlite3_mutex_enter(db->mutex); - sqlite3Error(db, SQLITE_OK, 0); while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){ int nCol; char **azVals = 0; @@ -62389,7 +55847,12 @@ SQLITE_API int sqlite3_exec( } nCallback = 0; + nCol = sqlite3_column_count(pStmt); + azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char *) + 1); + if( azCols==0 ){ + goto exec_out; + } while( 1 ){ int i; @@ -62399,18 +55862,8 @@ SQLITE_API int sqlite3_exec( if( xCallback && (SQLITE_ROW==rc || (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){ if( 0==nCallback ){ - if( azCols==0 ){ - azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1); - if( azCols==0 ){ - goto exec_out; - } - } for(i=0; imallocFailed = 1; - goto exec_out; - } } nCallback++; } @@ -62418,17 +55871,10 @@ SQLITE_API int sqlite3_exec( azVals = &azCols[nCol]; for(i=0; imallocFailed = 1; - goto exec_out; - } } } if( xCallback(pArg, nCol, azVals, azCols) ){ rc = SQLITE_ABORT; - sqlite3_finalize(pStmt); - pStmt = 0; - sqlite3Error(db, SQLITE_ABORT, 0); goto exec_out; } } @@ -62456,7 +55902,7 @@ exec_out: rc = sqlite3ApiExit(db, rc); if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){ int nErrMsg = 1 + strlen(sqlite3_errmsg(db)); - *pzErrMsg = sqlite3Malloc(nErrMsg); + *pzErrMsg = sqlite3_malloc(nErrMsg); if( *pzErrMsg ){ memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg); } @@ -62484,13 +55930,10 @@ exec_out: ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. -** -** $Id: loadext.c,v 1.51 2008/07/08 14:17:35 danielk1977 Exp $ */ +#ifndef SQLITE_OMIT_LOAD_EXTENSION -#ifndef SQLITE_CORE - #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ -#endif +#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ /************** Include sqlite3ext.h in the middle of loadext.c **************/ /************** Begin file sqlite3ext.h **************************************/ /* @@ -62510,7 +55953,7 @@ exec_out: ** as extensions by SQLite should #include this file instead of ** sqlite3.h. ** -** @(#) $Id: sqlite3ext.h,v 1.24 2008/06/30 15:09:29 danielk1977 Exp $ +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef _SQLITE3EXT_H_ #define _SQLITE3EXT_H_ @@ -62518,13 +55961,13 @@ exec_out: typedef struct sqlite3_api_routines sqlite3_api_routines; /* -** The following structure holds pointers to all of the SQLite API +** The following structure hold pointers to all of the SQLite API ** routines. ** ** WARNING: In order to maintain backwards compatibility, add new ** interfaces to the end of this structure only. If you insert new ** interfaces in the middle of this structure, then older different -** versions of SQLite will not be able to load each others' shared +** versions of SQLite will not be able to load each others shared ** libraries! */ struct sqlite3_api_routines { @@ -62572,7 +56015,7 @@ struct sqlite3_api_routines { int (*complete)(const char*sql); int (*complete16)(const void*sql); int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*)); - int (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*)); + int (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*)); int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); @@ -62676,17 +56119,6 @@ struct sqlite3_api_routines { sqlite3_vfs *(*vfs_find)(const char*); int (*vfs_register)(sqlite3_vfs*,int); int (*vfs_unregister)(sqlite3_vfs*); - int (*xthreadsafe)(void); - void (*result_zeroblob)(sqlite3_context*,int); - void (*result_error_code)(sqlite3_context*,int); - int (*test_control)(int, ...); - void (*randomness)(int,void*); - sqlite3 *(*context_db_handle)(sqlite3_context*); - int (*extended_result_codes)(sqlite3*,int); - int (*limit)(sqlite3*,int,int); - sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*); - const char *(*sql)(sqlite3_stmt*); - int (*status)(int,int*,int*,int); }; /* @@ -62847,20 +56279,9 @@ struct sqlite3_api_routines { #define sqlite3_vfs_find sqlite3_api->vfs_find #define sqlite3_vfs_register sqlite3_api->vfs_register #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister -#define sqlite3_threadsafe sqlite3_api->xthreadsafe -#define sqlite3_result_zeroblob sqlite3_api->result_zeroblob -#define sqlite3_result_error_code sqlite3_api->result_error_code -#define sqlite3_test_control sqlite3_api->test_control -#define sqlite3_randomness sqlite3_api->randomness -#define sqlite3_context_db_handle sqlite3_api->context_db_handle -#define sqlite3_extended_result_codes sqlite3_api->extended_result_codes -#define sqlite3_limit sqlite3_api->limit -#define sqlite3_next_stmt sqlite3_api->next_stmt -#define sqlite3_sql sqlite3_api->sql -#define sqlite3_status sqlite3_api->status #endif /* SQLITE_CORE */ -#define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api = 0; +#define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api; #define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v; #endif /* _SQLITE3EXT_H_ */ @@ -62868,8 +56289,6 @@ struct sqlite3_api_routines { /************** End of sqlite3ext.h ******************************************/ /************** Continuing where we left off in loadext.c ********************/ -#ifndef SQLITE_OMIT_LOAD_EXTENSION - /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer @@ -62967,7 +56386,7 @@ struct sqlite3_api_routines { ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ -static const sqlite3_api_routines sqlite3Apis = { +SQLITE_API const sqlite3_api_routines sqlite3_apis = { sqlite3_aggregate_context, sqlite3_aggregate_count, sqlite3_bind_blob, @@ -63140,25 +56559,6 @@ static const sqlite3_api_routines sqlite3Apis = { sqlite3_vfs_find, sqlite3_vfs_register, sqlite3_vfs_unregister, - - /* - ** Added for 3.5.8 - */ - sqlite3_threadsafe, - sqlite3_result_zeroblob, - sqlite3_result_error_code, - sqlite3_test_control, - sqlite3_randomness, - sqlite3_context_db_handle, - - /* - ** Added for 3.6.0 - */ - sqlite3_extended_result_codes, - sqlite3_limit, - sqlite3_next_stmt, - sqlite3_sql, - sqlite3_status, }; /* @@ -63227,7 +56627,7 @@ static int sqlite3LoadExtension( sqlite3OsDlClose(pVfs, handle); } return SQLITE_ERROR; - }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){ + }else if( xInit(db, &zErrmsg, &sqlite3_apis) ){ if( pzErrMsg ){ *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); } @@ -63292,19 +56692,6 @@ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){ return SQLITE_OK; } -#endif /* SQLITE_OMIT_LOAD_EXTENSION */ - -/* -** The auto-extension code added regardless of whether or not extension -** loading is supported. We need a dummy sqlite3Apis pointer for that -** code if regular extension loading is not available. This is that -** dummy pointer. -*/ -#ifdef SQLITE_OMIT_LOAD_EXTENSION -static const sqlite3_api_routines sqlite3Apis = { 0 }; -#endif - - /* ** The following object holds the list of automatically loaded ** extensions. @@ -63323,57 +56710,40 @@ static struct { ** loaded by every new database connection. */ SQLITE_API int sqlite3_auto_extension(void *xInit){ + int i; int rc = SQLITE_OK; -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ){ - return rc; - }else -#endif - { - int i; -#ifndef SQLITE_MUTEX_NOOP - sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); -#endif - sqlite3_mutex_enter(mutex); - for(i=0; i=autoext.nExt ){ xInit = 0; @@ -63403,7 +56771,7 @@ SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){ autoext.aExt[i]; } sqlite3_mutex_leave(mutex); - if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){ + if( xInit && xInit(db, &zErrmsg, &sqlite3_apis) ){ sqlite3Error(db, SQLITE_ERROR, "automatic extension loading failed: %s", zErrmsg); go = 0; @@ -63414,6 +56782,8 @@ SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){ return rc; } +#endif /* SQLITE_OMIT_LOAD_EXTENSION */ + /************** End of loadext.c *********************************************/ /************** Begin file pragma.c ******************************************/ /* @@ -63429,7 +56799,7 @@ SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){ ************************************************************************* ** This file contains code used to implement the PRAGMA command. ** -** $Id: pragma.c,v 1.182 2008/07/08 07:35:52 danielk1977 Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* Ignore this whole file if pragmas are disabled @@ -63527,7 +56897,7 @@ static int getTempStore(const char *z){ static int invalidateTempStorage(Parse *pParse){ sqlite3 *db = pParse->db; if( db->aDb[1].pBt!=0 ){ - if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){ + if( !db->autoCommit ){ sqlite3ErrorMsg(pParse, "temporary storage cannot be changed " "from within a transaction"); return SQLITE_ERROR; @@ -63543,7 +56913,7 @@ static int invalidateTempStorage(Parse *pParse){ #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** If the TEMP database is open, close it and mark the database schema -** as needing reloading. This must be done when using the SQLITE_TEMP_STORE +** as needing reloading. This must be done when using the TEMP_STORE ** or DEFAULT_TEMP_STORE pragmas. */ static int changeTempStorage(Parse *pParse, const char *zStorageType){ @@ -63563,13 +56933,12 @@ static int changeTempStorage(Parse *pParse, const char *zStorageType){ */ static void returnSingleInt(Parse *pParse, const char *zLabel, int value){ Vdbe *v = sqlite3GetVdbe(pParse); - int mem = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, value, mem); + sqlite3VdbeAddOp(v, OP_Integer, value, 0); if( pParse->explain==0 ){ sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P3_STATIC); } - sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); } #ifndef SQLITE_OMIT_FLAG_PRAGMAS @@ -63626,7 +56995,7 @@ static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){ ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. */ - sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); + sqlite3VdbeAddOp(v, OP_Expire, 0, 0); } } @@ -63666,9 +57035,8 @@ SQLITE_PRIVATE void sqlite3Pragma( int iDb; /* Database index for */ sqlite3 *db = pParse->db; Db *pDb; - Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db); + Vdbe *v = sqlite3GetVdbe(pParse); if( v==0 ) return; - pParse->nMem = 2; /* Interpret the [database.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. */ @@ -63715,21 +57083,20 @@ SQLITE_PRIVATE void sqlite3Pragma( */ if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){ static const VdbeOpList getCacheSize[] = { - { OP_ReadCookie, 0, 1, 2}, /* 0 */ - { OP_IfPos, 1, 6, 0}, - { OP_Integer, 0, 2, 0}, - { OP_Subtract, 1, 2, 1}, - { OP_IfPos, 1, 6, 0}, - { OP_Integer, 0, 1, 0}, /* 5 */ - { OP_ResultRow, 1, 1, 0}, + { OP_ReadCookie, 0, 2, 0}, /* 0 */ + { OP_AbsValue, 0, 0, 0}, + { OP_Dup, 0, 0, 0}, + { OP_Integer, 0, 0, 0}, + { OP_Ne, 0, 6, 0}, + { OP_Integer, 0, 0, 0}, /* 5 */ + { OP_Callback, 1, 0, 0}, }; int addr; if( sqlite3ReadSchema(pParse) ) goto pragma_out; sqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P4_STATIC); - pParse->nMem += 2; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P3_STATIC); addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize); sqlite3VdbeChangeP1(v, addr, iDb); sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE); @@ -63737,12 +57104,12 @@ SQLITE_PRIVATE void sqlite3Pragma( int size = atoi(zRight); if( size<0 ) size = -size; sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3VdbeAddOp2(v, OP_Integer, size, 1); - sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, 2); - addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0); - sqlite3VdbeAddOp2(v, OP_Integer, -size, 1); - sqlite3VdbeJumpHere(v, addr); - sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 2, 1); + sqlite3VdbeAddOp(v, OP_Integer, size, 0); + sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 2); + addr = sqlite3VdbeAddOp(v, OP_Integer, 0, 0); + sqlite3VdbeAddOp(v, OP_Ge, 0, addr+3); + sqlite3VdbeAddOp(v, OP_Negative, 0, 0); + sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 2); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } @@ -63766,8 +57133,7 @@ SQLITE_PRIVATE void sqlite3Pragma( /* Malloc may fail when setting the page-size, as there is an internal ** buffer that the pager module resizes using sqlite3_realloc(). */ - db->nextPagesize = atoi(zRight); - if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1) ){ + if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, atoi(zRight), -1) ){ db->mallocFailed = 1; } } @@ -63794,24 +57160,6 @@ SQLITE_PRIVATE void sqlite3Pragma( returnSingleInt(pParse, "max_page_count", newMax); }else - /* - ** PRAGMA [database.]page_count - ** - ** Return the number of pages in the specified database. - */ - if( sqlite3StrICmp(zLeft,"page_count")==0 ){ - Vdbe *v; - int iReg; - v = sqlite3GetVdbe(pParse); - if( !v || sqlite3ReadSchema(pParse) ) goto pragma_out; - sqlite3CodeVerifySchema(pParse, iDb); - iReg = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); - sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", P4_STATIC); - }else - /* ** PRAGMA [database.]locking_mode ** PRAGMA [database.]locking_mode = (normal|exclusive) @@ -63854,88 +57202,10 @@ SQLITE_PRIVATE void sqlite3Pragma( zRet = "exclusive"; } sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P4_STATIC); - sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P3_STATIC); + sqlite3VdbeOp3(v, OP_String8, 0, 0, zRet, 0); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); }else - - /* - ** PRAGMA [database.]journal_mode - ** PRAGMA [database.]journal_mode = (delete|persist|off) - */ - if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){ - int eMode; - static const char *azModeName[] = {"delete", "persist", "off"}; - - if( zRight==0 ){ - eMode = PAGER_JOURNALMODE_QUERY; - }else{ - int n = strlen(zRight); - eMode = 2; - while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){ - eMode--; - } - } - if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){ - /* Simple "PRAGMA journal_mode;" statement. This is a query for - ** the current default journal mode (which may be different to - ** the journal-mode of the main database). - */ - eMode = db->dfltJournalMode; - }else{ - Pager *pPager; - if( pId2->n==0 ){ - /* This indicates that no database name was specified as part - ** of the PRAGMA command. In this case the journal-mode must be - ** set on all attached databases, as well as the main db file. - ** - ** Also, the sqlite3.dfltJournalMode variable is set so that - ** any subsequently attached databases also use the specified - ** journal mode. - */ - int ii; - assert(pDb==&db->aDb[0]); - for(ii=1; iinDb; ii++){ - if( db->aDb[ii].pBt ){ - pPager = sqlite3BtreePager(db->aDb[ii].pBt); - sqlite3PagerJournalMode(pPager, eMode); - } - } - db->dfltJournalMode = eMode; - } - pPager = sqlite3BtreePager(pDb->pBt); - eMode = sqlite3PagerJournalMode(pPager, eMode); - } - assert( eMode==PAGER_JOURNALMODE_DELETE - || eMode==PAGER_JOURNALMODE_PERSIST - || eMode==PAGER_JOURNALMODE_OFF ); - sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", P4_STATIC); - sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, - azModeName[eMode], P4_STATIC); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); - }else - - /* - ** PRAGMA [database.]journal_size_limit - ** PRAGMA [database.]journal_size_limit=N - ** - ** Get or set the (boolean) value of the database 'auto-vacuum' parameter. - */ - if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){ - Pager *pPager = sqlite3BtreePager(pDb->pBt); - i64 iLimit = -2; - if( zRight ){ - int iLimit32 = atoi(zRight); - if( iLimit32<-1 ){ - iLimit32 = -1; - } - iLimit = iLimit32; - } - iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); - returnSingleInt(pParse, "journal_size_limit", (int)iLimit); - }else - #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ /* @@ -63972,11 +57242,11 @@ SQLITE_PRIVATE void sqlite3Pragma( */ static const VdbeOpList setMeta6[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ - { OP_ReadCookie, 0, 1, 3}, /* 1 */ - { OP_If, 1, 0, 0}, /* 2 */ + { OP_ReadCookie, 0, 3, 0}, /* 1 */ + { OP_If, 0, 0, 0}, /* 2 */ { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ - { OP_Integer, 0, 1, 0}, /* 4 */ - { OP_SetCookie, 0, 6, 1}, /* 5 */ + { OP_Integer, 0, 0, 0}, /* 4 */ + { OP_SetCookie, 0, 6, 0}, /* 5 */ }; int iAddr; iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6); @@ -64007,11 +57277,11 @@ SQLITE_PRIVATE void sqlite3Pragma( iLimit = 0x7fffffff; } sqlite3BeginWriteOperation(pParse, 0, iDb); - sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); - addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); - sqlite3VdbeAddOp1(v, OP_ResultRow, 1); - sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); - sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); + sqlite3VdbeAddOp(v, OP_MemInt, iLimit, 0); + addr = sqlite3VdbeAddOp(v, OP_IncrVacuum, iDb, 0); + sqlite3VdbeAddOp(v, OP_Callback, 0, 0); + sqlite3VdbeAddOp(v, OP_MemIncr, -1, 0); + sqlite3VdbeAddOp(v, OP_IfMemPos, 0, addr); sqlite3VdbeJumpHere(v, addr); }else #endif @@ -64077,22 +57347,20 @@ SQLITE_PRIVATE void sqlite3Pragma( if( sqlite3_temp_directory ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, - "temp_store_directory", P4_STATIC); - sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + "temp_store_directory", P3_STATIC); + sqlite3VdbeOp3(v, OP_String8, 0, 0, sqlite3_temp_directory, 0); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); } }else{ - if( zRight[0] ){ - int res; - sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); - if( res==0 ){ - sqlite3ErrorMsg(pParse, "not a writable directory"); - goto pragma_out; - } + if( zRight[0] + && !sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE) + ){ + sqlite3ErrorMsg(pParse, "not a writable directory"); + goto pragma_out; } - if( SQLITE_TEMP_STORE==0 - || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) - || (SQLITE_TEMP_STORE==2 && db->temp_store==1) + if( TEMP_STORE==0 + || (TEMP_STORE==1 && db->temp_store<=1) + || (TEMP_STORE==2 && db->temp_store==1) ){ invalidateTempStorage(pParse); } @@ -64159,13 +57427,12 @@ SQLITE_PRIVATE void sqlite3Pragma( int nHidden = 0; Column *pCol; sqlite3VdbeSetNumCols(v, 6); - pParse->nMem = 6; - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P4_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P4_STATIC); - sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P4_STATIC); - sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P4_STATIC); - sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P3_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P3_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P3_STATIC); + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P3_STATIC); + sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P3_STATIC); sqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; inCol; i++, pCol++){ const Token *pDflt; @@ -64173,18 +57440,18 @@ SQLITE_PRIVATE void sqlite3Pragma( nHidden++; continue; } - sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1); - sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3VdbeAddOp(v, OP_Integer, i-nHidden, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pCol->zName, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pCol->zType ? pCol->zType : "", 0); - sqlite3VdbeAddOp2(v, OP_Integer, pCol->notNull, 4); + sqlite3VdbeAddOp(v, OP_Integer, pCol->notNull, 0); if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){ - sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n); + sqlite3VdbeOp3(v, OP_String8, 0, 0, (char*)pDflt->z, pDflt->n); }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, 5); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); } - sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6); + sqlite3VdbeAddOp(v, OP_Integer, pCol->isPrimKey, 0); + sqlite3VdbeAddOp(v, OP_Callback, 6, 0); } } }else @@ -64198,17 +57465,16 @@ SQLITE_PRIVATE void sqlite3Pragma( int i; pTab = pIdx->pTable; sqlite3VdbeSetNumCols(v, 3); - pParse->nMem = 3; - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P4_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P4_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P3_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P3_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P3_STATIC); for(i=0; inColumn; i++){ int cnum = pIdx->aiColumn[i]; - sqlite3VdbeAddOp2(v, OP_Integer, i, 1); - sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2); + sqlite3VdbeAddOp(v, OP_Integer, i, 0); + sqlite3VdbeAddOp(v, OP_Integer, cnum, 0); assert( pTab->nCol>cnum ); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->aCol[cnum].zName, 0); + sqlite3VdbeAddOp(v, OP_Callback, 3, 0); } } }else @@ -64224,15 +57490,14 @@ SQLITE_PRIVATE void sqlite3Pragma( if( pIdx ){ int i = 0; sqlite3VdbeSetNumCols(v, 3); - pParse->nMem = 3; - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P3_STATIC); while(pIdx){ - sqlite3VdbeAddOp2(v, OP_Integer, i, 1); - sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0); - sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + sqlite3VdbeAddOp(v, OP_Integer, i, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0); + sqlite3VdbeAddOp(v, OP_Integer, pIdx->onError!=OE_None, 0); + sqlite3VdbeAddOp(v, OP_Callback, 3, 0); ++i; pIdx = pIdx->pNext; } @@ -64244,18 +57509,17 @@ SQLITE_PRIVATE void sqlite3Pragma( int i; if( sqlite3ReadSchema(pParse) ) goto pragma_out; sqlite3VdbeSetNumCols(v, 3); - pParse->nMem = 3; - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P3_STATIC); for(i=0; inDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zName!=0 ); - sqlite3VdbeAddOp2(v, OP_Integer, i, 1); - sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3VdbeAddOp(v, OP_Integer, i, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, sqlite3BtreeGetFilename(db->aDb[i].pBt), 0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); + sqlite3VdbeAddOp(v, OP_Callback, 3, 0); } }else @@ -64263,14 +57527,13 @@ SQLITE_PRIVATE void sqlite3Pragma( int i = 0; HashElem *p; sqlite3VdbeSetNumCols(v, 2); - pParse->nMem = 2; - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC); for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); - sqlite3VdbeAddOp2(v, OP_Integer, i++, 1); - sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + sqlite3VdbeAddOp(v, OP_Integer, i++, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pColl->zName, 0); + sqlite3VdbeAddOp(v, OP_Callback, 2, 0); } }else #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ @@ -64287,23 +57550,22 @@ SQLITE_PRIVATE void sqlite3Pragma( if( pFK ){ int i = 0; sqlite3VdbeSetNumCols(v, 5); - pParse->nMem = 5; - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P4_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P4_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P4_STATIC); - sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P4_STATIC); - sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", P3_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", P3_STATIC); + sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", P3_STATIC); + sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", P3_STATIC); + sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", P3_STATIC); while(pFK){ int j; for(j=0; jnCol; j++){ char *zCol = pFK->aCol[j].zCol; - sqlite3VdbeAddOp2(v, OP_Integer, i, 1); - sqlite3VdbeAddOp2(v, OP_Integer, j, 2); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0); - sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, - pTab->aCol[pFK->aCol[j].iFrom].zName, 0); - sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); + sqlite3VdbeAddOp(v, OP_Integer, i, 0); + sqlite3VdbeAddOp(v, OP_Integer, j, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, pFK->zTo, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, + pTab->aCol[pFK->aCol[j].iFrom].zName, 0); + sqlite3VdbeOp3(v, zCol ? OP_String8 : OP_Null, 0, 0, zCol, 0); + sqlite3VdbeAddOp(v, OP_Callback, 5, 0); } ++i; pFK = pFK->pNextFrom; @@ -64353,19 +57615,19 @@ SQLITE_PRIVATE void sqlite3Pragma( ** error message */ static const VdbeOpList endCode[] = { - { OP_AddImm, 1, 0, 0}, /* 0 */ - { OP_IfNeg, 1, 0, 0}, /* 1 */ - { OP_String8, 0, 3, 0}, /* 2 */ - { OP_ResultRow, 3, 1, 0}, + { OP_MemLoad, 0, 0, 0}, + { OP_Integer, 0, 0, 0}, + { OP_Ne, 0, 0, 0}, /* 2 */ + { OP_String8, 0, 0, "ok"}, + { OP_Callback, 1, 0, 0}, }; int isQuick = (zLeft[0]=='q'); /* Initialize the VDBE program */ if( sqlite3ReadSchema(pParse) ) goto pragma_out; - pParse->nMem = 6; sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P3_STATIC); /* Set the maximum error count */ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; @@ -64375,7 +57637,7 @@ SQLITE_PRIVATE void sqlite3Pragma( mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } - sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */ + sqlite3VdbeAddOp(v, OP_MemInt, mxErr, 0); /* Do an integrity check on each database file */ for(i=0; inDb; i++){ @@ -64386,43 +57648,32 @@ SQLITE_PRIVATE void sqlite3Pragma( if( OMIT_TEMPDB && i==1 ) continue; sqlite3CodeVerifySchema(pParse, i); - addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */ - sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0); + sqlite3VdbeAddOp(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); /* Do an integrity check of the B-Tree - ** - ** Begin by filling registers 2, 3, ... with the root pages numbers - ** for all tables and indices in the database. */ pTbls = &db->aDb[i].pSchema->tblHash; for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; - sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt); + sqlite3VdbeAddOp(v, OP_Integer, pTab->tnum, 0); cnt++; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt); + sqlite3VdbeAddOp(v, OP_Integer, pIdx->tnum, 0); cnt++; } } if( cnt==0 ) continue; - - /* Make sure sufficient number of registers have been allocated */ - if( pParse->nMem < cnt+4 ){ - pParse->nMem = cnt+4; - } - - /* Do the b-tree integrity checks */ - sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1); - sqlite3VdbeChangeP5(v, i); - addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); - sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, + sqlite3VdbeAddOp(v, OP_IntegrityCk, 0, i); + addr = sqlite3VdbeAddOp(v, OP_IsNull, -1, 0); + sqlite3VdbeOp3(v, OP_String8, 0, 0, sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName), - P4_DYNAMIC); - sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1); - sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2); - sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1); + P3_DYNAMIC); + sqlite3VdbeAddOp(v, OP_Pull, 1, 0); + sqlite3VdbeAddOp(v, OP_Concat, 0, 0); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); sqlite3VdbeJumpHere(v, addr); /* Make sure all the indices are constructed correctly. @@ -64433,72 +57684,64 @@ SQLITE_PRIVATE void sqlite3Pragma( int loopTop; if( pTab->pIndex==0 ) continue; - addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ - sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0); + sqlite3VdbeAddOp(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead); - sqlite3VdbeAddOp2(v, OP_Integer, 0, 2); /* reg(2) will count entries */ - loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0); - sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1); /* increment entry count */ + sqlite3VdbeAddOp(v, OP_MemInt, 0, 1); + loopTop = sqlite3VdbeAddOp(v, OP_Rewind, 1, 0); + sqlite3VdbeAddOp(v, OP_MemIncr, 1, 1); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int jmp2; static const VdbeOpList idxErr[] = { - { OP_AddImm, 1, -1, 0}, - { OP_String8, 0, 3, 0}, /* 1 */ - { OP_Rowid, 1, 4, 0}, - { OP_String8, 0, 5, 0}, /* 3 */ - { OP_String8, 0, 6, 0}, /* 4 */ - { OP_Concat, 4, 3, 3}, - { OP_Concat, 5, 3, 3}, - { OP_Concat, 6, 3, 3}, - { OP_ResultRow, 3, 1, 0}, - { OP_IfPos, 1, 0, 0}, /* 9 */ - { OP_Halt, 0, 0, 0}, + { OP_MemIncr, -1, 0, 0}, + { OP_String8, 0, 0, "rowid "}, + { OP_Rowid, 1, 0, 0}, + { OP_String8, 0, 0, " missing from index "}, + { OP_String8, 0, 0, 0}, /* 4 */ + { OP_Concat, 2, 0, 0}, + { OP_Callback, 1, 0, 0}, }; - sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 1); - jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3); + sqlite3GenerateIndexKey(v, pIdx, 1); + jmp2 = sqlite3VdbeAddOp(v, OP_Found, j+2, 0); addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr); - sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC); - sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC); - sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC); - sqlite3VdbeJumpHere(v, addr+9); + sqlite3VdbeChangeP3(v, addr+4, pIdx->zName, P3_STATIC); sqlite3VdbeJumpHere(v, jmp2); } - sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1); + sqlite3VdbeAddOp(v, OP_Next, 1, loopTop+1); sqlite3VdbeJumpHere(v, loopTop); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ static const VdbeOpList cntIdx[] = { - { OP_Integer, 0, 3, 0}, + { OP_MemInt, 0, 2, 0}, { OP_Rewind, 0, 0, 0}, /* 1 */ - { OP_AddImm, 3, 1, 0}, + { OP_MemIncr, 1, 2, 0}, { OP_Next, 0, 0, 0}, /* 3 */ - { OP_Eq, 2, 0, 3}, /* 4 */ - { OP_AddImm, 1, -1, 0}, - { OP_String8, 0, 2, 0}, /* 6 */ - { OP_String8, 0, 3, 0}, /* 7 */ - { OP_Concat, 3, 2, 2}, - { OP_ResultRow, 2, 1, 0}, + { OP_MemLoad, 1, 0, 0}, + { OP_MemLoad, 2, 0, 0}, + { OP_Eq, 0, 0, 0}, /* 6 */ + { OP_MemIncr, -1, 0, 0}, + { OP_String8, 0, 0, "wrong # of entries in index "}, + { OP_String8, 0, 0, 0}, /* 9 */ + { OP_Concat, 0, 0, 0}, + { OP_Callback, 1, 0, 0}, }; if( pIdx->tnum==0 ) continue; - addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); - sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0); + sqlite3VdbeAddOp(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx); sqlite3VdbeChangeP1(v, addr+1, j+2); sqlite3VdbeChangeP2(v, addr+1, addr+4); sqlite3VdbeChangeP1(v, addr+3, j+2); sqlite3VdbeChangeP2(v, addr+3, addr+2); - sqlite3VdbeJumpHere(v, addr+4); - sqlite3VdbeChangeP4(v, addr+6, - "wrong # of entries in index ", P4_STATIC); - sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC); + sqlite3VdbeJumpHere(v, addr+6); + sqlite3VdbeChangeP3(v, addr+9, pIdx->zName, P3_STATIC); } } } addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode); - sqlite3VdbeChangeP2(v, addr, -mxErr); - sqlite3VdbeJumpHere(v, addr+1); - sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC); + sqlite3VdbeChangeP1(v, addr+1, mxErr); + sqlite3VdbeJumpHere(v, addr+2); }else #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ @@ -64544,15 +57787,15 @@ SQLITE_PRIVATE void sqlite3Pragma( if( !zRight ){ /* "PRAGMA encoding" */ if( sqlite3ReadSchema(pParse) ) goto pragma_out; sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P4_STATIC); - sqlite3VdbeAddOp2(v, OP_String8, 0, 1); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P3_STATIC); + sqlite3VdbeAddOp(v, OP_String8, 0, 0); for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ if( pEnc->enc==ENC(pParse->db) ){ - sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC); + sqlite3VdbeChangeP3(v, -1, pEnc->zName, P3_STATIC); break; } } - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); }else{ /* "PRAGMA encoding = XXX" */ /* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value @@ -64628,8 +57871,8 @@ SQLITE_PRIVATE void sqlite3Pragma( /* Write the specified cookie value */ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ - { OP_Integer, 0, 1, 0}, /* 1 */ - { OP_SetCookie, 0, 0, 1}, /* 2 */ + { OP_Integer, 0, 0, 0}, /* 1 */ + { OP_SetCookie, 0, 0, 0}, /* 2 */ }; int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie); sqlite3VdbeChangeP1(v, addr, iDb); @@ -64639,14 +57882,14 @@ SQLITE_PRIVATE void sqlite3Pragma( }else{ /* Read the specified cookie value */ static const VdbeOpList readCookie[] = { - { OP_ReadCookie, 0, 1, 0}, /* 0 */ - { OP_ResultRow, 1, 1, 0} + { OP_ReadCookie, 0, 0, 0}, /* 0 */ + { OP_Callback, 1, 0, 0} }; int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie); sqlite3VdbeChangeP1(v, addr, iDb); - sqlite3VdbeChangeP3(v, addr, iCookie); + sqlite3VdbeChangeP2(v, addr, iCookie); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P4_TRANSIENT); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P3_TRANSIENT); } }else #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ @@ -64662,25 +57905,24 @@ SQLITE_PRIVATE void sqlite3Pragma( int i; Vdbe *v = sqlite3GetVdbe(pParse); sqlite3VdbeSetNumCols(v, 2); - pParse->nMem = 2; - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P4_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P3_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P3_STATIC); for(i=0; inDb; i++){ Btree *pBt; Pager *pPager; const char *zState = "unknown"; int j; if( db->aDb[i].zName==0 ) continue; - sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC); + sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, P3_STATIC); pBt = db->aDb[i].pBt; if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){ zState = "closed"; - }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, + }else if( sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } - sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC); - sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); + sqlite3VdbeOp3(v, OP_String8, 0, 0, zState, P3_STATIC); + sqlite3VdbeAddOp(v, OP_Callback, 2, 0); } }else #endif @@ -64725,7 +57967,7 @@ SQLITE_PRIVATE void sqlite3Pragma( ** the VDBE implementing the pragma to expire. Most (all?) pragmas ** are only valid for a single execution. */ - sqlite3VdbeAddOp2(v, OP_Expire, 1, 0); + sqlite3VdbeAddOp(v, OP_Expire, 1, 0); /* ** Reset the safety level, in case the fullfsync flag or synchronous @@ -64762,26 +58004,17 @@ pragma_out: ** interface, and routines that contribute to loading the database schema ** from disk. ** -** $Id: prepare.c,v 1.89 2008/07/08 19:34:07 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* ** Fill the InitData structure with an error message that indicates ** that the database is corrupt. */ -static void corruptSchema( - InitData *pData, /* Initialization context */ - const char *zObj, /* Object being parsed at the point of error */ - const char *zExtra /* Error information */ -){ +static void corruptSchema(InitData *pData, const char *zExtra){ if( !pData->db->mallocFailed ){ - if( zObj==0 ) zObj = "?"; - sqlite3SetString(pData->pzErrMsg, pData->db, - "malformed database schema (%s)", zObj); - if( zExtra && zExtra[0] ){ - *pData->pzErrMsg = sqlite3MPrintf(pData->db, "%z - %s", - *pData->pzErrMsg, zExtra); - } + sqlite3SetString(pData->pzErrMsg, "malformed database schema", + zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0); } pData->rc = SQLITE_CORRUPT; } @@ -64807,14 +58040,14 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char pData->rc = SQLITE_OK; DbClearProperty(db, iDb, DB_Empty); if( db->mallocFailed ){ - corruptSchema(pData, argv[0], 0); + corruptSchema(pData, 0); return SQLITE_NOMEM; } assert( argc==3 ); if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */ if( argv[1]==0 ){ - corruptSchema(pData, argv[0], 0); + corruptSchema(pData, 0); return 1; } assert( iDb>=0 && iDbnDb ); @@ -64837,13 +58070,11 @@ SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char if( rc==SQLITE_NOMEM ){ db->mallocFailed = 1; }else if( rc!=SQLITE_INTERRUPT ){ - corruptSchema(pData, argv[0], zErr); + corruptSchema(pData, zErr); } sqlite3_free(zErr); return 1; } - }else if( argv[0]==0 ){ - corruptSchema(pData, 0, 0); }else{ /* If the SQL column is blank it means this is an index that ** was created to be the PRIMARY KEY or to fulfill a UNIQUE @@ -64930,6 +58161,7 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ zMasterName = SCHEMA_TABLE(iDb); /* Construct the schema tables. */ + sqlite3SafetyOff(db); azArg[0] = zMasterName; azArg[1] = "1"; azArg[2] = zMasterSchema; @@ -64937,10 +58169,9 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ initData.db = db; initData.iDb = iDb; initData.pzErrMsg = pzErrMsg; - (void)sqlite3SafetyOff(db); rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0); - (void)sqlite3SafetyOn(db); if( rc ){ + sqlite3SafetyOn(db); rc = initData.rc; goto error_out; } @@ -64948,6 +58179,7 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ if( pTab ){ pTab->readOnly = 1; } + sqlite3SafetyOn(db); /* Create a cursor to hold the database open */ @@ -64958,16 +58190,12 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ } return SQLITE_OK; } - curMain = sqlite3MallocZero(sqlite3BtreeCursorSize()); - if( !curMain ){ - rc = SQLITE_NOMEM; - goto error_out; - } sqlite3BtreeEnter(pDb->pBt); - rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, curMain); + rc = sqlite3BtreeCursor(pDb->pBt, MASTER_ROOT, 0, 0, 0, &curMain); if( rc!=SQLITE_OK && rc!=SQLITE_EMPTY ){ - sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc)); - goto leave_error_out; + sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0); + sqlite3BtreeLeave(pDb->pBt); + goto error_out; } /* Get the database meta information. @@ -64993,8 +58221,10 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ rc = sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]); } if( rc ){ - sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc)); - goto leave_error_out; + sqlite3SetString(pzErrMsg, sqlite3ErrStr(rc), (char*)0); + sqlite3BtreeCloseCursor(curMain); + sqlite3BtreeLeave(pDb->pBt); + goto error_out; } }else{ memset(meta, 0, sizeof(meta)); @@ -65014,10 +58244,11 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ }else{ /* If opening an attached database, the encoding much match ENC(db) */ if( meta[4]!=ENC(db) ){ - sqlite3SetString(pzErrMsg, db, "attached databases must use the same" - " text encoding as main database"); - rc = SQLITE_ERROR; - goto leave_error_out; + sqlite3BtreeCloseCursor(curMain); + sqlite3SetString(pzErrMsg, "attached databases must use the same" + " text encoding as main database", (char*)0); + sqlite3BtreeLeave(pDb->pBt); + return SQLITE_ERROR; } } }else{ @@ -65025,13 +58256,10 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ } pDb->pSchema->enc = ENC(db); - if( pDb->pSchema->cache_size==0 ){ - size = meta[2]; - if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } - if( size<0 ) size = -size; - pDb->pSchema->cache_size = size; - sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); - } + size = meta[2]; + if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; } + pDb->pSchema->cache_size = size; + sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); /* ** file_format==1 Version 3.0.0. @@ -65044,9 +58272,10 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ pDb->pSchema->file_format = 1; } if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){ - sqlite3SetString(pzErrMsg, db, "unsupported file format"); - rc = SQLITE_ERROR; - goto leave_error_out; + sqlite3BtreeCloseCursor(curMain); + sqlite3SetString(pzErrMsg, "unsupported file format", (char*)0); + sqlite3BtreeLeave(pDb->pBt); + return SQLITE_ERROR; } /* Ticket #2804: When we open a database in the newer file format, @@ -65069,7 +58298,7 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM '%q'.%s", db->aDb[iDb].zName, zMasterName); - (void)sqlite3SafetyOff(db); + sqlite3SafetyOff(db); #ifndef SQLITE_OMIT_AUTHORIZATION { int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); @@ -65082,15 +58311,17 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ } #endif if( rc==SQLITE_ABORT ) rc = initData.rc; - (void)sqlite3SafetyOn(db); + sqlite3SafetyOn(db); sqlite3_free(zSql); #ifndef SQLITE_OMIT_ANALYZE if( rc==SQLITE_OK ){ sqlite3AnalysisLoad(db, iDb); } #endif + sqlite3BtreeCloseCursor(curMain); } if( db->mallocFailed ){ + /* sqlite3SetString(pzErrMsg, "out of memory", (char*)0); */ rc = SQLITE_NOMEM; sqlite3ResetInternalSchema(db, 0); } @@ -65106,14 +58337,6 @@ static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){ DbSetProperty(db, iDb, DB_SchemaLoaded); rc = SQLITE_OK; } - - /* Jump here for an error that occurs after successfully allocating - ** curMain and calling sqlite3BtreeEnter(). For an error that occurs - ** before that point, jump to error_out. - */ -leave_error_out: - sqlite3BtreeCloseCursor(curMain); - sqlite3_free(curMain); sqlite3BtreeLeave(pDb->pBt); error_out: @@ -65200,32 +58423,23 @@ static int schemaIsValid(sqlite3 *db){ int cookie; int allOk = 1; - curTemp = (BtCursor *)sqlite3Malloc(sqlite3BtreeCursorSize()); - if( curTemp ){ - assert( sqlite3_mutex_held(db->mutex) ); - for(iDb=0; allOk && iDbnDb; iDb++){ - Btree *pBt; - pBt = db->aDb[iDb].pBt; - if( pBt==0 ) continue; - memset(curTemp, 0, sqlite3BtreeCursorSize()); - rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, curTemp); - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie); - if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){ - allOk = 0; - } - sqlite3BtreeCloseCursor(curTemp); - } - if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ - db->mallocFailed = 1; + assert( sqlite3_mutex_held(db->mutex) ); + for(iDb=0; allOk && iDbnDb; iDb++){ + Btree *pBt; + pBt = db->aDb[iDb].pBt; + if( pBt==0 ) continue; + rc = sqlite3BtreeCursor(pBt, MASTER_ROOT, 0, 0, 0, &curTemp); + if( rc==SQLITE_OK ){ + rc = sqlite3BtreeGetMeta(pBt, 1, (u32 *)&cookie); + if( rc==SQLITE_OK && cookie!=db->aDb[iDb].pSchema->schema_cookie ){ + allOk = 0; } + sqlite3BtreeCloseCursor(curTemp); + } + if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){ + db->mallocFailed = 1; } - sqlite3_free(curTemp); - }else{ - allOk = 0; - db->mallocFailed = 1; } - return allOk; } @@ -65264,7 +58478,7 @@ SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){ /* ** Compile the UTF-8 encoded SQL statement zSql into a statement handle. */ -static int sqlite3Prepare( +SQLITE_PRIVATE int sqlite3Prepare( sqlite3 *db, /* Database handle. */ const char *zSql, /* UTF-8 encoded SQL statement. */ int nBytes, /* Length of zSql in bytes. */ @@ -65296,30 +58510,27 @@ static int sqlite3Prepare( if( rc ){ const char *zDb = db->aDb[i].zName; sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb); - (void)sqlite3SafetyOff(db); - return sqlite3ApiExit(db, SQLITE_LOCKED); + sqlite3SafetyOff(db); + return SQLITE_LOCKED; } } } memset(&sParse, 0, sizeof(sParse)); sParse.db = db; - if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){ + if( nBytes>=0 && zSql[nBytes]!=0 ){ char *zSqlCopy; - int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; - if( nBytes>mxLen ){ + if( SQLITE_MAX_SQL_LENGTH>0 && nBytes>SQLITE_MAX_SQL_LENGTH ){ sqlite3Error(db, SQLITE_TOOBIG, "statement too long"); - (void)sqlite3SafetyOff(db); - return sqlite3ApiExit(db, SQLITE_TOOBIG); + sqlite3SafetyOff(db); + return SQLITE_TOOBIG; } zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); if( zSqlCopy ){ sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); sqlite3_free(zSqlCopy); - sParse.zTail = &zSql[sParse.zTail-zSqlCopy]; - }else{ - sParse.zTail = &zSql[nBytes]; } + sParse.zTail = &zSql[nBytes]; }else{ sqlite3RunParser(&sParse, zSql, &zErrMsg); } @@ -65346,19 +58557,16 @@ static int sqlite3Prepare( if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){ if( sParse.explain==2 ){ sqlite3VdbeSetNumCols(sParse.pVdbe, 3); - sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P4_STATIC); + sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "order", P3_STATIC); + sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "from", P3_STATIC); + sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "detail", P3_STATIC); }else{ - sqlite3VdbeSetNumCols(sParse.pVdbe, 8); - sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 5, COLNAME_NAME, "p4", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 6, COLNAME_NAME, "p5", P4_STATIC); - sqlite3VdbeSetColName(sParse.pVdbe, 7, COLNAME_NAME, "comment",P4_STATIC); + sqlite3VdbeSetNumCols(sParse.pVdbe, 5); + sqlite3VdbeSetColName(sParse.pVdbe, 0, COLNAME_NAME, "addr", P3_STATIC); + sqlite3VdbeSetColName(sParse.pVdbe, 1, COLNAME_NAME, "opcode", P3_STATIC); + sqlite3VdbeSetColName(sParse.pVdbe, 2, COLNAME_NAME, "p1", P3_STATIC); + sqlite3VdbeSetColName(sParse.pVdbe, 3, COLNAME_NAME, "p2", P3_STATIC); + sqlite3VdbeSetColName(sParse.pVdbe, 4, COLNAME_NAME, "p3", P3_STATIC); } } #endif @@ -65397,7 +58605,7 @@ static int sqlite3LockAndPrepare( const char **pzTail /* OUT: End of parsed string */ ){ int rc; - if( !sqlite3SafetyCheckOk(db) ){ + if( sqlite3SafetyCheck(db) ){ return SQLITE_MISUSE; } sqlite3_mutex_enter(db->mutex); @@ -65421,7 +58629,9 @@ SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){ assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); zSql = sqlite3_sql((sqlite3_stmt *)p); - assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ + if( zSql==0 ){ + return 0; + } db = sqlite3VdbeDb(p); assert( sqlite3_mutex_held(db->mutex) ); rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0); @@ -65457,10 +58667,7 @@ SQLITE_API int sqlite3_prepare( sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ - int rc; - rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; + return sqlite3LockAndPrepare(db,zSql,nBytes,0,ppStmt,pzTail); } SQLITE_API int sqlite3_prepare_v2( sqlite3 *db, /* Database handle. */ @@ -65469,10 +58676,7 @@ SQLITE_API int sqlite3_prepare_v2( sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ - int rc; - rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; + return sqlite3LockAndPrepare(db,zSql,nBytes,1,ppStmt,pzTail); } @@ -65496,7 +58700,7 @@ static int sqlite3Prepare16( const char *zTail8 = 0; int rc = SQLITE_OK; - if( !sqlite3SafetyCheckOk(db) ){ + if( sqlite3SafetyCheck(db) ){ return SQLITE_MISUSE; } sqlite3_mutex_enter(db->mutex); @@ -65535,10 +58739,7 @@ SQLITE_API int sqlite3_prepare16( sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ - int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; + return sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail); } SQLITE_API int sqlite3_prepare16_v2( sqlite3 *db, /* Database handle. */ @@ -65547,10 +58748,7 @@ SQLITE_API int sqlite3_prepare16_v2( sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const void **pzTail /* OUT: End of parsed string */ ){ - int rc; - rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail); - assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */ - return rc; + return sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail); } #endif /* SQLITE_OMIT_UTF16 */ @@ -65571,7 +58769,7 @@ SQLITE_API int sqlite3_prepare16_v2( ** This file contains C code routines that are called by the parser ** to handle SELECT statements in SQLite. ** -** $Id: select.c,v 1.457 2008/07/15 20:56:17 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ @@ -65591,17 +58789,6 @@ static void clearSelect(Select *p){ sqlite3ExprDelete(p->pOffset); } -/* -** Initialize a SelectDest structure. -*/ -SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){ - pDest->eDest = eDest; - pDest->iParm = iParm; - pDest->affinity = 0; - pDest->iMem = 0; - pDest->nMem = 0; -} - /* ** Allocate a new Select structure and return a pointer to that @@ -65642,6 +58829,8 @@ SQLITE_PRIVATE Select *sqlite3SelectNew( assert( pOffset==0 || pLimit!=0 ); pNew->pLimit = pLimit; pNew->pOffset = pOffset; + pNew->iLimit = -1; + pNew->iOffset = -1; pNew->addrOpenEphm[0] = -1; pNew->addrOpenEphm[1] = -1; pNew->addrOpenEphm[2] = -1; @@ -65718,11 +58907,12 @@ SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *p (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) || (jointype & JT_ERROR)!=0 ){ - const char *zSp = " "; - assert( pB!=0 ); - if( pC==0 ){ zSp++; } + const char *zSp1 = " "; + const char *zSp2 = " "; + if( pB==0 ){ zSp1++; } + if( pC==0 ){ zSp2++; } sqlite3ErrorMsg(pParse, "unknown or unsupported join type: " - "%T %T%s%T", pA, pB, zSp, pC); + "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC); jointype = JT_INNER; }else if( jointype & JT_RIGHT ){ sqlite3ErrorMsg(pParse, @@ -65760,30 +58950,12 @@ static void setToken(Token *p, const char *z){ ** {a"bc} -> {"a""bc"} */ static void setQuotedToken(Parse *pParse, Token *p, const char *z){ - - /* Check if the string contains any " characters. If it does, then - ** this function will malloc space to create a quoted version of - ** the string in. Otherwise, save a call to sqlite3MPrintf() by - ** just copying the pointer to the string. - */ - const char *z2 = z; - while( *z2 ){ - if( *z2=='"' ) break; - z2++; - } - - if( *z2 ){ - /* String contains " characters - copy and quote the string. */ - p->z = (u8 *)sqlite3MPrintf(pParse->db, "\"%w\"", z); - if( p->z ){ - p->n = strlen((char *)p->z); - p->dyn = 1; - } + p->z = (u8 *)sqlite3MPrintf(0, "\"%w\"", z); + p->dyn = 1; + if( p->z ){ + p->n = strlen((char *)p->z); }else{ - /* String contains no " characters - copy the pointer. */ - p->z = (u8*)z; - p->n = (z2 - z); - p->dyn = 0; + pParse->db->mallocFailed = 1; } } @@ -65796,6 +58968,7 @@ SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *pParse, const char *zName){ return sqlite3PExpr(pParse, TK_ID, 0, 0, &dummy); } + /* ** Add a term to the WHERE expression in *ppExpr that requires the ** zCol column to be equal in the two tables pTab1 and pTab2. @@ -65808,8 +58981,7 @@ static void addWhereTerm( const Table *pTab2, /* Second table */ const char *zAlias2, /* Alias for second table. May be NULL */ int iRightJoinTable, /* VDBE cursor for the right table */ - Expr **ppExpr, /* Add the equality term to this expression */ - int isOuterJoin /* True if dealing with an OUTER join */ + Expr **ppExpr /* Add the equality term to this expression */ ){ Expr *pE1a, *pE1b, *pE1c; Expr *pE2a, *pE2b, *pE2c; @@ -65828,7 +59000,7 @@ static void addWhereTerm( pE1c = sqlite3PExpr(pParse, TK_DOT, pE1b, pE1a, 0); pE2c = sqlite3PExpr(pParse, TK_DOT, pE2b, pE2a, 0); pE = sqlite3PExpr(pParse, TK_EQ, pE1c, pE2c, 0); - if( pE && isOuterJoin ){ + if( pE ){ ExprSetProperty(pE, EP_FromJoin); pE->iRightJoinTable = iRightJoinTable; } @@ -65896,10 +59068,8 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ for(i=0; inSrc-1; i++, pRight++, pLeft++){ Table *pLeftTab = pLeft->pTab; Table *pRightTab = pRight->pTab; - int isOuter; if( pLeftTab==0 || pRightTab==0 ) continue; - isOuter = (pRight->jointype & JT_OUTER)!=0; /* When the NATURAL keyword is present, add WHERE clause terms for ** every column that the two tables have in common. @@ -65915,7 +59085,7 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ if( columnIndex(pRightTab, zName)>=0 ){ addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, pRightTab, pRight->zAlias, - pRight->iCursor, &p->pWhere, isOuter); + pRight->iCursor, &p->pWhere); } } @@ -65933,7 +59103,7 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ ** an AND operator. */ if( pRight->pOn ){ - if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor); + setJoinExpr(pRight->pOn, pRight->iCursor); p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn); pRight->pOn = 0; } @@ -65956,7 +59126,7 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ } addWhereTerm(pParse, zName, pLeftTab, pLeft->zAlias, pRightTab, pRight->zAlias, - pRight->iCursor, &p->pWhere, isOuter); + pRight->iCursor, &p->pWhere); } } } @@ -65970,36 +59140,24 @@ static int sqliteProcessJoin(Parse *pParse, Select *p){ static void pushOntoSorter( Parse *pParse, /* Parser context */ ExprList *pOrderBy, /* The ORDER BY clause */ - Select *pSelect, /* The whole SELECT statement */ - int regData /* Register holding data to be sorted */ + Select *pSelect /* The whole SELECT statement */ ){ Vdbe *v = pParse->pVdbe; - int nExpr = pOrderBy->nExpr; - int regBase = sqlite3GetTempRange(pParse, nExpr+2); - int regRecord = sqlite3GetTempReg(pParse); - sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0); - sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); - sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3ReleaseTempRange(pParse, regBase, nExpr+2); - if( pSelect->iLimit ){ + sqlite3ExprCodeExprList(pParse, pOrderBy); + sqlite3VdbeAddOp(v, OP_Sequence, pOrderBy->iECursor, 0); + sqlite3VdbeAddOp(v, OP_Pull, pOrderBy->nExpr + 1, 0); + sqlite3VdbeAddOp(v, OP_MakeRecord, pOrderBy->nExpr + 2, 0); + sqlite3VdbeAddOp(v, OP_IdxInsert, pOrderBy->iECursor, 0); + if( pSelect->iLimit>=0 ){ int addr1, addr2; - int iLimit; - if( pSelect->iOffset ){ - iLimit = pSelect->iOffset+1; - }else{ - iLimit = pSelect->iLimit; - } - addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); - sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1); - addr2 = sqlite3VdbeAddOp0(v, OP_Goto); + addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0); + sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1); + addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); - sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); + sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0); + sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0); sqlite3VdbeJumpHere(v, addr2); - pSelect->iLimit = 0; + pSelect->iLimit = -1; } } @@ -66009,21 +59167,25 @@ static void pushOntoSorter( static void codeOffset( Vdbe *v, /* Generate code into this VM */ Select *p, /* The SELECT statement being coded */ - int iContinue /* Jump here to skip the current record */ + int iContinue, /* Jump here to skip the current record */ + int nPop /* Number of times to pop stack when jumping */ ){ - if( p->iOffset && iContinue!=0 ){ + if( p->iOffset>=0 && iContinue!=0 ){ int addr; - sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1); - addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset); - sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue); - VdbeComment((v, "skip OFFSET records")); + sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iOffset); + addr = sqlite3VdbeAddOp(v, OP_IfMemNeg, p->iOffset, 0); + if( nPop>0 ){ + sqlite3VdbeAddOp(v, OP_Pop, nPop, 0); + } + sqlite3VdbeAddOp(v, OP_Goto, 0, iContinue); + VdbeComment((v, "# skip OFFSET records")); sqlite3VdbeJumpHere(v, addr); } } /* -** Add code that will check to make sure the N registers starting at iMem -** form a distinct entry. iTab is a sorting index that holds previously +** Add code that will check to make sure the top N elements of the +** stack are distinct. iTab is a sorting index that holds previously ** seen combinations of the N values. A new entry is made in iTab ** if the current N values are new. ** @@ -66031,21 +59193,17 @@ static void codeOffset( ** stack if the top N elements are not distinct. */ static void codeDistinct( - Parse *pParse, /* Parsing and code generating context */ + Vdbe *v, /* Generate code into this VM */ int iTab, /* A sorting index used to test for distinctness */ int addrRepeat, /* Jump to here if not distinct */ - int N, /* Number of elements */ - int iMem /* First element */ + int N /* The top N elements of the stack must be distinct */ ){ - Vdbe *v; - int r1; - - v = pParse->pVdbe; - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1); - sqlite3VdbeAddOp3(v, OP_Found, iTab, addrRepeat, r1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1); - sqlite3ReleaseTempReg(pParse, r1); + sqlite3VdbeAddOp(v, OP_MakeRecord, -N, 0); + sqlite3VdbeAddOp(v, OP_Distinct, iTab, sqlite3VdbeCurrentAddr(v)+3); + sqlite3VdbeAddOp(v, OP_Pop, N+1, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, addrRepeat); + VdbeComment((v, "# skip indistinct records")); + sqlite3VdbeAddOp(v, OP_IdxInsert, iTab, 0); } /* @@ -66054,12 +59212,7 @@ static void codeDistinct( ** column. We do this in a subroutine because the error occurs in multiple ** places. */ -static int checkForMultiColumnSelectError( - Parse *pParse, /* Parse context. */ - SelectDest *pDest, /* Destination of SELECT results */ - int nExpr /* Number of result columns returned by SELECT */ -){ - int eDest = pDest->eDest; +static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){ if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){ sqlite3ErrorMsg(pParse, "only a single result allowed for " "a SELECT that is part of an expression"); @@ -66078,7 +59231,7 @@ static int checkForMultiColumnSelectError( ** then data is pulled from srcTab and pEList is used only to get the ** datatypes for each column. */ -static void selectInnerLoop( +static int selectInnerLoop( Parse *pParse, /* The parser context */ Select *p, /* The complete select statement being coded */ ExprList *pEList, /* List of values being extracted */ @@ -66086,54 +59239,37 @@ static void selectInnerLoop( int nColumn, /* Number of columns in the source table */ ExprList *pOrderBy, /* If not NULL, sort results using this key */ int distinct, /* If >=0, make sure results are distinct */ - SelectDest *pDest, /* How to dispose of the results */ + int eDest, /* How to dispose of the results */ + int iParm, /* An argument to the disposal method */ int iContinue, /* Jump here to continue with next row */ - int iBreak /* Jump here to break out of the inner loop */ + int iBreak, /* Jump here to break out of the inner loop */ + char *aff /* affinity string if eDest is SRT_Union */ ){ Vdbe *v = pParse->pVdbe; int i; int hasDistinct; /* True if the DISTINCT keyword is present */ - int regResult; /* Start of memory holding result set */ - int eDest = pDest->eDest; /* How to dispose of results */ - int iParm = pDest->iParm; /* First argument to disposal method */ - int nResultCol; /* Number of result columns */ - if( v==0 ) return; + if( v==0 ) return 0; assert( pEList!=0 ); - hasDistinct = distinct>=0; + + /* If there was a LIMIT clause on the SELECT statement, then do the check + ** to see if this row should be output. + */ + hasDistinct = distinct>=0 && pEList->nExpr>0; if( pOrderBy==0 && !hasDistinct ){ - codeOffset(v, p, iContinue); + codeOffset(v, p, iContinue, 0); } /* Pull the requested columns. */ - if( nColumn>0 ){ - nResultCol = nColumn; - }else{ - nResultCol = pEList->nExpr; - } - if( pDest->iMem==0 ){ - pDest->iMem = pParse->nMem+1; - pDest->nMem = nResultCol; - pParse->nMem += nResultCol; - }else if( pDest->nMem!=nResultCol ){ - /* This happens when two SELECTs of a compound SELECT have differing - ** numbers of result columns. The error message will be generated by - ** a higher-level routine. */ - return; - } - regResult = pDest->iMem; if( nColumn>0 ){ for(i=0; inExpr; + sqlite3ExprCodeExprList(pParse, pEList); } - nColumn = nResultCol; /* If the DISTINCT keyword was present on the SELECT statement ** and this row has been seen before, then do not make this row @@ -66142,14 +59278,14 @@ static void selectInnerLoop( if( hasDistinct ){ assert( pEList!=0 ); assert( pEList->nExpr==nColumn ); - codeDistinct(pParse, distinct, iContinue, nColumn, regResult); + codeDistinct(v, distinct, iContinue, nColumn); if( pOrderBy==0 ){ - codeOffset(v, p, iContinue); + codeOffset(v, p, iContinue, nColumn); } } - if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ - return; + if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ + return 0; } switch( eDest ){ @@ -66158,11 +59294,11 @@ static void selectInnerLoop( */ #ifndef SQLITE_OMIT_COMPOUND_SELECT case SRT_Union: { - int r1; - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); - sqlite3ReleaseTempReg(pParse, r1); + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); + if( aff ){ + sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); + } + sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0); break; } @@ -66171,7 +59307,11 @@ static void selectInnerLoop( ** the temporary table iParm. */ case SRT_Except: { - sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn); + int addr; + addr = sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); + sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); + sqlite3VdbeAddOp(v, OP_NotFound, iParm, addr+3); + sqlite3VdbeAddOp(v, OP_Delete, iParm, 0); break; } #endif @@ -66180,18 +59320,14 @@ static void selectInnerLoop( */ case SRT_Table: case SRT_EphemTab: { - int r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); if( pOrderBy ){ - pushOntoSorter(pParse, pOrderBy, p, r1); + pushOntoSorter(pParse, pOrderBy, p); }else{ - int r2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2); - sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3ReleaseTempReg(pParse, r2); + sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); + sqlite3VdbeAddOp(v, OP_Pull, 1, 0); + sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); } - sqlite3ReleaseTempReg(pParse, r1); break; } @@ -66201,28 +59337,33 @@ static void selectInnerLoop( ** item into the set table with bogus data. */ case SRT_Set: { + int addr1 = sqlite3VdbeCurrentAddr(v); + int addr2; + assert( nColumn==1 ); - p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); + sqlite3VdbeAddOp(v, OP_NotNull, -1, addr1+3); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); + p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr,(iParm>>16)&0xff); if( pOrderBy ){ /* At first glance you would think we could optimize out the ** ORDER BY in this case since the order of entries in the set ** does not matter. But there might be a LIMIT clause, in which ** case the order does matter */ - pushOntoSorter(pParse, pOrderBy, p, regResult); + pushOntoSorter(pParse, pOrderBy, p); }else{ - int r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); - sqlite3ExprCacheAffinityChange(pParse, regResult, 1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); - sqlite3ReleaseTempReg(pParse, r1); + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); + sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); } + sqlite3VdbeJumpHere(v, addr2); break; } /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { - sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); + sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm); + sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); /* The LIMIT clause will terminate the loop for us */ break; } @@ -66234,9 +59375,9 @@ static void selectInnerLoop( case SRT_Mem: { assert( nColumn==1 ); if( pOrderBy ){ - pushOntoSorter(pParse, pOrderBy, p, regResult); + pushOntoSorter(pParse, pOrderBy, p); }else{ - sqlite3ExprCodeMove(pParse, regResult, iParm, 1); + sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); /* The LIMIT clause will jump out of the loop for us */ } break; @@ -66247,18 +59388,15 @@ static void selectInnerLoop( ** case of a subroutine, the subroutine itself is responsible for ** popping the data from the stack. */ - case SRT_Coroutine: + case SRT_Subroutine: case SRT_Callback: { if( pOrderBy ){ - int r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); - pushOntoSorter(pParse, pOrderBy, p, r1); - sqlite3ReleaseTempReg(pParse, r1); - }else if( eDest==SRT_Coroutine ){ - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); + pushOntoSorter(pParse, pOrderBy, p); + }else if( eDest==SRT_Subroutine ){ + sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); }else{ - sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); - sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn); + sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); } break; } @@ -66271,6 +59409,7 @@ static void selectInnerLoop( */ default: { assert( eDest==SRT_Discard ); + sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); break; } #endif @@ -66278,12 +59417,11 @@ static void selectInnerLoop( /* Jump to the end of the loop if the LIMIT is reached. */ - if( p->iLimit ){ - assert( pOrderBy==0 ); /* If there is an ORDER BY, the call to - ** pushOntoSorter() would have cleared p->iLimit */ - sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); - sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak); + if( p->iLimit>=0 && pOrderBy==0 ){ + sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); + sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak); } + return 0; } /* @@ -66298,8 +59436,8 @@ static void selectInnerLoop( ** ** Space to hold the KeyInfo structure is obtain from malloc. The calling ** function is responsible for seeing that this structure is eventually -** freed. Add the KeyInfo structure to the P4 field of an opcode using -** P4_KEYINFO_HANDOFF is the usual way of dealing with this. +** freed. Add the KeyInfo structure to the P3 field of an opcode using +** P3_KEYINFO_HANDOFF is the usual way of dealing with this. */ static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ sqlite3 *db = pParse->db; @@ -66335,11 +59473,12 @@ static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ ** routine generates the code needed to do that. */ static void generateSortTail( - Parse *pParse, /* Parsing context */ - Select *p, /* The SELECT statement */ - Vdbe *v, /* Generate code into this VDBE */ - int nColumn, /* Number of columns of data */ - SelectDest *pDest /* Write the sorted results here */ + Parse *pParse, /* Parsing context */ + Select *p, /* The SELECT statement */ + Vdbe *v, /* Generate code into this VDBE */ + int nColumn, /* Number of columns of data */ + int eDest, /* Write the sorted results here */ + int iParm /* Optional parameter associated with eDest */ ){ int brk = sqlite3VdbeMakeLabel(v); int cont = sqlite3VdbeMakeLabel(v); @@ -66348,60 +59487,54 @@ static void generateSortTail( int pseudoTab = 0; ExprList *pOrderBy = p->pOrderBy; - int eDest = pDest->eDest; - int iParm = pDest->iParm; - - int regRow; - int regRowid; - iTab = pOrderBy->iECursor; - if( eDest==SRT_Callback || eDest==SRT_Coroutine ){ + if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ pseudoTab = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nColumn); - sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, eDest==SRT_Callback); + sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0); + sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn); } - addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, brk); - codeOffset(v, p, cont); - regRow = sqlite3GetTempReg(pParse); - regRowid = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow); + addr = 1 + sqlite3VdbeAddOp(v, OP_Sort, iTab, brk); + codeOffset(v, p, cont, 0); + if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ + sqlite3VdbeAddOp(v, OP_Integer, 1, 0); + } + sqlite3VdbeAddOp(v, OP_Column, iTab, pOrderBy->nExpr + 1); switch( eDest ){ case SRT_Table: case SRT_EphemTab: { - sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); + sqlite3VdbeAddOp(v, OP_Pull, 1, 0); + sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); break; } #ifndef SQLITE_OMIT_SUBQUERY case SRT_Set: { assert( nColumn==1 ); - sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1); - sqlite3ExprCacheAffinityChange(pParse, regRow, 1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid); + sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + sqlite3VdbeAddOp(v, OP_Goto, 0, sqlite3VdbeCurrentAddr(v)+3); + sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); + sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); break; } case SRT_Mem: { assert( nColumn==1 ); - sqlite3ExprCodeMove(pParse, regRow, iParm, 1); + sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); /* The LIMIT clause will terminate the loop for us */ break; } #endif case SRT_Callback: - case SRT_Coroutine: { + case SRT_Subroutine: { int i; - sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid); - sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid); + sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0); for(i=0; iiMem+i ); - sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); + sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i); } if( eDest==SRT_Callback ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); - sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn); + sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); }else{ - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); + sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); } break; } @@ -66410,20 +59543,21 @@ static void generateSortTail( break; } } - sqlite3ReleaseTempReg(pParse, regRow); - sqlite3ReleaseTempReg(pParse, regRowid); - /* LIMIT has been implemented by the pushOntoSorter() routine. + /* Jump to the end of the loop when the LIMIT is reached */ - assert( p->iLimit==0 ); + if( p->iLimit>=0 ){ + sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); + sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk); + } /* The bottom of the loop */ sqlite3VdbeResolveLabel(v, cont); - sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); + sqlite3VdbeAddOp(v, OP_Next, iTab, addr); sqlite3VdbeResolveLabel(v, brk); - if( eDest==SRT_Callback || eDest==SRT_Coroutine ){ - sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); + if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ + sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0); } } @@ -66570,7 +59704,6 @@ static void generateColumnTypes( SrcList *pTabList, /* List of tables */ ExprList *pEList /* Expressions defining the result set */ ){ -#ifndef SQLITE_OMIT_DECLTYPE Vdbe *v = pParse->pVdbe; int i; NameContext sNC; @@ -66578,26 +59711,20 @@ static void generateColumnTypes( sNC.pParse = pParse; for(i=0; inExpr; i++){ Expr *p = pEList->a[i].pExpr; - const char *zType; -#ifdef SQLITE_ENABLE_COLUMN_METADATA const char *zOrigDb = 0; const char *zOrigTab = 0; const char *zOrigCol = 0; - zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); + const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); /* The vdbe must make its own copy of the column-type and other ** column specific strings, in case the schema is reset before this ** virtual machine is deleted. */ - sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT); - sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT); - sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT); -#else - zType = columnType(&sNC, p, 0, 0, 0); -#endif - sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P3_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P3_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P3_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P3_TRANSIENT); } -#endif /* SQLITE_OMIT_DECLTYPE */ } /* @@ -66635,7 +59762,9 @@ static void generateColumnNames( if( pEList->a[i].zName ){ char *zName = pEList->a[i].zName; sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, strlen(zName)); - }else if( p->op==TK_COLUMN && pTabList ){ + continue; + } + if( p->op==TK_COLUMN && pTabList ){ Table *pTab; char *zCol; int iCol = p->iColumn; @@ -66649,7 +59778,7 @@ static void generateColumnNames( }else{ zCol = pTab->aCol[iCol].zName; } - if( !shortNames && !fullNames ){ + if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){ sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){ char *zName = 0; @@ -66657,13 +59786,19 @@ static void generateColumnNames( zTab = pTabList->a[j].zAlias; if( fullNames || zTab==0 ) zTab = pTab->zName; - zName = sqlite3MPrintf(db, "%s.%s", zTab, zCol); - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC); + sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC); }else{ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); } - }else{ + }else if( p->span.z && p->span.z[0] ){ sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); + /* sqlite3VdbeCompressSpace(v, addr); */ + }else{ + char zName[30]; + assert( p->op!=TK_COLUMN || pTabList==0 ); + sqlite3_snprintf(sizeof(zName), zName, "column%d", i+1); + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, 0); } } generateColumnTypes(pParse, pTabList, pEList); @@ -66696,25 +59831,16 @@ static int prepSelectStmt(Parse*, Select*); */ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){ Table *pTab; - int i, j, rc; + int i, j; ExprList *pEList; Column *aCol, *pCol; sqlite3 *db = pParse->db; - int savedFlags; - savedFlags = db->flags; - db->flags &= ~SQLITE_FullColNames; - db->flags |= SQLITE_ShortColNames; - rc = sqlite3SelectResolve(pParse, pSelect, 0); - if( rc==SQLITE_OK ){ - while( pSelect->pPrior ) pSelect = pSelect->pPrior; - rc = prepSelectStmt(pParse, pSelect); - if( rc==SQLITE_OK ){ - rc = sqlite3SelectResolve(pParse, pSelect, 0); - } + while( pSelect->pPrior ) pSelect = pSelect->pPrior; + if( prepSelectStmt(pParse, pSelect) ){ + return 0; } - db->flags = savedFlags; - if( rc ){ + if( sqlite3SelectResolve(pParse, pSelect, 0) ){ return 0; } pTab = sqlite3DbMallocZero(db, sizeof(Table) ); @@ -66728,7 +59854,7 @@ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Se assert( pTab->nCol>0 ); pTab->aCol = aCol = sqlite3DbMallocZero(db, sizeof(pTab->aCol[0])*pTab->nCol); for(i=0, pCol=aCol; inCol; i++, pCol++){ - Expr *p; + Expr *p, *pR; char *zType; char *zName; int nName; @@ -66743,14 +59869,16 @@ SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Se if( (zName = pEList->a[i].zName)!=0 ){ /* If the column contains an "AS " phrase, use as the name */ zName = sqlite3DbStrDup(db, zName); - }else if( p->op==TK_COLUMN && p->pTab ){ - /* For columns use the column name name */ - int iCol = p->iColumn; - if( iCol<0 ) iCol = p->pTab->iPKey; - zName = sqlite3MPrintf(db, "%s", p->pTab->aCol[iCol].zName); - }else{ + }else if( p->op==TK_DOT + && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){ + /* For columns of the from A.B use B as the name */ + zName = sqlite3MPrintf(db, "%T", &pR->token); + }else if( p->span.z && p->span.z[0] ){ /* Use the original text of the column expression as its name */ zName = sqlite3MPrintf(db, "%T", &p->span); + }else{ + /* If all else fails, make up a name */ + zName = sqlite3MPrintf(db, "column%d", i+1); } if( !zName || db->mallocFailed ){ db->mallocFailed = 1; @@ -66871,7 +59999,7 @@ static int prepSelectStmt(Parse *pParse, Select *p){ /* An ordinary table or view name in the FROM clause */ assert( pFrom->pTab==0 ); pFrom->pTab = pTab = - sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase); + sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); if( pTab==0 ){ return 1; } @@ -66925,8 +60053,8 @@ static int prepSelectStmt(Parse *pParse, Select *p){ struct ExprList_item *a = pEList->a; ExprList *pNew = 0; int flags = pParse->db->flags; - int longNames = (flags & SQLITE_FullColNames)!=0 - && (flags & SQLITE_ShortColNames)==0; + int longNames = (flags & SQLITE_FullColNames)!=0 && + (flags & SQLITE_ShortColNames)==0; for(k=0; knExpr; k++){ Expr *pE = a[k].pExpr; @@ -66958,8 +60086,8 @@ static int prepSelectStmt(Parse *pParse, Select *p){ if( zTabName==0 || zTabName[0]==0 ){ zTabName = pTab->zName; } - assert( zTabName ); - if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){ + if( zTName && (zTabName==0 || zTabName[0]==0 || + sqlite3StrICmp(zTName, zTabName)!=0) ){ continue; } tableSeen = 1; @@ -66993,19 +60121,14 @@ static int prepSelectStmt(Parse *pParse, Select *p){ pRight = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); if( pRight==0 ) break; setQuotedToken(pParse, &pRight->token, zName); - if( longNames || pTabList->nSrc>1 ){ + if( zTabName && (longNames || pTabList->nSrc>1) ){ Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, 0); pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); if( pExpr==0 ) break; setQuotedToken(pParse, &pLeft->token, zTabName); -#if 1 setToken(&pExpr->span, sqlite3MPrintf(db, "%s.%s", zTabName, zName)); pExpr->span.dyn = 1; -#else - pExpr->span = pRight->token; - pExpr->span.dyn = 0; -#endif pExpr->token.z = 0; pExpr->token.n = 0; pExpr->token.dyn = 0; @@ -67035,12 +60158,10 @@ static int prepSelectStmt(Parse *pParse, Select *p){ sqlite3ExprListDelete(pEList); p->pEList = pNew; } -#if SQLITE_MAX_COLUMN - if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){ sqlite3ErrorMsg(pParse, "too many columns in result set"); rc = SQLITE_ERROR; } -#endif if( db->mallocFailed ){ rc = SQLITE_NOMEM; } @@ -67051,9 +60172,9 @@ static int prepSelectStmt(Parse *pParse, Select *p){ ** pE is a pointer to an expression which is a single term in ** ORDER BY or GROUP BY clause. ** -** At the point this routine is called, we already know that the -** ORDER BY term is not an integer index into the result set. That -** casee is handled by the calling routine. +** If pE evaluates to an integer constant i, then return i. +** This is an indication to the caller that it should sort +** by the i-th column of the result set. ** ** If pE is a well-formed expression and the SELECT statement ** is not compound, then return 0. This indicates to the @@ -67078,8 +60199,20 @@ static int matchOrderByTermToExprList( ExprList *pEList; /* The columns of the result set */ NameContext nc; /* Name context for resolving pE */ - assert( sqlite3ExprIsInteger(pE, &i)==0 ); + + /* If the term is an integer constant, return the value of that + ** constant */ pEList = pSelect->pEList; + if( sqlite3ExprIsInteger(pE, &i) ){ + if( i<=0 ){ + /* If i is too small, make it too big. That way the calling + ** function still sees a value that is out of range, but does + ** not confuse the column number with 0 or -1 result code. + */ + i = pEList->nExpr+1; + } + return i; + } /* If the term is a simple identifier that try to match that identifier ** against a column name in the result set. @@ -67154,14 +60287,12 @@ static int processOrderGroupBy( sqlite3 *db = pParse->db; ExprList *pEList; - if( pOrderBy==0 || pParse->db->mallocFailed ) return 0; -#if SQLITE_MAX_COLUMN - if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + if( pOrderBy==0 ) return 0; + if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ const char *zType = isOrder ? "ORDER" : "GROUP"; sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); return 1; } -#endif pEList = pSelect->pEList; if( pEList==0 ){ return 0; @@ -67169,19 +60300,16 @@ static int processOrderGroupBy( for(i=0; inExpr; i++){ int iCol; Expr *pE = pOrderBy->a[i].pExpr; - if( sqlite3ExprIsInteger(pE, &iCol) ){ - if( iCol<=0 || iCol>pEList->nExpr ){ - const char *zType = isOrder ? "ORDER" : "GROUP"; - sqlite3ErrorMsg(pParse, - "%r %s BY term out of range - should be " - "between 1 and %d", i+1, zType, pEList->nExpr); - return 1; - } - }else{ - iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg); - if( iCol<0 ){ - return 1; - } + iCol = matchOrderByTermToExprList(pParse, pSelect, pE, i+1, 0, pHasAgg); + if( iCol<0 ){ + return 1; + } + if( iCol>pEList->nExpr ){ + const char *zType = isOrder ? "ORDER" : "GROUP"; + sqlite3ErrorMsg(pParse, + "%r %s BY term out of range - should be " + "between 1 and %d", i+1, zType, pEList->nExpr); + return 1; } if( iCol>0 ){ CollSeq *pColl = pE->pColl; @@ -67189,7 +60317,7 @@ static int processOrderGroupBy( sqlite3ExprDelete(pE); pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr); pOrderBy->a[i].pExpr = pE; - if( pE && pColl && flags ){ + if( pColl && flags ){ pE->pColl = pColl; pE->flags |= flags; } @@ -67202,15 +60330,22 @@ static int processOrderGroupBy( ** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return ** the number of errors seen. ** -** If iTable>0 then make the N-th term of the ORDER BY clause refer to -** the N-th column of table iTable. +** The processing depends on whether the SELECT is simple or compound. +** For a simple SELECT statement, evry term of the ORDER BY or GROUP BY +** clause needs to be an expression. If any expression is an integer +** constant, then that expression is replaced by the corresponding +** expression from the result set. ** -** If iTable==0 then transform each term of the ORDER BY clause to refer -** to a column of the result set by number. +** For compound SELECT statements, every expression needs to be of +** type TK_COLUMN with a iTable value as given in the 4th parameter. +** If any expression is an integer, that becomes the column number. +** Otherwise, match the expression against result set columns from +** the left-most SELECT. */ static int processCompoundOrderBy( Parse *pParse, /* Parsing context. Leave error messages here */ - Select *pSelect /* The SELECT statement containing the ORDER BY */ + Select *pSelect, /* The SELECT statement containing the ORDER BY */ + int iTable /* Output table for compound SELECT statements */ ){ int i; ExprList *pOrderBy; @@ -67220,13 +60355,11 @@ static int processCompoundOrderBy( pOrderBy = pSelect->pOrderBy; if( pOrderBy==0 ) return 0; - db = pParse->db; -#if SQLITE_MAX_COLUMN - if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){ + if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); return 1; } -#endif + db = pParse->db; for(i=0; inExpr; i++){ pOrderBy->a[i].done = 0; } @@ -67235,37 +60368,36 @@ static int processCompoundOrderBy( } while( pSelect && moreToDo ){ moreToDo = 0; - pEList = pSelect->pEList; - if( pEList==0 ){ - return 1; - } for(i=0; inExpr; i++){ - int iCol = -1; + int iCol; Expr *pE, *pDup; if( pOrderBy->a[i].done ) continue; pE = pOrderBy->a[i].pExpr; - if( sqlite3ExprIsInteger(pE, &iCol) ){ - if( iCol<0 || iCol>pEList->nExpr ){ - sqlite3ErrorMsg(pParse, - "%r ORDER BY term out of range - should be " - "between 1 and %d", i+1, pEList->nExpr); - return 1; - } - }else{ - pDup = sqlite3ExprDup(db, pE); - if( !db->mallocFailed ){ - assert(pDup); - iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0); - } - sqlite3ExprDelete(pDup); - if( iCol<0 ){ - return 1; - } + pDup = sqlite3ExprDup(db, pE); + if( pDup==0 ){ + return 1; + } + iCol = matchOrderByTermToExprList(pParse, pSelect, pDup, i+1, 1, 0); + sqlite3ExprDelete(pDup); + if( iCol<0 ){ + return 1; + } + pEList = pSelect->pEList; + if( pEList==0 ){ + return 1; + } + if( iCol>pEList->nExpr ){ + sqlite3ErrorMsg(pParse, + "%r ORDER BY term out of range - should be " + "between 1 and %d", i+1, pEList->nExpr); + return 1; } if( iCol>0 ){ - pE->op = TK_INTEGER; - pE->flags |= EP_IntValue; - pE->iTable = iCol; + pE->op = TK_COLUMN; + pE->iTable = iTable; + pE->iAgg = -1; + pE->iColumn = iCol-1; + pE->pTab = 0; pOrderBy->a[i].done = 1; }else{ moreToDo = 1; @@ -67291,11 +60423,6 @@ SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){ Vdbe *v = pParse->pVdbe; if( v==0 ){ v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db); -#ifndef SQLITE_OMIT_TRACE - if( v ){ - sqlite3VdbeAddOp0(v, OP_Trace); - } -#endif } return v; } @@ -67323,8 +60450,7 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ Vdbe *v = 0; int iLimit = 0; int iOffset; - int addr1; - if( p->iLimit ) return; + int addr1, addr2; /* ** "LIMIT -1" always shows all rows. There is some @@ -67333,35 +60459,58 @@ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ ** no rows. */ if( p->pLimit ){ - p->iLimit = iLimit = ++pParse->nMem; + p->iLimit = iLimit = pParse->nMem; + pParse->nMem += 2; v = sqlite3GetVdbe(pParse); if( v==0 ) return; - sqlite3ExprCode(pParse, p->pLimit, iLimit); - sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); - VdbeComment((v, "LIMIT counter")); - sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); + sqlite3ExprCode(pParse, p->pLimit); + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); + sqlite3VdbeAddOp(v, OP_MemStore, iLimit, 1); + VdbeComment((v, "# LIMIT counter")); + sqlite3VdbeAddOp(v, OP_IfMemZero, iLimit, iBreak); + sqlite3VdbeAddOp(v, OP_MemLoad, iLimit, 0); } if( p->pOffset ){ - p->iOffset = iOffset = ++pParse->nMem; - if( p->pLimit ){ - pParse->nMem++; /* Allocate an extra register for limit+offset */ - } + p->iOffset = iOffset = pParse->nMem++; v = sqlite3GetVdbe(pParse); if( v==0 ) return; - sqlite3ExprCode(pParse, p->pOffset, iOffset); - sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); - VdbeComment((v, "OFFSET counter")); - addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); - sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset); + sqlite3ExprCode(pParse, p->pOffset); + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); + sqlite3VdbeAddOp(v, OP_MemStore, iOffset, p->pLimit==0); + VdbeComment((v, "# OFFSET counter")); + addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iOffset, 0); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + sqlite3VdbeAddOp(v, OP_Integer, 0, 0); sqlite3VdbeJumpHere(v, addr1); if( p->pLimit ){ - sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1); - VdbeComment((v, "LIMIT+OFFSET")); - addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); - sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1); - sqlite3VdbeJumpHere(v, addr1); + sqlite3VdbeAddOp(v, OP_Add, 0, 0); } } + if( p->pLimit ){ + addr1 = sqlite3VdbeAddOp(v, OP_IfMemPos, iLimit, 0); + sqlite3VdbeAddOp(v, OP_Pop, 1, 0); + sqlite3VdbeAddOp(v, OP_MemInt, -1, iLimit+1); + addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); + sqlite3VdbeJumpHere(v, addr1); + sqlite3VdbeAddOp(v, OP_MemStore, iLimit+1, 1); + VdbeComment((v, "# LIMIT+OFFSET")); + sqlite3VdbeJumpHere(v, addr2); + } +} + +/* +** Allocate a virtual index to use for sorting. +*/ +static void createSortingIndex(Parse *pParse, Select *p, ExprList *pOrderBy){ + if( pOrderBy ){ + int addr; + assert( pOrderBy->iECursor==0 ); + pOrderBy->iECursor = pParse->nTab++; + addr = sqlite3VdbeAddOp(pParse->pVdbe, OP_OpenEphemeral, + pOrderBy->iECursor, pOrderBy->nExpr+1); + assert( p->addrOpenEphm[2] == -1 ); + p->addrOpenEphm[2] = addr; + } } #ifndef SQLITE_OMIT_COMPOUND_SELECT @@ -67387,19 +60536,10 @@ static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){ } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ -/* Forward reference */ -static int multiSelectOrderBy( - Parse *pParse, /* Parsing context */ - Select *p, /* The right-most of SELECTs to be coded */ - SelectDest *pDest /* What to do with query results */ -); - - #ifndef SQLITE_OMIT_COMPOUND_SELECT /* -** This routine is called to process a compound query form from -** two or more separate queries using UNION, UNION ALL, EXCEPT, or -** INTERSECT +** This routine is called to process a query that is really the union +** or intersection of two or more separate queries. ** ** "p" points to the right-most of the two queries. the query on the ** left is p->pPrior. The left query could also be a compound query @@ -67430,13 +60570,17 @@ static int multiSelectOrderBy( static int multiSelect( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ - SelectDest *pDest /* What to do with query results */ + int eDest, /* \___ Store query results as specified */ + int iParm, /* / by these two parameters. */ + char *aff /* If eDest is SRT_Union, the affinity string */ ){ int rc = SQLITE_OK; /* Success code from a subroutine */ Select *pPrior; /* Another SELECT immediately to our left */ Vdbe *v; /* Generate code to this VDBE */ - SelectDest dest; /* Alternative data destination */ - Select *pDelete = 0; /* Chain of simple selects to delete */ + int nCol; /* Number of columns in the result set */ + ExprList *pOrderBy; /* The ORDER BY clause on p */ + int aSetP2[2]; /* Set P2 value of these op to number of columns */ + int nSetP2 = 0; /* Number of slots in aSetP2[] used */ /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT. @@ -67471,11 +60615,231 @@ static int multiSelect( /* Create the destination temporary table if necessary */ - dest = *pDest; - if( dest.eDest==SRT_EphemTab ){ + if( eDest==SRT_EphemTab ){ assert( p->pEList ); - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr); - dest.eDest = SRT_Table; + assert( nSetP2pOrderBy; + switch( p->op ){ + case TK_ALL: { + if( pOrderBy==0 ){ + int addr = 0; + assert( !pPrior->pLimit ); + pPrior->pLimit = p->pLimit; + pPrior->pOffset = p->pOffset; + rc = sqlite3Select(pParse, pPrior, eDest, iParm, 0, 0, 0, aff); + p->pLimit = 0; + p->pOffset = 0; + if( rc ){ + goto multi_select_end; + } + p->pPrior = 0; + p->iLimit = pPrior->iLimit; + p->iOffset = pPrior->iOffset; + if( p->iLimit>=0 ){ + addr = sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, 0); + VdbeComment((v, "# Jump ahead if LIMIT reached")); + } + rc = sqlite3Select(pParse, p, eDest, iParm, 0, 0, 0, aff); + p->pPrior = pPrior; + if( rc ){ + goto multi_select_end; + } + if( addr ){ + sqlite3VdbeJumpHere(v, addr); + } + break; + } + /* For UNION ALL ... ORDER BY fall through to the next case */ + } + case TK_EXCEPT: + case TK_UNION: { + int unionTab; /* Cursor number of the temporary table holding result */ + int op = 0; /* One of the SRT_ operations to apply to self */ + int priorOp; /* The SRT_ operation to apply to prior selects */ + Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ + int addr; + + priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union; + if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ + /* We can reuse a temporary table generated by a SELECT to our + ** right. + */ + unionTab = iParm; + }else{ + /* We will need to create our own temporary table to hold the + ** intermediate results. + */ + unionTab = pParse->nTab++; + if( processCompoundOrderBy(pParse, p, unionTab) ){ + rc = 1; + goto multi_select_end; + } + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0); + if( priorOp==SRT_Table ){ + assert( nSetP2addrOpenEphm[0] == -1 ); + p->addrOpenEphm[0] = addr; + p->pRightmost->usesEphm = 1; + } + createSortingIndex(pParse, p, pOrderBy); + assert( p->pEList ); + } + + /* Code the SELECT statements to our left + */ + assert( !pPrior->pOrderBy ); + rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); + if( rc ){ + goto multi_select_end; + } + + /* Code the current SELECT statement + */ + switch( p->op ){ + case TK_EXCEPT: op = SRT_Except; break; + case TK_UNION: op = SRT_Union; break; + case TK_ALL: op = SRT_Table; break; + } + p->pPrior = 0; + p->pOrderBy = 0; + p->disallowOrderBy = pOrderBy!=0; + pLimit = p->pLimit; + p->pLimit = 0; + pOffset = p->pOffset; + p->pOffset = 0; + rc = sqlite3Select(pParse, p, op, unionTab, 0, 0, 0, aff); + /* Query flattening in sqlite3Select() might refill p->pOrderBy. + ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ + sqlite3ExprListDelete(p->pOrderBy); + p->pPrior = pPrior; + p->pOrderBy = pOrderBy; + sqlite3ExprDelete(p->pLimit); + p->pLimit = pLimit; + p->pOffset = pOffset; + p->iLimit = -1; + p->iOffset = -1; + if( rc ){ + goto multi_select_end; + } + + + /* Convert the data in the temporary table into whatever form + ** it is that we currently need. + */ + if( eDest!=priorOp || unionTab!=iParm ){ + int iCont, iBreak, iStart; + assert( p->pEList ); + if( eDest==SRT_Callback ){ + Select *pFirst = p; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + iBreak = sqlite3VdbeMakeLabel(v); + iCont = sqlite3VdbeMakeLabel(v); + computeLimitRegisters(pParse, p, iBreak); + sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); + iStart = sqlite3VdbeCurrentAddr(v); + rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, + pOrderBy, -1, eDest, iParm, + iCont, iBreak, 0); + if( rc ){ + rc = 1; + goto multi_select_end; + } + sqlite3VdbeResolveLabel(v, iCont); + sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); + sqlite3VdbeResolveLabel(v, iBreak); + sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); + } + break; + } + case TK_INTERSECT: { + int tab1, tab2; + int iCont, iBreak, iStart; + Expr *pLimit, *pOffset; + int addr; + + /* INTERSECT is different from the others since it requires + ** two temporary tables. Hence it has its own case. Begin + ** by allocating the tables we will need. + */ + tab1 = pParse->nTab++; + tab2 = pParse->nTab++; + if( processCompoundOrderBy(pParse, p, tab1) ){ + rc = 1; + goto multi_select_end; + } + createSortingIndex(pParse, p, pOrderBy); + + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 0); + assert( p->addrOpenEphm[0] == -1 ); + p->addrOpenEphm[0] = addr; + p->pRightmost->usesEphm = 1; + assert( p->pEList ); + + /* Code the SELECTs to our left into temporary table "tab1". + */ + rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); + if( rc ){ + goto multi_select_end; + } + + /* Code the current SELECT into temporary table "tab2" + */ + addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab2, 0); + assert( p->addrOpenEphm[1] == -1 ); + p->addrOpenEphm[1] = addr; + p->pPrior = 0; + pLimit = p->pLimit; + p->pLimit = 0; + pOffset = p->pOffset; + p->pOffset = 0; + rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); + p->pPrior = pPrior; + sqlite3ExprDelete(p->pLimit); + p->pLimit = pLimit; + p->pOffset = pOffset; + if( rc ){ + goto multi_select_end; + } + + /* Generate code to take the intersection of the two temporary + ** tables. + */ + assert( p->pEList ); + if( eDest==SRT_Callback ){ + Select *pFirst = p; + while( pFirst->pPrior ) pFirst = pFirst->pPrior; + generateColumnNames(pParse, 0, pFirst->pEList); + } + iBreak = sqlite3VdbeMakeLabel(v); + iCont = sqlite3VdbeMakeLabel(v); + computeLimitRegisters(pParse, p, iBreak); + sqlite3VdbeAddOp(v, OP_Rewind, tab1, iBreak); + iStart = sqlite3VdbeAddOp(v, OP_RowKey, tab1, 0); + sqlite3VdbeAddOp(v, OP_NotFound, tab2, iCont); + rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, + pOrderBy, -1, eDest, iParm, + iCont, iBreak, 0); + if( rc ){ + rc = 1; + goto multi_select_end; + } + sqlite3VdbeResolveLabel(v, iCont); + sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); + sqlite3VdbeResolveLabel(v, iBreak); + sqlite3VdbeAddOp(v, OP_Close, tab2, 0); + sqlite3VdbeAddOp(v, OP_Close, tab1, 0); + break; + } } /* Make sure all SELECTs in the statement have the same number of elements @@ -67489,236 +60853,35 @@ static int multiSelect( goto multi_select_end; } - /* Compound SELECTs that have an ORDER BY clause are handled separately. + /* Set the number of columns in temporary tables */ - if( p->pOrderBy ){ - return multiSelectOrderBy(pParse, p, pDest); + nCol = p->pEList->nExpr; + while( nSetP2 ){ + sqlite3VdbeChangeP2(v, aSetP2[--nSetP2], nCol); } - /* Generate code for the left and right SELECT statements. - */ - switch( p->op ){ - case TK_ALL: { - int addr = 0; - assert( !pPrior->pLimit ); - pPrior->pLimit = p->pLimit; - pPrior->pOffset = p->pOffset; - rc = sqlite3Select(pParse, pPrior, &dest, 0, 0, 0); - p->pLimit = 0; - p->pOffset = 0; - if( rc ){ - goto multi_select_end; - } - p->pPrior = 0; - p->iLimit = pPrior->iLimit; - p->iOffset = pPrior->iOffset; - if( p->iLimit ){ - addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); - VdbeComment((v, "Jump ahead if LIMIT reached")); - } - rc = sqlite3Select(pParse, p, &dest, 0, 0, 0); - pDelete = p->pPrior; - p->pPrior = pPrior; - if( rc ){ - goto multi_select_end; - } - if( addr ){ - sqlite3VdbeJumpHere(v, addr); - } - break; - } - case TK_EXCEPT: - case TK_UNION: { - int unionTab; /* Cursor number of the temporary table holding result */ - int op = 0; /* One of the SRT_ operations to apply to self */ - int priorOp; /* The SRT_ operation to apply to prior selects */ - Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */ - int addr; - SelectDest uniondest; - - priorOp = SRT_Union; - if( dest.eDest==priorOp && !p->pLimit && !p->pOffset ){ - /* We can reuse a temporary table generated by a SELECT to our - ** right. - */ - unionTab = dest.iParm; - }else{ - /* We will need to create our own temporary table to hold the - ** intermediate results. - */ - unionTab = pParse->nTab++; - assert( p->pOrderBy==0 ); - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); - assert( p->addrOpenEphm[0] == -1 ); - p->addrOpenEphm[0] = addr; - p->pRightmost->usesEphm = 1; - assert( p->pEList ); - } - - /* Code the SELECT statements to our left - */ - assert( !pPrior->pOrderBy ); - sqlite3SelectDestInit(&uniondest, priorOp, unionTab); - rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT statement - */ - switch( p->op ){ - case TK_EXCEPT: op = SRT_Except; break; - case TK_UNION: op = SRT_Union; break; - case TK_ALL: op = SRT_Table; break; - } - p->pPrior = 0; - p->disallowOrderBy = 0; - pLimit = p->pLimit; - p->pLimit = 0; - pOffset = p->pOffset; - p->pOffset = 0; - uniondest.eDest = op; - rc = sqlite3Select(pParse, p, &uniondest, 0, 0, 0); - /* Query flattening in sqlite3Select() might refill p->pOrderBy. - ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */ - sqlite3ExprListDelete(p->pOrderBy); - pDelete = p->pPrior; - p->pPrior = pPrior; - p->pOrderBy = 0; - sqlite3ExprDelete(p->pLimit); - p->pLimit = pLimit; - p->pOffset = pOffset; - p->iLimit = 0; - p->iOffset = 0; - if( rc ){ - goto multi_select_end; - } - - - /* Convert the data in the temporary table into whatever form - ** it is that we currently need. - */ - if( dest.eDest!=priorOp || unionTab!=dest.iParm ){ - int iCont, iBreak, iStart; - assert( p->pEList ); - if( dest.eDest==SRT_Callback ){ - Select *pFirst = p; - while( pFirst->pPrior ) pFirst = pFirst->pPrior; - generateColumnNames(pParse, 0, pFirst->pEList); - } - iBreak = sqlite3VdbeMakeLabel(v); - iCont = sqlite3VdbeMakeLabel(v); - computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); - iStart = sqlite3VdbeCurrentAddr(v); - selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, - 0, -1, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0); - } - break; - } - case TK_INTERSECT: { - int tab1, tab2; - int iCont, iBreak, iStart; - Expr *pLimit, *pOffset; - int addr; - SelectDest intersectdest; - int r1; - - /* INTERSECT is different from the others since it requires - ** two temporary tables. Hence it has its own case. Begin - ** by allocating the tables we will need. - */ - tab1 = pParse->nTab++; - tab2 = pParse->nTab++; - assert( p->pOrderBy==0 ); - - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0); - assert( p->addrOpenEphm[0] == -1 ); - p->addrOpenEphm[0] = addr; - p->pRightmost->usesEphm = 1; - assert( p->pEList ); - - /* Code the SELECTs to our left into temporary table "tab1". - */ - sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); - rc = sqlite3Select(pParse, pPrior, &intersectdest, 0, 0, 0); - if( rc ){ - goto multi_select_end; - } - - /* Code the current SELECT into temporary table "tab2" - */ - addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0); - assert( p->addrOpenEphm[1] == -1 ); - p->addrOpenEphm[1] = addr; - p->pPrior = 0; - pLimit = p->pLimit; - p->pLimit = 0; - pOffset = p->pOffset; - p->pOffset = 0; - intersectdest.iParm = tab2; - rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0); - pDelete = p->pPrior; - p->pPrior = pPrior; - sqlite3ExprDelete(p->pLimit); - p->pLimit = pLimit; - p->pOffset = pOffset; - if( rc ){ - goto multi_select_end; - } - - /* Generate code to take the intersection of the two temporary - ** tables. - */ - assert( p->pEList ); - if( dest.eDest==SRT_Callback ){ - Select *pFirst = p; - while( pFirst->pPrior ) pFirst = pFirst->pPrior; - generateColumnNames(pParse, 0, pFirst->pEList); - } - iBreak = sqlite3VdbeMakeLabel(v); - iCont = sqlite3VdbeMakeLabel(v); - computeLimitRegisters(pParse, p, iBreak); - sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); - r1 = sqlite3GetTempReg(pParse); - iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1); - sqlite3VdbeAddOp3(v, OP_NotFound, tab2, iCont, r1); - sqlite3ReleaseTempReg(pParse, r1); - selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr, - 0, -1, &dest, iCont, iBreak); - sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); - sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); - sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); - break; - } - } - - /* Compute collating sequences used by - ** temporary tables needed to implement the compound select. - ** Attach the KeyInfo structure to all temporary tables. + /* Compute collating sequences used by either the ORDER BY clause or + ** by any temporary tables needed to implement the compound select. + ** Attach the KeyInfo structure to all temporary tables. Invoke the + ** ORDER BY processing if there is an ORDER BY clause. ** ** This section is run by the right-most SELECT statement only. ** SELECT statements to the left always skip this part. The right-most ** SELECT might also skip this part if it has no ORDER BY clause and ** no temp tables are required. */ - if( p->usesEphm ){ + if( pOrderBy || p->usesEphm ){ int i; /* Loop counter */ KeyInfo *pKeyInfo; /* Collating sequence for the result set */ Select *pLoop; /* For looping through SELECT statements */ + int nKeyCol; /* Number of entries in pKeyInfo->aCol[] */ CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */ - int nCol; /* Number of columns in result set */ + CollSeq **aCopy; /* A copy of pKeyInfo->aColl[] */ assert( p->pRightmost==p ); - nCol = p->pEList->nExpr; + nKeyCol = nCol + (pOrderBy ? pOrderBy->nExpr : 0); pKeyInfo = sqlite3DbMallocZero(pParse->db, - sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1)); + sizeof(*pKeyInfo)+nKeyCol*(sizeof(CollSeq*) + 1)); if( !pKeyInfo ){ rc = SQLITE_NOMEM; goto multi_select_end; @@ -67744,612 +60907,63 @@ static int multiSelect( break; } sqlite3VdbeChangeP2(v, addr, nCol); - sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); + sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } + + if( pOrderBy ){ + struct ExprList_item *pOTerm = pOrderBy->a; + int nOrderByExpr = pOrderBy->nExpr; + int addr; + u8 *pSortOrder; + + /* Reuse the same pKeyInfo for the ORDER BY as was used above for + ** the compound select statements. Except we have to change out the + ** pKeyInfo->aColl[] values. Some of the aColl[] values will be + ** reused when constructing the pKeyInfo for the ORDER BY, so make + ** a copy. Sufficient space to hold both the nCol entries for + ** the compound select and the nOrderbyExpr entries for the ORDER BY + ** was allocated above. But we need to move the compound select + ** entries out of the way before constructing the ORDER BY entries. + ** Move the compound select entries into aCopy[] where they can be + ** accessed and reused when constructing the ORDER BY entries. + ** Because nCol might be greater than or less than nOrderByExpr + ** we have to use memmove() when doing the copy. + */ + aCopy = &pKeyInfo->aColl[nOrderByExpr]; + pSortOrder = pKeyInfo->aSortOrder = (u8*)&aCopy[nCol]; + memmove(aCopy, pKeyInfo->aColl, nCol*sizeof(CollSeq*)); + + apColl = pKeyInfo->aColl; + for(i=0; ipExpr; + if( (pExpr->flags & EP_ExpCollate) ){ + assert( pExpr->pColl!=0 ); + *apColl = pExpr->pColl; + }else{ + *apColl = aCopy[pExpr->iColumn]; + } + *pSortOrder = pOTerm->sortOrder; + } + assert( p->pRightmost==p ); + assert( p->addrOpenEphm[2]>=0 ); + addr = p->addrOpenEphm[2]; + sqlite3VdbeChangeP2(v, addr, p->pOrderBy->nExpr+2); + pKeyInfo->nField = nOrderByExpr; + sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); + pKeyInfo = 0; + generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); + } + sqlite3_free(pKeyInfo); } multi_select_end: - pDest->iMem = dest.iMem; - pDest->nMem = dest.nMem; - sqlite3SelectDelete(pDelete); return rc; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ -/* -** Code an output subroutine for a coroutine implementation of a -** SELECT statment. -** -** The data to be output is contained in pIn->iMem. There are -** pIn->nMem columns to be output. pDest is where the output should -** be sent. -** -** regReturn is the number of the register holding the subroutine -** return address. -** -** If regPrev>0 then it is a the first register in a vector that -** records the previous output. mem[regPrev] is a flag that is false -** if there has been no previous output. If regPrev>0 then code is -** generated to suppress duplicates. pKeyInfo is used for comparing -** keys. -** -** If the LIMIT found in p->iLimit is reached, jump immediately to -** iBreak. -*/ -static int generateOutputSubroutine( - Parse *pParse, /* Parsing context */ - Select *p, /* The SELECT statement */ - SelectDest *pIn, /* Coroutine supplying data */ - SelectDest *pDest, /* Where to send the data */ - int regReturn, /* The return address register */ - int regPrev, /* Previous result register. No uniqueness if 0 */ - KeyInfo *pKeyInfo, /* For comparing with previous entry */ - int p4type, /* The p4 type for pKeyInfo */ - int iBreak /* Jump here if we hit the LIMIT */ -){ - Vdbe *v = pParse->pVdbe; - int iContinue; - int addr; - - addr = sqlite3VdbeCurrentAddr(v); - iContinue = sqlite3VdbeMakeLabel(v); - - /* Suppress duplicates for UNION, EXCEPT, and INTERSECT - */ - if( regPrev ){ - int j1, j2; - j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); - j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem, - (char*)pKeyInfo, p4type); - sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); - sqlite3VdbeJumpHere(v, j1); - sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem); - sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev); - } - if( pParse->db->mallocFailed ) return 0; - - /* Suppress the the first OFFSET entries if there is an OFFSET clause - */ - codeOffset(v, p, iContinue); - - switch( pDest->eDest ){ - /* Store the result as data using a unique key. - */ - case SRT_Table: - case SRT_EphemTab: { - int r1 = sqlite3GetTempReg(pParse); - int r2 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1); - sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2); - sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2); - sqlite3VdbeChangeP5(v, OPFLAG_APPEND); - sqlite3ReleaseTempReg(pParse, r2); - sqlite3ReleaseTempReg(pParse, r1); - break; - } - -#ifndef SQLITE_OMIT_SUBQUERY - /* If we are creating a set for an "expr IN (SELECT ...)" construct, - ** then there should be a single item on the stack. Write this - ** item into the set table with bogus data. - */ - case SRT_Set: { - int r1; - assert( pIn->nMem==1 ); - p->affinity = - sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity); - r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1); - sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1); - sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1); - sqlite3ReleaseTempReg(pParse, r1); - break; - } - -#if 0 /* Never occurs on an ORDER BY query */ - /* If any row exist in the result set, record that fact and abort. - */ - case SRT_Exists: { - sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm); - /* The LIMIT clause will terminate the loop for us */ - break; - } -#endif - - /* If this is a scalar select that is part of an expression, then - ** store the results in the appropriate memory cell and break out - ** of the scan loop. - */ - case SRT_Mem: { - assert( pIn->nMem==1 ); - sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1); - /* The LIMIT clause will jump out of the loop for us */ - break; - } -#endif /* #ifndef SQLITE_OMIT_SUBQUERY */ - - /* Send the data to the callback function or to a subroutine. In the - ** case of a subroutine, the subroutine itself is responsible for - ** popping the data from the stack. - */ - case SRT_Coroutine: { - if( pDest->iMem==0 ){ - pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem); - pDest->nMem = pIn->nMem; - } - sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem); - sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm); - break; - } - - case SRT_Callback: { - sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem); - sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem); - break; - } - -#if !defined(SQLITE_OMIT_TRIGGER) - /* Discard the results. This is used for SELECT statements inside - ** the body of a TRIGGER. The purpose of such selects is to call - ** user-defined functions that have side effects. We do not care - ** about the actual results of the select. - */ - default: { - break; - } -#endif - } - - /* Jump to the end of the loop if the LIMIT is reached. - */ - if( p->iLimit ){ - sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); - sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak); - } - - /* Generate the subroutine return - */ - sqlite3VdbeResolveLabel(v, iContinue); - sqlite3VdbeAddOp1(v, OP_Return, regReturn); - - return addr; -} - -/* -** Alternative compound select code generator for cases when there -** is an ORDER BY clause. -** -** We assume a query of the following form: -** -** ORDER BY -** -** is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea -** is to code both and with the ORDER BY clause as -** co-routines. Then run the co-routines in parallel and merge the results -** into the output. In addition to the two coroutines (called selectA and -** selectB) there are 7 subroutines: -** -** outA: Move the output of the selectA coroutine into the output -** of the compound query. -** -** outB: Move the output of the selectB coroutine into the output -** of the compound query. (Only generated for UNION and -** UNION ALL. EXCEPT and INSERTSECT never output a row that -** appears only in B.) -** -** AltB: Called when there is data from both coroutines and AB. -** -** EofA: Called when data is exhausted from selectA. -** -** EofB: Called when data is exhausted from selectB. -** -** The implementation of the latter five subroutines depend on which -** is used: -** -** -** UNION ALL UNION EXCEPT INTERSECT -** ------------- ----------------- -------------- ----------------- -** AltB: outA, nextA outA, nextA outA, nextA nextA -** -** AeqB: outA, nextA nextA nextA outA, nextA -** -** AgtB: outB, nextB outB, nextB nextB nextB -** -** EofA: outB, nextB outB, nextB halt halt -** -** EofB: outA, nextA outA, nextA outA, nextA halt -** -** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA -** causes an immediate jump to EofA and an EOF on B following nextB causes -** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or -** following nextX causes a jump to the end of the select processing. -** -** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled -** within the output subroutine. The regPrev register set holds the previously -** output value. A comparison is made against this value and the output -** is skipped if the next results would be the same as the previous. -** -** The implementation plan is to implement the two coroutines and seven -** subroutines first, then put the control logic at the bottom. Like this: -** -** goto Init -** coA: coroutine for left query (A) -** coB: coroutine for right query (B) -** outA: output one row of A -** outB: output one row of B (UNION and UNION ALL only) -** EofA: ... -** EofB: ... -** AltB: ... -** AeqB: ... -** AgtB: ... -** Init: initialize coroutine registers -** yield coA -** if eof(A) goto EofA -** yield coB -** if eof(B) goto EofB -** Cmpr: Compare A, B -** Jump AltB, AeqB, AgtB -** End: ... -** -** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not -** actually called using Gosub and they do not Return. EofA and EofB loop -** until all data is exhausted then jump to the "end" labe. AltB, AeqB, -** and AgtB jump to either L2 or to one of EofA or EofB. -*/ -static int multiSelectOrderBy( - Parse *pParse, /* Parsing context */ - Select *p, /* The right-most of SELECTs to be coded */ - SelectDest *pDest /* What to do with query results */ -){ - int i, j; /* Loop counters */ - Select *pPrior; /* Another SELECT immediately to our left */ - Vdbe *v; /* Generate code to this VDBE */ - SelectDest destA; /* Destination for coroutine A */ - SelectDest destB; /* Destination for coroutine B */ - int regAddrA; /* Address register for select-A coroutine */ - int regEofA; /* Flag to indicate when select-A is complete */ - int regAddrB; /* Address register for select-B coroutine */ - int regEofB; /* Flag to indicate when select-B is complete */ - int addrSelectA; /* Address of the select-A coroutine */ - int addrSelectB; /* Address of the select-B coroutine */ - int regOutA; /* Address register for the output-A subroutine */ - int regOutB; /* Address register for the output-B subroutine */ - int addrOutA; /* Address of the output-A subroutine */ - int addrOutB; /* Address of the output-B subroutine */ - int addrEofA; /* Address of the select-A-exhausted subroutine */ - int addrEofB; /* Address of the select-B-exhausted subroutine */ - int addrAltB; /* Address of the AB subroutine */ - int regLimitA; /* Limit register for select-A */ - int regLimitB; /* Limit register for select-A */ - int regPrev; /* A range of registers to hold previous output */ - int savedLimit; /* Saved value of p->iLimit */ - int savedOffset; /* Saved value of p->iOffset */ - int labelCmpr; /* Label for the start of the merge algorithm */ - int labelEnd; /* Label for the end of the overall SELECT stmt */ - int j1; /* Jump instructions that get retargetted */ - int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */ - KeyInfo *pKeyDup; /* Comparison information for duplicate removal */ - KeyInfo *pKeyMerge; /* Comparison information for merging rows */ - sqlite3 *db; /* Database connection */ - ExprList *pOrderBy; /* The ORDER BY clause */ - int nOrderBy; /* Number of terms in the ORDER BY clause */ - int *aPermute; /* Mapping from ORDER BY terms to result set columns */ - u8 NotUsed; /* Dummy variables */ - - assert( p->pOrderBy!=0 ); - db = pParse->db; - v = pParse->pVdbe; - if( v==0 ) return SQLITE_NOMEM; - labelEnd = sqlite3VdbeMakeLabel(v); - labelCmpr = sqlite3VdbeMakeLabel(v); - - - /* Patch up the ORDER BY clause - */ - op = p->op; - pPrior = p->pPrior; - assert( pPrior->pOrderBy==0 ); - pOrderBy = p->pOrderBy; - assert( pOrderBy ); - if( processCompoundOrderBy(pParse, p) ){ - return SQLITE_ERROR; - } - nOrderBy = pOrderBy->nExpr; - - /* For operators other than UNION ALL we have to make sure that - ** the ORDER BY clause covers every term of the result set. Add - ** terms to the ORDER BY clause as necessary. - */ - if( op!=TK_ALL ){ - for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){ - for(j=0; ja[j].pExpr; - assert( pTerm->op==TK_INTEGER ); - assert( (pTerm->flags & EP_IntValue)!=0 ); - if( pTerm->iTable==i ) break; - } - if( j==nOrderBy ){ - Expr *pNew = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, 0); - if( pNew==0 ) return SQLITE_NOMEM; - pNew->flags |= EP_IntValue; - pNew->iTable = i; - pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew, 0); - nOrderBy++; - } - } - } - - /* Compute the comparison permutation and keyinfo that is used with - ** the permutation in order to comparisons to determine if the next - ** row of results comes from selectA or selectB. Also add explicit - ** collations to the ORDER BY clause terms so that when the subqueries - ** to the right and the left are evaluated, they use the correct - ** collation. - */ - aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy); - if( aPermute ){ - for(i=0; ia[i].pExpr; - assert( pTerm->op==TK_INTEGER ); - assert( (pTerm->flags & EP_IntValue)!=0 ); - aPermute[i] = pTerm->iTable-1; - assert( aPermute[i]>=0 && aPermute[i]pEList->nExpr ); - } - pKeyMerge = - sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1)); - if( pKeyMerge ){ - pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy]; - pKeyMerge->nField = nOrderBy; - pKeyMerge->enc = ENC(db); - for(i=0; ia[i].pExpr; - if( pTerm->flags & EP_ExpCollate ){ - pColl = pTerm->pColl; - }else{ - pColl = multiSelectCollSeq(pParse, p, aPermute[i]); - pTerm->flags |= EP_ExpCollate; - pTerm->pColl = pColl; - } - pKeyMerge->aColl[i] = pColl; - pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder; - } - } - }else{ - pKeyMerge = 0; - } - - /* Reattach the ORDER BY clause to the query. - */ - p->pOrderBy = pOrderBy; - pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy); - - /* Allocate a range of temporary registers and the KeyInfo needed - ** for the logic that removes duplicate result rows when the - ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL). - */ - if( op==TK_ALL ){ - regPrev = 0; - }else{ - int nExpr = p->pEList->nExpr; - assert( nOrderBy>=nExpr ); - regPrev = sqlite3GetTempRange(pParse, nExpr+1); - sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev); - pKeyDup = sqlite3DbMallocZero(db, - sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) ); - if( pKeyDup ){ - pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr]; - pKeyDup->nField = nExpr; - pKeyDup->enc = ENC(db); - for(i=0; iaColl[i] = multiSelectCollSeq(pParse, p, i); - pKeyDup->aSortOrder[i] = 0; - } - } - } - - /* Separate the left and the right query from one another - */ - p->pPrior = 0; - pPrior->pRightmost = 0; - processOrderGroupBy(pParse, p, p->pOrderBy, 1, &NotUsed); - if( pPrior->pPrior==0 ){ - processOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, 1, &NotUsed); - } - - /* Compute the limit registers */ - computeLimitRegisters(pParse, p, labelEnd); - if( p->iLimit && op==TK_ALL ){ - regLimitA = ++pParse->nMem; - regLimitB = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit, - regLimitA); - sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB); - }else{ - regLimitA = regLimitB = 0; - } - sqlite3ExprDelete(p->pLimit); - p->pLimit = 0; - sqlite3ExprDelete(p->pOffset); - p->pOffset = 0; - - regAddrA = ++pParse->nMem; - regEofA = ++pParse->nMem; - regAddrB = ++pParse->nMem; - regEofB = ++pParse->nMem; - regOutA = ++pParse->nMem; - regOutB = ++pParse->nMem; - sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA); - sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB); - - /* Jump past the various subroutines and coroutines to the main - ** merge loop - */ - j1 = sqlite3VdbeAddOp0(v, OP_Goto); - addrSelectA = sqlite3VdbeCurrentAddr(v); - - - /* Generate a coroutine to evaluate the SELECT statement to the - ** left of the compound operator - the "A" select. - */ - VdbeNoopComment((v, "Begin coroutine for left SELECT")); - pPrior->iLimit = regLimitA; - sqlite3Select(pParse, pPrior, &destA, 0, 0, 0); - sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA); - sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); - VdbeNoopComment((v, "End coroutine for left SELECT")); - - /* Generate a coroutine to evaluate the SELECT statement on - ** the right - the "B" select - */ - addrSelectB = sqlite3VdbeCurrentAddr(v); - VdbeNoopComment((v, "Begin coroutine for right SELECT")); - savedLimit = p->iLimit; - savedOffset = p->iOffset; - p->iLimit = regLimitB; - p->iOffset = 0; - sqlite3Select(pParse, p, &destB, 0, 0, 0); - p->iLimit = savedLimit; - p->iOffset = savedOffset; - sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB); - sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); - VdbeNoopComment((v, "End coroutine for right SELECT")); - - /* Generate a subroutine that outputs the current row of the A - ** select as the next output row of the compound select. - */ - VdbeNoopComment((v, "Output routine for A")); - addrOutA = generateOutputSubroutine(pParse, - p, &destA, pDest, regOutA, - regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd); - - /* Generate a subroutine that outputs the current row of the B - ** select as the next output row of the compound select. - */ - if( op==TK_ALL || op==TK_UNION ){ - VdbeNoopComment((v, "Output routine for B")); - addrOutB = generateOutputSubroutine(pParse, - p, &destB, pDest, regOutB, - regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd); - } - - /* Generate a subroutine to run when the results from select A - ** are exhausted and only data in select B remains. - */ - VdbeNoopComment((v, "eof-A subroutine")); - if( op==TK_EXCEPT || op==TK_INTERSECT ){ - addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd); - }else{ - addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd); - sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); - sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA); - } - - /* Generate a subroutine to run when the results from select B - ** are exhausted and only data in select A remains. - */ - if( op==TK_INTERSECT ){ - addrEofB = addrEofA; - }else{ - VdbeNoopComment((v, "eof-B subroutine")); - addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd); - sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA); - sqlite3VdbeAddOp1(v, OP_Yield, regAddrA); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB); - } - - /* Generate code to handle the case of AB - */ - VdbeNoopComment((v, "A-gt-B subroutine")); - addrAgtB = sqlite3VdbeCurrentAddr(v); - if( op==TK_ALL || op==TK_UNION ){ - sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB); - } - sqlite3VdbeAddOp1(v, OP_Yield, regAddrB); - sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); - sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr); - - /* This code runs once to initialize everything. - */ - sqlite3VdbeJumpHere(v, j1); - sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA); - sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB); - sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA); - sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB); - sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA); - sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB); - - /* Implement the main merge loop - */ - sqlite3VdbeResolveLabel(v, labelCmpr); - sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY); - sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy, - (char*)pKeyMerge, P4_KEYINFO_HANDOFF); - sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); - - /* Release temporary registers - */ - if( regPrev ){ - sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1); - } - - /* Jump to the this point in order to terminate the query. - */ - sqlite3VdbeResolveLabel(v, labelEnd); - - /* Set the number of output columns - */ - if( pDest->eDest==SRT_Callback ){ - Select *pFirst = pPrior; - while( pFirst->pPrior ) pFirst = pFirst->pPrior; - generateColumnNames(pParse, 0, pFirst->pEList); - } - - /* Reassembly the compound query so that it will be freed correctly - ** by the calling function */ - if( p->pPrior ){ - sqlite3SelectDelete(p->pPrior); - } - p->pPrior = pPrior; - - /*** TBD: Insert subroutine calls to close cursors on incomplete - **** subqueries ****/ - return SQLITE_OK; -} - #ifndef SQLITE_OMIT_VIEW /* Forward Declarations */ static void substExprList(sqlite3*, ExprList*, int, ExprList*); @@ -68503,26 +61117,6 @@ static void substSelect( ** subquery does not have both an ORDER BY and a LIMIT clause. ** (See ticket #2339) ** -** (16) The outer query is not an aggregate or the subquery does -** not contain ORDER BY. (Ticket #2942) This used to not matter -** until we introduced the group_concat() function. -** -** (17) The sub-query is not a compound select, or it is a UNION ALL -** compound clause made up entirely of non-aggregate queries, and -** the parent query: -** -** * is not itself part of a compound select, -** * is not an aggregate or DISTINCT query, and -** * has no other tables or sub-selects in the FROM clause. -** -** The parent and sub-query may contain WHERE clauses. Subject to -** rules (11), (13) and (14), they may also contain ORDER BY, -** LIMIT and OFFSET clauses. -** -** (18) If the sub-query is a compound select, then all terms of the -** ORDER by clause of the parent must be simple references to -** columns of the sub-query. -** ** In this routine, the "p" parameter is a pointer to the outer query. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates. @@ -68534,16 +61128,13 @@ static void substSelect( ** the subquery before this routine runs. */ static int flattenSubquery( - Parse *pParse, /* Parsing context */ + sqlite3 *db, /* Database connection */ Select *p, /* The parent or outer SELECT statement */ int iFrom, /* Index in p->pSrc->a[] of the inner subquery */ int isAgg, /* True if outer SELECT uses aggregate functions */ int subqueryIsAgg /* True if the subquery uses aggregate functions */ ){ - const char *zSavedAuthContext = pParse->zAuthContext; - Select *pParent; Select *pSub; /* The inner query or "subquery" */ - Select *pSub1; /* Pointer to the rightmost select in sub-query */ SrcList *pSrc; /* The FROM clause of the outer query */ SrcList *pSubSrc; /* The FROM clause of the subquery */ ExprList *pList; /* The result set of the outer query */ @@ -68551,7 +61142,6 @@ static int flattenSubquery( int i; /* Loop counter */ Expr *pWhere; /* The WHERE clause */ struct SrcList_item *pSubitem; /* The subquery */ - sqlite3 *db = pParse->db; /* Check to see if flattening is permitted. Return 0 if not. */ @@ -68559,7 +61149,6 @@ static int flattenSubquery( pSrc = p->pSrc; assert( pSrc && iFrom>=0 && iFromnSrc ); pSubitem = &pSrc->a[iFrom]; - iParent = pSubitem->iCursor; pSub = pSubitem->pSelect; assert( pSub!=0 ); if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */ @@ -68585,7 +61174,6 @@ static int flattenSubquery( if( (p->disallowOrderBy || p->pOrderBy) && pSub->pOrderBy ){ return 0; /* Restriction (11) */ } - if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */ /* Restriction 3: If the subquery is a join, make sure the subquery is ** not used as the right operand of an outer join. Examples of why this @@ -68620,114 +61208,41 @@ static int flattenSubquery( return 0; } - /* Restriction 17: If the sub-query is a compound SELECT, then it must - ** use only the UNION ALL operator. And none of the simple select queries - ** that make up the compound SELECT are allowed to be aggregate or distinct - ** queries. - */ - if( pSub->pPrior ){ - if( p->pPrior || isAgg || p->isDistinct || pSrc->nSrc!=1 ){ - return 0; - } - for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){ - if( pSub1->isAgg || pSub1->isDistinct - || (pSub1->pPrior && pSub1->op!=TK_ALL) - || !pSub1->pSrc || pSub1->pSrc->nSrc!=1 - ){ - return 0; - } - } - - /* Restriction 18. */ - if( p->pOrderBy ){ - int ii; - for(ii=0; iipOrderBy->nExpr; ii++){ - Expr *pExpr = p->pOrderBy->a[ii].pExpr; - if( pExpr->op!=TK_COLUMN || pExpr->iTable!=iParent ){ - return 0; - } - } - } - } - - pParse->zAuthContext = pSubitem->zName; - sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0); - pParse->zAuthContext = zSavedAuthContext; - - /* If the sub-query is a compound SELECT statement, then it must be - ** a UNION ALL and the parent query must be of the form: - ** - ** SELECT FROM () - ** - ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block - ** creates N copies of the parent query without any ORDER BY, LIMIT or - ** OFFSET clauses and joins them to the left-hand-side of the original - ** using UNION ALL operators. In this case N is the number of simple - ** select statements in the compound sub-query. - */ - for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){ - Select *pNew; - ExprList *pOrderBy = p->pOrderBy; - Expr *pLimit = p->pLimit; - Expr *pOffset = p->pOffset; - Select *pPrior = p->pPrior; - p->pOrderBy = 0; - p->pSrc = 0; - p->pPrior = 0; - p->pLimit = 0; - pNew = sqlite3SelectDup(db, p); - pNew->pPrior = pPrior; - p->pPrior = pNew; - p->pOrderBy = pOrderBy; - p->op = TK_ALL; - p->pSrc = pSrc; - p->pLimit = pLimit; - p->pOffset = pOffset; - p->pRightmost = 0; - pNew->pRightmost = 0; - } - /* If we reach this point, it means flattening is permitted for the ** iFrom-th entry of the FROM clause in the outer query. */ - pSub = pSub1 = pSubitem->pSelect; - for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){ - int nSubSrc = pSubSrc->nSrc; - int jointype = 0; - pSubSrc = pSub->pSrc; - pSrc = pParent->pSrc; - /* Move all of the FROM elements of the subquery into the - ** the FROM clause of the outer query. Before doing this, remember - ** the cursor number for the original outer query FROM element in - ** iParent. The iParent cursor will never be used. Subsequent code - ** will scan expressions looking for iParent references and replace - ** those references with expressions that resolve to the subquery FROM - ** elements we are now copying in. - */ - if( pSrc ){ - pSubitem = &pSrc->a[iFrom]; - nSubSrc = pSubSrc->nSrc; - jointype = pSubitem->jointype; - sqlite3DeleteTable(pSubitem->pTab); - sqlite3_free(pSubitem->zDatabase); - sqlite3_free(pSubitem->zName); - sqlite3_free(pSubitem->zAlias); - pSubitem->pTab = 0; - pSubitem->zDatabase = 0; - pSubitem->zName = 0; - pSubitem->zAlias = 0; - } - if( nSubSrc!=1 || !pSrc ){ + /* Move all of the FROM elements of the subquery into the + ** the FROM clause of the outer query. Before doing this, remember + ** the cursor number for the original outer query FROM element in + ** iParent. The iParent cursor will never be used. Subsequent code + ** will scan expressions looking for iParent references and replace + ** those references with expressions that resolve to the subquery FROM + ** elements we are now copying in. + */ + iParent = pSubitem->iCursor; + { + int nSubSrc = pSubSrc->nSrc; + int jointype = pSubitem->jointype; + + sqlite3DeleteTable(pSubitem->pTab); + sqlite3_free(pSubitem->zDatabase); + sqlite3_free(pSubitem->zName); + sqlite3_free(pSubitem->zAlias); + pSubitem->pTab = 0; + pSubitem->zDatabase = 0; + pSubitem->zName = 0; + pSubitem->zAlias = 0; + if( nSubSrc>1 ){ int extra = nSubSrc - 1; - for(i=(pSrc?1:0); ipSrc = 0; + p->pSrc = 0; return 1; } } - pParent->pSrc = pSrc; + p->pSrc = pSrc; for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){ pSrc->a[i] = pSrc->a[i-extra]; } @@ -68737,111 +61252,239 @@ static int flattenSubquery( memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i])); } pSrc->a[iFrom].jointype = jointype; - - /* Now begin substituting subquery result set expressions for - ** references to the iParent in the outer query. - ** - ** Example: - ** - ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; - ** \ \_____________ subquery __________/ / - ** \_____________________ outer query ______________________________/ - ** - ** We look at every expression in the outer query and every place we see - ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". - */ - pList = pParent->pEList; - for(i=0; inExpr; i++){ - Expr *pExpr; - if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ - pList->a[i].zName = - sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n); - } - } - substExprList(db, pParent->pEList, iParent, pSub->pEList); - if( isAgg ){ - substExprList(db, pParent->pGroupBy, iParent, pSub->pEList); - substExpr(db, pParent->pHaving, iParent, pSub->pEList); - } - if( pSub->pOrderBy ){ - assert( pParent->pOrderBy==0 ); - pParent->pOrderBy = pSub->pOrderBy; - pSub->pOrderBy = 0; - }else if( pParent->pOrderBy ){ - substExprList(db, pParent->pOrderBy, iParent, pSub->pEList); - } - if( pSub->pWhere ){ - pWhere = sqlite3ExprDup(db, pSub->pWhere); - }else{ - pWhere = 0; - } - if( subqueryIsAgg ){ - assert( pParent->pHaving==0 ); - pParent->pHaving = pParent->pWhere; - pParent->pWhere = pWhere; - substExpr(db, pParent->pHaving, iParent, pSub->pEList); - pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, - sqlite3ExprDup(db, pSub->pHaving)); - assert( pParent->pGroupBy==0 ); - pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy); - }else{ - substExpr(db, pParent->pWhere, iParent, pSub->pEList); - pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere); - } - - /* The flattened query is distinct if either the inner or the - ** outer query is distinct. - */ - pParent->isDistinct = pParent->isDistinct || pSub->isDistinct; - - /* - ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; - ** - ** One is tempted to try to add a and b to combine the limits. But this - ** does not work if either limit is negative. - */ - if( pSub->pLimit ){ - pParent->pLimit = pSub->pLimit; - pSub->pLimit = 0; + } + + /* Now begin substituting subquery result set expressions for + ** references to the iParent in the outer query. + ** + ** Example: + ** + ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b; + ** \ \_____________ subquery __________/ / + ** \_____________________ outer query ______________________________/ + ** + ** We look at every expression in the outer query and every place we see + ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10". + */ + pList = p->pEList; + for(i=0; inExpr; i++){ + Expr *pExpr; + if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){ + pList->a[i].zName = + sqlite3DbStrNDup(db, (char*)pExpr->span.z, pExpr->span.n); } } + substExprList(db, p->pEList, iParent, pSub->pEList); + if( isAgg ){ + substExprList(db, p->pGroupBy, iParent, pSub->pEList); + substExpr(db, p->pHaving, iParent, pSub->pEList); + } + if( pSub->pOrderBy ){ + assert( p->pOrderBy==0 ); + p->pOrderBy = pSub->pOrderBy; + pSub->pOrderBy = 0; + }else if( p->pOrderBy ){ + substExprList(db, p->pOrderBy, iParent, pSub->pEList); + } + if( pSub->pWhere ){ + pWhere = sqlite3ExprDup(db, pSub->pWhere); + }else{ + pWhere = 0; + } + if( subqueryIsAgg ){ + assert( p->pHaving==0 ); + p->pHaving = p->pWhere; + p->pWhere = pWhere; + substExpr(db, p->pHaving, iParent, pSub->pEList); + p->pHaving = sqlite3ExprAnd(db, p->pHaving, + sqlite3ExprDup(db, pSub->pHaving)); + assert( p->pGroupBy==0 ); + p->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy); + }else{ + substExpr(db, p->pWhere, iParent, pSub->pEList); + p->pWhere = sqlite3ExprAnd(db, p->pWhere, pWhere); + } + + /* The flattened query is distinct if either the inner or the + ** outer query is distinct. + */ + p->isDistinct = p->isDistinct || pSub->isDistinct; + + /* + ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y; + ** + ** One is tempted to try to add a and b to combine the limits. But this + ** does not work if either limit is negative. + */ + if( pSub->pLimit ){ + p->pLimit = pSub->pLimit; + pSub->pLimit = 0; + } /* Finially, delete what is left of the subquery and return ** success. */ - sqlite3SelectDelete(pSub1); - + sqlite3SelectDelete(pSub); return 1; } #endif /* SQLITE_OMIT_VIEW */ /* -** Analyze the SELECT statement passed as an argument to see if it -** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if -** it is, or 0 otherwise. At present, a query is considered to be -** a min()/max() query if: +** Analyze the SELECT statement passed in as an argument to see if it +** is a simple min() or max() query. If it is and this query can be +** satisfied using a single seek to the beginning or end of an index, +** then generate the code for this SELECT and return 1. If this is not a +** simple min() or max() query, then return 0; ** -** 1. There is a single object in the FROM clause. +** A simply min() or max() query looks like this: ** -** 2. There is a single expression in the result set, and it is -** either min(x) or max(x), where x is a column reference. +** SELECT min(a) FROM table; +** SELECT max(a) FROM table; +** +** The query may have only a single table in its FROM argument. There +** can be no GROUP BY or HAVING or WHERE clauses. The result set must +** be the min() or max() of a single column of the table. The column +** in the min() or max() function must be indexed. +** +** The parameters to this routine are the same as for sqlite3Select(). +** See the header comment on that routine for additional information. */ -static int minMaxQuery(Parse *pParse, Select *p){ +static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ Expr *pExpr; - ExprList *pEList = p->pEList; + int iCol; + Table *pTab; + Index *pIdx; + int base; + Vdbe *v; + int seekOp; + ExprList *pEList, *pList, eList; + struct ExprList_item eListItem; + SrcList *pSrc; + int brk; + int iDb; - if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL; + /* Check to see if this query is a simple min() or max() query. Return + ** zero if it is not. + */ + if( p->pGroupBy || p->pHaving || p->pWhere ) return 0; + pSrc = p->pSrc; + if( pSrc->nSrc!=1 ) return 0; + pEList = p->pEList; + if( pEList->nExpr!=1 ) return 0; pExpr = pEList->a[0].pExpr; - pEList = pExpr->pList; - if( pExpr->op!=TK_AGG_FUNCTION || pEList==0 || pEList->nExpr!=1 ) return 0; - if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL; - if( pExpr->token.n!=3 ) return WHERE_ORDERBY_NORMAL; + if( pExpr->op!=TK_AGG_FUNCTION ) return 0; + pList = pExpr->pList; + if( pList==0 || pList->nExpr!=1 ) return 0; + if( pExpr->token.n!=3 ) return 0; if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ - return WHERE_ORDERBY_MIN; + seekOp = OP_Rewind; }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ - return WHERE_ORDERBY_MAX; + seekOp = OP_Last; + }else{ + return 0; } - return WHERE_ORDERBY_NORMAL; + pExpr = pList->a[0].pExpr; + if( pExpr->op!=TK_COLUMN ) return 0; + iCol = pExpr->iColumn; + pTab = pSrc->a[0].pTab; + + /* This optimization cannot be used with virtual tables. */ + if( IsVirtual(pTab) ) return 0; + + /* If we get to here, it means the query is of the correct form. + ** Check to make sure we have an index and make pIdx point to the + ** appropriate index. If the min() or max() is on an INTEGER PRIMARY + ** key column, no index is necessary so set pIdx to NULL. If no + ** usable index is found, return 0. + */ + if( iCol<0 ){ + pIdx = 0; + }else{ + CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr); + if( pColl==0 ) return 0; + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ + assert( pIdx->nColumn>=1 ); + if( pIdx->aiColumn[0]==iCol && + 0==sqlite3StrICmp(pIdx->azColl[0], pColl->zName) ){ + break; + } + } + if( pIdx==0 ) return 0; + } + + /* Identify column types if we will be using the callback. This + ** step is skipped if the output is going to a table or a memory cell. + ** The column names have already been generated in the calling function. + */ + v = sqlite3GetVdbe(pParse); + if( v==0 ) return 0; + + /* If the output is destined for a temporary table, open that table. + */ + if( eDest==SRT_EphemTab ){ + sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 1); + } + + /* Generating code to find the min or the max. Basically all we have + ** to do is find the first or the last entry in the chosen index. If + ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first + ** or last entry in the main table. + */ + iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); + assert( iDb>=0 || pTab->isEphem ); + sqlite3CodeVerifySchema(pParse, iDb); + sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); + base = pSrc->a[0].iCursor; + brk = sqlite3VdbeMakeLabel(v); + computeLimitRegisters(pParse, p, brk); + if( pSrc->a[0].pSelect==0 ){ + sqlite3OpenTable(pParse, base, iDb, pTab, OP_OpenRead); + } + if( pIdx==0 ){ + sqlite3VdbeAddOp(v, seekOp, base, 0); + }else{ + /* Even though the cursor used to open the index here is closed + ** as soon as a single value has been read from it, allocate it + ** using (pParse->nTab++) to prevent the cursor id from being + ** reused. This is important for statements of the form + ** "INSERT INTO x SELECT max() FROM x". + */ + int iIdx; + KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); + iIdx = pParse->nTab++; + assert( pIdx->pSchema==pTab->pSchema ); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, + (char*)pKey, P3_KEYINFO_HANDOFF); + if( seekOp==OP_Rewind ){ + sqlite3VdbeAddOp(v, OP_Null, 0, 0); + sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0); + seekOp = OP_MoveGt; + } + if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){ + /* Ticket #2514: invert the seek operator if we are using + ** a descending index. */ + if( seekOp==OP_Last ){ + seekOp = OP_Rewind; + }else{ + assert( seekOp==OP_MoveGt ); + seekOp = OP_MoveLt; + } + } + sqlite3VdbeAddOp(v, seekOp, iIdx, 0); + sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0); + sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); + sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); + } + eList.nExpr = 1; + memset(&eListItem, 0, sizeof(eListItem)); + eList.a = &eListItem; + eList.a[0].pExpr = pExpr; + selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, brk, brk, 0); + sqlite3VdbeResolveLabel(v, brk); + sqlite3VdbeAddOp(v, OP_Close, base, 0); + + return 1; } /* @@ -68989,10 +61632,10 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ return; } for(i=0; inColumn; i++){ - sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); + sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0); } for(pFunc=pAggInfo->aFunc, i=0; inFunc; i++, pFunc++){ - sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); + sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0); if( pFunc->iDistinct>=0 ){ Expr *pE = pFunc->pExpr; if( pE->pList==0 || pE->pList->nExpr!=1 ){ @@ -69001,8 +61644,8 @@ static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){ pFunc->iDistinct = -1; }else{ KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, - (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0, + (char*)pKeyInfo, P3_KEYINFO_HANDOFF); } } } @@ -69018,8 +61661,8 @@ static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){ struct AggInfo_func *pF; for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ ExprList *pList = pF->pExpr->pList; - sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, - (void*)pF->pFunc, P4_FUNCDEF); + sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, + (void*)pF->pFunc, P3_FUNCDEF); } } @@ -69037,20 +61680,17 @@ static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ for(i=0, pF=pAggInfo->aFunc; inFunc; i++, pF++){ int nArg; int addrNext = 0; - int regAgg; ExprList *pList = pF->pExpr->pList; if( pList ){ nArg = pList->nExpr; - regAgg = sqlite3GetTempRange(pParse, nArg); - sqlite3ExprCodeExprList(pParse, pList, regAgg, 0); + sqlite3ExprCodeExprList(pParse, pList); }else{ nArg = 0; - regAgg = 0; } if( pF->iDistinct>=0 ){ addrNext = sqlite3VdbeMakeLabel(v); assert( nArg==1 ); - codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); + codeDistinct(v, pF->iDistinct, addrNext, 1); } if( pF->pFunc->needCollSeq ){ CollSeq *pColl = 0; @@ -69063,86 +61703,44 @@ static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){ if( !pColl ){ pColl = pParse->db->pDfltColl; } - sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); + sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); } - sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, - (void*)pF->pFunc, P4_FUNCDEF); - sqlite3VdbeChangeP5(v, nArg); - sqlite3ReleaseTempRange(pParse, regAgg, nArg); - sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg); + sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF); if( addrNext ){ sqlite3VdbeResolveLabel(v, addrNext); } } for(i=0, pC=pAggInfo->aCol; inAccumulator; i++, pC++){ - sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); + sqlite3ExprCode(pParse, pC->pExpr); + sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1); } pAggInfo->directMode = 0; } -#if 0 -/* -** This function is used when a SELECT statement is used to create a -** temporary table for iterating through when running an INSTEAD OF -** UPDATE or INSTEAD OF DELETE trigger. -** -** If possible, the SELECT statement is modified so that NULL values -** are stored in the temporary table for all columns for which the -** corresponding bit in argument mask is not set. If mask takes the -** special value 0xffffffff, then all columns are populated. -*/ -SQLITE_PRIVATE void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){ - if( p && !p->pPrior && !p->isDistinct && mask!=0xffffffff ){ - ExprList *pEList; - int i; - sqlite3SelectResolve(pParse, p, 0); - pEList = p->pEList; - for(i=0; pEList && inExpr && i<32; i++){ - if( !(mask&((u32)1<a[i].pExpr); - pEList->a[i].pExpr = sqlite3Expr(pParse->db, TK_NULL, 0, 0, 0); - } - } - } -} -#endif /* ** Generate code for the given SELECT statement. ** ** The results are distributed in various ways depending on the -** contents of the SelectDest structure pointed to by argument pDest -** as follows: +** value of eDest and iParm. ** -** pDest->eDest Result +** eDest Value Result ** ------------ ------------------------------------------- ** SRT_Callback Invoke the callback for each row of the result. ** -** SRT_Mem Store first result in memory cell pDest->iParm +** SRT_Mem Store first result in memory cell iParm ** -** SRT_Set Store results as keys of table pDest->iParm. -** Apply the affinity pDest->affinity before storing them. +** SRT_Set Store results as keys of table iParm. ** -** SRT_Union Store results as a key in a temporary table pDest->iParm. +** SRT_Union Store results as a key in a temporary table iParm ** -** SRT_Except Remove results from the temporary table pDest->iParm. +** SRT_Except Remove results from the temporary table iParm. ** -** SRT_Table Store results in temporary table pDest->iParm +** SRT_Table Store results in temporary table iParm ** -** SRT_EphemTab Create an temporary table pDest->iParm and store -** the result there. The cursor is left open after -** returning. -** -** SRT_Coroutine Invoke a co-routine to compute a single row of -** the result -** -** SRT_Exists Store a 1 in memory cell pDest->iParm if the result -** set is not empty. -** -** SRT_Discard Throw the results away. -** -** See the selectInnerLoop() function for a canonical listing of the -** allowed values of eDest and their meanings. +** The table above is incomplete. Additional eDist value have be added +** since this comment was written. See the selectInnerLoop() function for +** a complete listing of the allowed values of eDest and their meanings. ** ** This routine returns the number of errors. If any errors are ** encountered, then an appropriate error message is left in @@ -69175,10 +61773,12 @@ SQLITE_PRIVATE void sqlite3SelectMask(Parse *pParse, Select *p, u32 mask){ SQLITE_PRIVATE int sqlite3Select( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ - SelectDest *pDest, /* What to do with the query results */ + int eDest, /* How to dispose of the results */ + int iParm, /* A parameter used by the eDest disposal method */ Select *pParent, /* Another SELECT for which this is a sub-query */ int parentTab, /* Index in pParent->pSrc of this query */ - int *pParentAgg /* True if pParent uses aggregate functions */ + int *pParentAgg, /* True if pParent uses aggregate functions */ + char *aff /* If eDest is SRT_Union, the affinity string */ ){ int i, j; /* Loop counters */ WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */ @@ -69206,26 +61806,43 @@ SQLITE_PRIVATE int sqlite3Select( memset(&sAggInfo, 0, sizeof(sAggInfo)); pOrderBy = p->pOrderBy; - if( IgnorableOrderby(pDest) ){ + if( IgnorableOrderby(eDest) ){ p->pOrderBy = 0; - - /* In these cases the DISTINCT operator makes no difference to the - ** results, so remove it if it were specified. - */ - assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || - pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard); - p->isDistinct = 0; } if( sqlite3SelectResolve(pParse, p, 0) ){ goto select_end; } p->pOrderBy = pOrderBy; +#ifndef SQLITE_OMIT_COMPOUND_SELECT + /* If there is are a sequence of queries, do the earlier ones first. + */ + if( p->pPrior ){ + if( p->pRightmost==0 ){ + Select *pLoop, *pRight = 0; + int cnt = 0; + for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ + pLoop->pRightmost = p; + pLoop->pNext = pRight; + pRight = pLoop; + } + if( SQLITE_MAX_COMPOUND_SELECT>0 && cnt>SQLITE_MAX_COMPOUND_SELECT ){ + sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); + return 1; + } + } + return multiSelect(pParse, p, eDest, iParm, aff); + } +#endif /* Make local copies of the parameters for this query. */ pTabList = p->pSrc; + pWhere = p->pWhere; + pGroupBy = p->pGroupBy; + pHaving = p->pHaving; isAgg = p->isAgg; + isDistinct = p->isDistinct; pEList = p->pEList; if( pEList==0 ) goto select_end; @@ -69235,9 +61852,18 @@ SQLITE_PRIVATE int sqlite3Select( */ if( pParse->nErr>0 ) goto select_end; + /* If writing to memory or generating a set + ** only a single column may be output. + */ +#ifndef SQLITE_OMIT_SUBQUERY + if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ + goto select_end; + } +#endif + /* ORDER BY is ignored for some destinations. */ - if( IgnorableOrderby(pDest) ){ + if( IgnorableOrderby(eDest) ){ pOrderBy = 0; } @@ -69249,24 +61875,20 @@ SQLITE_PRIVATE int sqlite3Select( /* Generate code for all sub-queries in the FROM clause */ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) - for(i=0; !p->pPrior && inSrc; i++){ + for(i=0; inSrc; i++){ + const char *zSavedAuthContext = 0; + int needRestoreContext; struct SrcList_item *pItem = &pTabList->a[i]; - SelectDest dest; - Select *pSub = pItem->pSelect; - int isAggSub; - char *zName = pItem->zName; - if( pSub==0 || pItem->isPopulated ) continue; - if( zName!=0 ){ /* An sql view */ - const char *zSavedAuthContext = pParse->zAuthContext; - pParse->zAuthContext = zName; - rc = sqlite3SelectResolve(pParse, pSub, 0); - pParse->zAuthContext = zSavedAuthContext; - if( rc ){ - goto select_end; - } + if( pItem->pSelect==0 || pItem->isPopulated ) continue; + if( pItem->zName!=0 ){ + zSavedAuthContext = pParse->zAuthContext; + pParse->zAuthContext = pItem->zName; + needRestoreContext = 1; + }else{ + needRestoreContext = 0; } - +#if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 /* Increment Parse.nHeight by the height of the largest expression ** tree refered to by this, the parent select. The child select ** may contain expression trees of at most @@ -69275,62 +61897,44 @@ SQLITE_PRIVATE int sqlite3Select( ** an exact limit. */ pParse->nHeight += sqlite3SelectExprHeight(p); - - /* Check to see if the subquery can be absorbed into the parent. */ - isAggSub = pSub->isAgg; - if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){ - if( isAggSub ){ - p->isAgg = isAgg = 1; - } - i = -1; - }else{ - sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); - sqlite3Select(pParse, pSub, &dest, p, i, &isAgg); - } - if( pParse->nErr || db->mallocFailed ){ +#endif + sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab, + pItem->iCursor, p, i, &isAgg, 0); + if( db->mallocFailed ){ goto select_end; } +#if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 pParse->nHeight -= sqlite3SelectExprHeight(p); +#endif + if( needRestoreContext ){ + pParse->zAuthContext = zSavedAuthContext; + } pTabList = p->pSrc; - if( !IgnorableOrderby(pDest) ){ + pWhere = p->pWhere; + if( !IgnorableOrderby(eDest) ){ pOrderBy = p->pOrderBy; } - } - pEList = p->pEList; -#endif - pWhere = p->pWhere; - pGroupBy = p->pGroupBy; - pHaving = p->pHaving; - isDistinct = p->isDistinct; - -#ifndef SQLITE_OMIT_COMPOUND_SELECT - /* If there is are a sequence of queries, do the earlier ones first. - */ - if( p->pPrior ){ - if( p->pRightmost==0 ){ - Select *pLoop, *pRight = 0; - int cnt = 0; - int mxSelect; - for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){ - pLoop->pRightmost = p; - pLoop->pNext = pRight; - pRight = pLoop; - } - mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT]; - if( mxSelect && cnt>mxSelect ){ - sqlite3ErrorMsg(pParse, "too many terms in compound SELECT"); - return 1; - } - } - return multiSelect(pParse, p, pDest); + pGroupBy = p->pGroupBy; + pHaving = p->pHaving; + isDistinct = p->isDistinct; } #endif - /* If writing to memory or generating a set - ** only a single column may be output. + /* Check for the special case of a min() or max() function by itself + ** in the result set. */ -#ifndef SQLITE_OMIT_SUBQUERY - if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ + if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ + rc = 0; + goto select_end; + } + + /* Check to see if this is a subquery that can be "flattened" into its parent. + ** If flattening is a possiblity, do so and return immediately. + */ +#ifndef SQLITE_OMIT_VIEW + if( pParent && pParentAgg && + flattenSubquery(db, pParent, parentTab, *pParentAgg, isAgg) ){ + if( isAgg ) *pParentAgg = 1; goto select_end; } #endif @@ -69354,20 +61958,21 @@ SQLITE_PRIVATE int sqlite3Select( */ if( pOrderBy ){ KeyInfo *pKeyInfo; + if( pParse->nErr ){ + goto select_end; + } pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); pOrderBy->iECursor = pParse->nTab++; p->addrOpenEphm[2] = addrSortIndex = - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, - pOrderBy->iECursor, pOrderBy->nExpr+2, 0, - (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); }else{ addrSortIndex = -1; } /* If the output is destined for a temporary table, open that table. */ - if( pDest->eDest==SRT_EphemTab ){ - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); + if( eDest==SRT_EphemTab ){ + sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr); } /* Set the limiter. @@ -69382,8 +61987,8 @@ SQLITE_PRIVATE int sqlite3Select( assert( isAgg || pGroupBy ); distinct = pParse->nTab++; pKeyInfo = keyInfoFromExprList(pParse, p->pEList); - sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, - (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0, + (char*)pKeyInfo, P3_KEYINFO_HANDOFF); }else{ distinct = -1; } @@ -69393,7 +61998,7 @@ SQLITE_PRIVATE int sqlite3Select( /* This case is for non-aggregate queries ** Begin the database scan */ - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy); if( pWInfo==0 ) goto select_end; /* If sorting index that was created by a prior OP_OpenEphemeral @@ -69408,8 +62013,10 @@ SQLITE_PRIVATE int sqlite3Select( /* Use the standard inner loop */ assert(!isDistinct); - selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, - pWInfo->iContinue, pWInfo->iBreak); + if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, eDest, + iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ + goto select_end; + } /* End the database scan loop. */ @@ -69429,14 +62036,14 @@ SQLITE_PRIVATE int sqlite3Select( /* The following variables hold addresses or labels for parts of the ** virtual machine program we are putting together */ int addrOutputRow; /* Start of subroutine that outputs a result row */ - int regOutputRow; /* Return address register for output subroutine */ int addrSetAbort; /* Set the abort flag and return */ int addrInitializeLoop; /* Start of code that initializes the input loop */ int addrTopOfLoop; /* Top of the input loop */ + int addrGroupByChange; /* Code that runs when any GROUP BY term changes */ + int addrProcessRow; /* Code to process a single input row */ int addrEnd; /* End of all processing */ int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */ int addrReset; /* Subroutine for resetting the accumulator */ - int regReset; /* Return address register for reset subroutine */ addrEnd = sqlite3VdbeMakeLabel(v); @@ -69450,14 +62057,20 @@ SQLITE_PRIVATE int sqlite3Select( sNC.pAggInfo = &sAggInfo; sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; sAggInfo.pGroupBy = pGroupBy; - sqlite3ExprAnalyzeAggList(&sNC, pEList); - sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); - if( pHaving ){ - sqlite3ExprAnalyzeAggregates(&sNC, pHaving); + if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){ + goto select_end; + } + if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){ + goto select_end; + } + if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){ + goto select_end; } sAggInfo.nAccumulator = sAggInfo.nColumn; for(i=0; ipList); + if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){ + goto select_end; + } } if( db->mallocFailed ) goto select_end; @@ -69466,11 +62079,13 @@ SQLITE_PRIVATE int sqlite3Select( */ if( pGroupBy ){ KeyInfo *pKeyInfo; /* Keying information for the group by clause */ - int j1; /* Create labels that we will be needing */ + addrInitializeLoop = sqlite3VdbeMakeLabel(v); + addrGroupByChange = sqlite3VdbeMakeLabel(v); + addrProcessRow = sqlite3VdbeMakeLabel(v); /* If there is a GROUP BY clause we might need a sorting index to ** implement it. Allocate that sorting index now. If it turns out @@ -69479,23 +62094,24 @@ SQLITE_PRIVATE int sqlite3Select( */ sAggInfo.sortingIdx = pParse->nTab++; pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); - addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, - sAggInfo.sortingIdx, sAggInfo.nSortingColumn, - 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); + addrSortingIdx = + sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx, + sAggInfo.nSortingColumn, + (char*)pKeyInfo, P3_KEYINFO_HANDOFF); /* Initialize memory locations used by GROUP BY aggregate processing */ - iUseFlag = ++pParse->nMem; - iAbortFlag = ++pParse->nMem; - iAMem = pParse->nMem + 1; + iUseFlag = pParse->nMem++; + iAbortFlag = pParse->nMem++; + iAMem = pParse->nMem; pParse->nMem += pGroupBy->nExpr; - iBMem = pParse->nMem + 1; + iBMem = pParse->nMem; pParse->nMem += pGroupBy->nExpr; - sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag); - VdbeComment((v, "clear abort flag")); - sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag); - VdbeComment((v, "indicate accumulator empty")); - sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInitializeLoop); + sqlite3VdbeAddOp(v, OP_MemInt, 0, iAbortFlag); + VdbeComment((v, "# clear abort flag")); + sqlite3VdbeAddOp(v, OP_MemInt, 0, iUseFlag); + VdbeComment((v, "# indicate accumulator empty")); + sqlite3VdbeAddOp(v, OP_Goto, 0, addrInitializeLoop); /* Generate a subroutine that outputs a single row of the result ** set. This subroutine first looks at the iUseFlag. If iUseFlag @@ -69505,30 +62121,31 @@ SQLITE_PRIVATE int sqlite3Select( ** order to signal the caller to abort. */ addrSetAbort = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); - VdbeComment((v, "set abort flag")); - regOutputRow = ++pParse->nMem; - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag); + VdbeComment((v, "# set abort flag")); + sqlite3VdbeAddOp(v, OP_Return, 0, 0); addrOutputRow = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); - VdbeComment((v, "Groupby result generator entry point")); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); + sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2); + VdbeComment((v, "# Groupby result generator entry point")); + sqlite3VdbeAddOp(v, OP_Return, 0, 0); finalizeAggFunctions(pParse, &sAggInfo); if( pHaving ){ - sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1); } - selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, - distinct, pDest, - addrOutputRow+1, addrSetAbort); - sqlite3VdbeAddOp1(v, OP_Return, regOutputRow); - VdbeComment((v, "end groupby result generator")); + rc = selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, + distinct, eDest, iParm, + addrOutputRow+1, addrSetAbort, aff); + if( rc ){ + goto select_end; + } + sqlite3VdbeAddOp(v, OP_Return, 0, 0); + VdbeComment((v, "# end groupby result generator")); /* Generate a subroutine that will reset the group-by accumulator */ addrReset = sqlite3VdbeCurrentAddr(v); - regReset = ++pParse->nMem; resetAccumulator(pParse, &sAggInfo); - sqlite3VdbeAddOp1(v, OP_Return, regReset); + sqlite3VdbeAddOp(v, OP_Return, 0, 0); /* Begin a loop that will extract all source rows in GROUP BY order. ** This might involve two separate loops with an OP_Sort in between, or @@ -69536,8 +62153,8 @@ SQLITE_PRIVATE int sqlite3Select( ** in the right order to begin with. */ sqlite3VdbeResolveLabel(v, addrInitializeLoop); - sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0); + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy); if( pWInfo==0 ) goto select_end; if( pGroupBy==0 ){ /* The optimizer is able to deliver rows in group by order so @@ -69552,45 +62169,21 @@ SQLITE_PRIVATE int sqlite3Select( ** then loop over the sorting index in order to get the output ** in sorted order */ - int regBase; - int regRecord; - int nCol; - int nGroupBy; - groupBySort = 1; - nGroupBy = pGroupBy->nExpr; - nCol = nGroupBy + 1; - j = nGroupBy+1; - for(i=0; i=j ){ - nCol++; - j++; - } - } - regBase = sqlite3GetTempRange(pParse, nCol); - sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0); - sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); - j = nGroupBy+1; + sqlite3ExprCodeExprList(pParse, pGroupBy); + sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0); + j = pGroupBy->nExpr+1; for(i=0; iiSorterColumn>=j ){ - int r1 = j + regBase; - int r2 = sqlite3ExprCodeGetColumn(pParse, - pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0); - if( r1!=r2 ){ - sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1); - } - j++; - } + if( pCol->iSorterColumnpTab, pCol->iColumn, pCol->iTable); + j++; } - regRecord = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord); - sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord); - sqlite3ReleaseTempReg(pParse, regRecord); - sqlite3ReleaseTempRange(pParse, regBase, nCol); + sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0); + sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0); sqlite3WhereEnd(pWInfo); - sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); - VdbeComment((v, "GROUP BY sort")); + sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); + VdbeComment((v, "# GROUP BY sort")); sAggInfo.useSortingIdx = 1; } @@ -69602,19 +62195,28 @@ SQLITE_PRIVATE int sqlite3Select( addrTopOfLoop = sqlite3VdbeCurrentAddr(v); for(j=0; jnExpr; j++){ if( groupBySort ){ - sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j); + sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j); }else{ sAggInfo.directMode = 1; - sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); + sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr); } + sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, jnExpr-1); + } + for(j=pGroupBy->nExpr-1; j>=0; j--){ + if( jnExpr-1 ){ + sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0); + } + sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0); + if( j==0 ){ + sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow); + }else{ + sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange); + } + sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ); } - sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr, - (char*)pKeyInfo, P4_KEYINFO); - j1 = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); /* Generate code that runs whenever the GROUP BY changes. - ** Changes in the GROUP BY are detected by the previous code + ** Change in the GROUP BY are detected by the previous code ** block. If there were no changes, this block is skipped. ** ** This code copies current group by terms in b0,b1,b2,... @@ -69622,26 +62224,29 @@ SQLITE_PRIVATE int sqlite3Select( ** and resets the aggregate accumulator registers in preparation ** for the next GROUP BY batch. */ - sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr); - sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); - VdbeComment((v, "output one row")); - sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); - VdbeComment((v, "check abort flag")); - sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset); - VdbeComment((v, "reset accumulator")); + sqlite3VdbeResolveLabel(v, addrGroupByChange); + for(j=0; jnExpr; j++){ + sqlite3VdbeAddOp(v, OP_MemMove, iAMem+j, iBMem+j); + } + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); + VdbeComment((v, "# output one row")); + sqlite3VdbeAddOp(v, OP_IfMemPos, iAbortFlag, addrEnd); + VdbeComment((v, "# check abort flag")); + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); + VdbeComment((v, "# reset accumulator")); /* Update the aggregate accumulators based on the content of ** the current row */ - sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeResolveLabel(v, addrProcessRow); updateAccumulator(pParse, &sAggInfo); - sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); - VdbeComment((v, "indicate data in accumulator")); + sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag); + VdbeComment((v, "# indicate data in accumulator")); /* End of the loop */ if( groupBySort ){ - sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); + sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); }else{ sqlite3WhereEnd(pWInfo); sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); @@ -69649,74 +62254,27 @@ SQLITE_PRIVATE int sqlite3Select( /* Output the final row of result */ - sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow); - VdbeComment((v, "output final row")); + sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); + VdbeComment((v, "# output final row")); } /* endif pGroupBy */ else { - ExprList *pMinMax = 0; - ExprList *pDel = 0; - u8 flag; - - /* Check if the query is of one of the following forms: - ** - ** SELECT min(x) FROM ... - ** SELECT max(x) FROM ... - ** - ** If it is, then ask the code in where.c to attempt to sort results - ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. - ** If where.c is able to produce results sorted in this order, then - ** add vdbe code to break out of the processing loop after the - ** first iteration (since the first iteration of the loop is - ** guaranteed to operate on the row with the minimum or maximum - ** value of x, the only row required). - ** - ** A special flag must be passed to sqlite3WhereBegin() to slightly - ** modify behaviour as follows: - ** - ** + If the query is a "SELECT min(x)", then the loop coded by - ** where.c should not iterate over any values with a NULL value - ** for x. - ** - ** + The optimizer code in where.c (the thing that decides which - ** index or indices to use) should place a different priority on - ** satisfying the 'ORDER BY' clause than it does in other cases. - ** Refer to code and comments in where.c for details. - */ - flag = minMaxQuery(pParse, p); - if( flag ){ - pDel = pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->pList); - if( pMinMax && !db->mallocFailed ){ - pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN; - pMinMax->a[0].pExpr->op = TK_COLUMN; - } - } - /* This case runs if the aggregate has no GROUP BY clause. The ** processing is much simpler since there is only a single row ** of output. */ resetAccumulator(pParse, &sAggInfo); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag); - if( pWInfo==0 ){ - sqlite3ExprListDelete(pDel); - goto select_end; - } + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); + if( pWInfo==0 ) goto select_end; updateAccumulator(pParse, &sAggInfo); - if( !pMinMax && flag ){ - sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); - VdbeComment((v, "%s() by index",(flag==WHERE_ORDERBY_MIN?"min":"max"))); - } sqlite3WhereEnd(pWInfo); finalizeAggFunctions(pParse, &sAggInfo); pOrderBy = 0; if( pHaving ){ - sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1); } selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, - pDest, addrEnd, addrEnd); - - sqlite3ExprListDelete(pDel); + eDest, iParm, addrEnd, addrEnd, aff); } sqlite3VdbeResolveLabel(v, addrEnd); @@ -69726,7 +62284,7 @@ SQLITE_PRIVATE int sqlite3Select( ** and send them to the callback one by one. */ if( pOrderBy ){ - generateSortTail(pParse, p, v, pEList->nExpr, pDest); + generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); } #ifndef SQLITE_OMIT_SUBQUERY @@ -69759,7 +62317,7 @@ select_end: /* Identify column names if we will be using them in a callback. This ** step is skipped if the output is going to some other destination. */ - if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){ + if( rc==SQLITE_OK && eDest==SRT_Callback ){ generateColumnNames(pParse, pTabList, pEList); } @@ -69883,8 +62441,6 @@ SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){ ** ** These routines are in a separate files so that they will not be linked ** if they are not used. -** -** $Id: table.c,v 1.36 2008/07/08 22:28:49 shane Exp $ */ #ifndef SQLITE_OMIT_GET_TABLE @@ -69937,15 +62493,17 @@ static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){ if( p->nRow==0 ){ p->nColumn = nCol; for(i=0; iazResult[p->nData++] = z; } }else if( p->nColumn!=nCol ){ - sqlite3_free(p->zErrMsg); - p->zErrMsg = sqlite3_mprintf( - "sqlite3_get_table() called with two or more incompatible queries" - ); + sqlite3SetString(&p->zErrMsg, + "sqlite3_get_table() called with two or more incompatible queries", + (char*)0); p->rc = SQLITE_ERROR; return 1; } @@ -69993,7 +62551,7 @@ SQLITE_API int sqlite3_get_table( ){ int rc; TabResult res; - + if( pazResult==0 ){ return SQLITE_ERROR; } *pazResult = 0; if( pnColumn ) *pnColumn = 0; if( pnRow ) *pnRow = 0; @@ -70004,15 +62562,19 @@ SQLITE_API int sqlite3_get_table( res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; - res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc ); - if( res.azResult==0 ){ - db->errCode = SQLITE_NOMEM; - return SQLITE_NOMEM; - } + res.azResult = sqlite3_malloc( sizeof(char*)*res.nAlloc ); + if( res.azResult==0 ) return SQLITE_NOMEM; res.azResult[0] = 0; rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); - assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); - res.azResult[0] = SQLITE_INT_TO_PTR(res.nData); +#ifndef NDEBUG + sqlite3_mutex_enter(db->mutex); + assert((rc&db->errMask)==rc && (res.rc&db->errMask)==res.rc); + sqlite3_mutex_leave(db->mutex); +#endif + if( res.azResult ){ + assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); + res.azResult[0] = (char*)res.nData; + } if( (rc&0xff)==SQLITE_ABORT ){ sqlite3_free_table(&res.azResult[1]); if( res.zErrMsg ){ @@ -70022,7 +62584,9 @@ SQLITE_API int sqlite3_get_table( } sqlite3_free(res.zErrMsg); } - db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ + sqlite3_mutex_enter(db->mutex); + db->errCode = res.rc; + sqlite3_mutex_leave(db->mutex); return res.rc; } sqlite3_free(res.zErrMsg); @@ -70035,7 +62599,6 @@ SQLITE_API int sqlite3_get_table( azNew = sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) ); if( azNew==0 ){ sqlite3_free_table(&res.azResult[1]); - db->errCode = SQLITE_NOMEM; return SQLITE_NOMEM; } res.nAlloc = res.nData+1; @@ -70056,8 +62619,8 @@ SQLITE_API void sqlite3_free_table( if( azResult ){ int i, n; azResult--; - assert( azResult!=0 ); - n = SQLITE_PTR_TO_INT(azResult[0]); + if( azResult==0 ) return; + n = (int)azResult[0]; for(i=1; iinit.busy ){ + static const VdbeOpList insertTrig[] = { + { OP_NewRowid, 0, 0, 0 }, + { OP_String8, 0, 0, "trigger" }, + { OP_String8, 0, 0, 0 }, /* 2: trigger name */ + { OP_String8, 0, 0, 0 }, /* 3: table name */ + { OP_Integer, 0, 0, 0 }, + { OP_String8, 0, 0, "CREATE TRIGGER "}, + { OP_String8, 0, 0, 0 }, /* 6: SQL */ + { OP_Concat, 0, 0, 0 }, + { OP_MakeRecord, 5, 0, "aaada" }, + { OP_Insert, 0, 0, 0 }, + }; + int addr; Vdbe *v; - char *z; /* Make an entry in the sqlite_master table */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto triggerfinish_cleanup; sqlite3BeginWriteOperation(pParse, 0, iDb); - z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n); - sqlite3NestedParse(pParse, - "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')", - db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name, - pTrig->table, z); - sqlite3_free(z); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf( - db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC + sqlite3OpenMasterTable(pParse, iDb); + addr = sqlite3VdbeAddOpList(v, ArraySize(insertTrig), insertTrig); + sqlite3VdbeChangeP3(v, addr+2, pTrig->name, 0); + sqlite3VdbeChangeP3(v, addr+3, pTrig->table, 0); + sqlite3VdbeChangeP3(v, addr+6, (char*)pAll->z, pAll->n); + sqlite3ChangeCookie(db, v, iDb); + sqlite3VdbeAddOp(v, OP_Close, 0, 0); + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, sqlite3MPrintf( + db, "type='trigger' AND name='%q'", pTrig->name), P3_DYNAMIC ); } @@ -70593,12 +63166,12 @@ SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ int base; static const VdbeOpList dropTrigger[] = { { OP_Rewind, 0, ADDR(9), 0}, - { OP_String8, 0, 1, 0}, /* 1 */ - { OP_Column, 0, 1, 2}, - { OP_Ne, 2, ADDR(8), 1}, - { OP_String8, 0, 1, 0}, /* 4: "trigger" */ - { OP_Column, 0, 0, 2}, - { OP_Ne, 2, ADDR(8), 1}, + { OP_String8, 0, 0, 0}, /* 1 */ + { OP_Column, 0, 1, 0}, + { OP_Ne, 0, ADDR(8), 0}, + { OP_String8, 0, 0, "trigger"}, + { OP_Column, 0, 0, 0}, + { OP_Ne, 0, ADDR(8), 0}, { OP_Delete, 0, 0, 0}, { OP_Next, 0, ADDR(1), 0}, /* 8 */ }; @@ -70606,11 +63179,10 @@ SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){ sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3OpenMasterTable(pParse, iDb); base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger); - sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0); - sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC); - sqlite3ChangeCookie(pParse, iDb); - sqlite3VdbeAddOp2(v, OP_Close, 0, 0); - sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0); + sqlite3VdbeChangeP3(v, base+1, pTrigger->name, 0); + sqlite3ChangeCookie(db, v, iDb); + sqlite3VdbeAddOp(v, OP_Close, 0, 0); + sqlite3VdbeOp3(v, OP_DropTrigger, iDb, 0, pTrigger->name, 0); } } @@ -70735,8 +63307,8 @@ static int codeTriggerProgram( assert( pTriggerStep!=0 ); assert( v!=0 ); - sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0); - VdbeComment((v, "begin trigger %s", pStepList->pTrig->name)); + sqlite3VdbeAddOp(v, OP_ContextPush, 0, 0); + VdbeComment((v, "# begin trigger %s", pStepList->pTrig->name)); while( pTriggerStep ){ orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin; pParse->trigStack->orconf = orconf; @@ -70744,11 +63316,8 @@ static int codeTriggerProgram( case TK_SELECT: { Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect); if( ss ){ - SelectDest dest; - - sqlite3SelectDestInit(&dest, SRT_Discard, 0); sqlite3SelectResolve(pParse, ss, 0); - sqlite3Select(pParse, ss, &dest, 0, 0, 0); + sqlite3Select(pParse, ss, SRT_Discard, 0, 0, 0, 0, 0); sqlite3SelectDelete(ss); } break; @@ -70756,31 +63325,31 @@ static int codeTriggerProgram( case TK_UPDATE: { SrcList *pSrc; pSrc = targetSrcList(pParse, pTriggerStep); - sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); + sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0); sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db, pTriggerStep->pExprList), sqlite3ExprDup(db, pTriggerStep->pWhere), orconf); - sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); + sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0); break; } case TK_INSERT: { SrcList *pSrc; pSrc = targetSrcList(pParse, pTriggerStep); - sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); + sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0); sqlite3Insert(pParse, pSrc, sqlite3ExprListDup(db, pTriggerStep->pExprList), sqlite3SelectDup(db, pTriggerStep->pSelect), sqlite3IdListDup(db, pTriggerStep->pIdList), orconf); - sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); + sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0); break; } case TK_DELETE: { SrcList *pSrc; - sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); + sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0); pSrc = targetSrcList(pParse, pTriggerStep); sqlite3DeleteFrom(pParse, pSrc, sqlite3ExprDup(db, pTriggerStep->pWhere)); - sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); + sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0); break; } default: @@ -70788,8 +63357,8 @@ static int codeTriggerProgram( } pTriggerStep = pTriggerStep->pNext; } - sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0); - VdbeComment((v, "end trigger %s", pStepList->pTrig->name)); + sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0); + VdbeComment((v, "# end trigger %s", pStepList->pTrig->name)); return 0; } @@ -70813,13 +63382,6 @@ static int codeTriggerProgram( ** a row containing values to be substituted for old.* expressions in the ** trigger program(s). ** -** If they are not NULL, the piOldColMask and piNewColMask output variables -** are set to values that describe the columns used by the trigger program -** in the OLD.* and NEW.* tables respectively. If column N of the -** pseudo-table is read at least once, the corresponding bit of the output -** mask is set. If a column with an index greater than 32 is read, the -** output mask is set to the special value 0xffffffff. -** */ SQLITE_PRIVATE int sqlite3CodeRowTrigger( Parse *pParse, /* Parse context */ @@ -70830,17 +63392,11 @@ SQLITE_PRIVATE int sqlite3CodeRowTrigger( int newIdx, /* The indice of the "new" row to access */ int oldIdx, /* The indice of the "old" row to access */ int orconf, /* ON CONFLICT policy */ - int ignoreJump, /* Instruction to jump to for RAISE(IGNORE) */ - u32 *piOldColMask, /* OUT: Mask of columns used from the OLD.* table */ - u32 *piNewColMask /* OUT: Mask of columns used from the NEW.* table */ + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */ ){ Trigger *p; - sqlite3 *db = pParse->db; TriggerStack trigStackEntry; - trigStackEntry.oldColMask = 0; - trigStackEntry.newColMask = 0; - assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE); assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER ); @@ -70848,6 +63404,7 @@ SQLITE_PRIVATE int sqlite3CodeRowTrigger( for(p=pTab->pTrigger; p; p=p->pNext){ int fire_this = 0; + sqlite3 *db = pParse->db; /* Determine whether we should code this trigger */ if( @@ -70876,11 +63433,6 @@ SQLITE_PRIVATE int sqlite3CodeRowTrigger( AuthContext sContext; NameContext sNC; -#ifndef SQLITE_OMIT_TRACE - sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0, - sqlite3MPrintf(db, "-- TRIGGER %s", p->name), - P4_DYNAMIC); -#endif memset(&sNC, 0, sizeof(sNC)); sNC.pParse = pParse; @@ -70902,7 +63454,7 @@ SQLITE_PRIVATE int sqlite3CodeRowTrigger( sqlite3ExprDelete(whenExpr); return 1; } - sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1); sqlite3ExprDelete(whenExpr); codeTriggerProgram(pParse, p->step_list, orconf); @@ -70914,8 +63466,6 @@ SQLITE_PRIVATE int sqlite3CodeRowTrigger( sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger); } } - if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask; - if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask; return 0; } #endif /* !defined(SQLITE_OMIT_TRIGGER) */ @@ -70936,7 +63486,7 @@ SQLITE_PRIVATE int sqlite3CodeRowTrigger( ** This file contains C code routines that are called by the parser ** to handle UPDATE statements. ** -** $Id: update.c,v 1.180 2008/07/09 16:51:51 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -70954,7 +63504,7 @@ static void updateVirtualTable( /* ** The most recently coded instruction was an OP_Column to retrieve the -** i-th column of table pTab. This routine sets the P4 parameter of the +** i-th column of table pTab. This routine sets the P3 parameter of the ** OP_Column to the default value, if any. ** ** The default value of a column is specified by a DEFAULT clause in the @@ -70962,9 +63512,9 @@ static void updateVirtualTable( ** was created, or added later to the table definition by an ALTER TABLE ** command. If the latter, then the row-records in the table btree on disk ** may not contain a value for the column and the default value, taken -** from the P4 parameter of the OP_Column instruction, is returned instead. +** from the P3 parameter of the OP_Column instruction, is returned instead. ** If the former, then all row-records are guaranteed to include a value -** for the column and the P4 value is not required. +** for the column and the P3 value is not required. ** ** Column definitions created by an ALTER TABLE command may only have ** literal default values specified: a number, null or a string. (If a more @@ -70972,7 +63522,7 @@ static void updateVirtualTable( ** when the ALTER TABLE is executed and one of the literal values written ** into the sqlite_master table.) ** -** Therefore, the P4 parameter is only required if the default value for +** Therefore, the P3 parameter is only required if the default value for ** the column is a literal number, string or null. The sqlite3ValueFromExpr() ** function is capable of transforming these types of expressions into ** sqlite3_value objects. @@ -70982,12 +63532,12 @@ SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){ sqlite3_value *pValue; u8 enc = ENC(sqlite3VdbeDb(v)); Column *pCol = &pTab->aCol[i]; - VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); assert( inCol ); - sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, - pCol->affinity, &pValue); + sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, pCol->affinity, &pValue); if( pValue ){ - sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM); + sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM); + }else{ + VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName)); } } } @@ -71013,9 +63563,11 @@ SQLITE_PRIVATE void sqlite3Update( Vdbe *v; /* The virtual database engine */ Index *pIdx; /* For looping over indices */ int nIdx; /* Number of indices that need updating */ + int nIdxTotal; /* Total number of indices */ int iCur; /* VDBE Cursor number of pTab */ sqlite3 *db; /* The database structure */ - int *aRegIdx = 0; /* One register assigned to each index to be updated */ + Index **apIdx = 0; /* An array of indices that need updating too */ + char *aIdxUsed = 0; /* aIdxUsed[i]==1 if the i-th index is used */ int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the ** an expression for the i-th column of the table. ** aXRef[i]==-1 if the i-th column is not changed. */ @@ -71025,29 +63577,17 @@ SQLITE_PRIVATE void sqlite3Update( AuthContext sContext; /* The authorization context */ NameContext sNC; /* The name-context to resolve expressions in */ int iDb; /* Database containing the table being updated */ - int j1; /* Addresses of jump instructions */ - int okOnePass; /* True for one-pass algorithm without the FIFO */ + int memCnt = 0; /* Memory cell used for counting rows changed */ + int mem1; /* Memory address storing the rowid for next row to update */ #ifndef SQLITE_OMIT_TRIGGER int isView; /* Trying to update a view */ int triggers_exist = 0; /* True if any row triggers exist */ #endif - int iBeginAfterTrigger; /* Address of after trigger program */ - int iEndAfterTrigger; /* Exit of after trigger program */ - int iBeginBeforeTrigger; /* Address of before trigger program */ - int iEndBeforeTrigger; /* Exit of before trigger program */ - u32 old_col_mask = 0; /* Mask of OLD.* columns in use */ - u32 new_col_mask = 0; /* Mask of NEW.* columns in use */ int newIdx = -1; /* index of trigger "new" temp table */ int oldIdx = -1; /* index of trigger "old" temp table */ - /* Register Allocations */ - int regRowCount = 0; /* A count of rows changed */ - int regOldRowid; /* The old rowid */ - int regNewRowid; /* The new rowid */ - int regData; /* New data for the row */ - sContext.pParse = 0; db = pParse->db; if( pParse->nErr || db->mallocFailed ){ @@ -71153,47 +63693,41 @@ SQLITE_PRIVATE void sqlite3Update( #endif } - /* Allocate memory for the array aRegIdx[]. There is one entry in the - ** array for each index associated with table being updated. Fill in - ** the value with a register number for indices that are to be used - ** and with zero for unused indices. + /* Allocate memory for the array apIdx[] and fill it with pointers to every + ** index that needs to be updated. Indices only need updating if their + ** key includes one of the columns named in pChanges or if the record + ** number of the original table entry is changing. */ - for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){} - if( nIdx>0 ){ - aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx ); - if( aRegIdx==0 ) goto update_cleanup; - } - for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ - int reg; + for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){ if( chngRowid ){ - reg = ++pParse->nMem; - }else{ - reg = 0; + i = 0; + }else { for(i=0; inColumn; i++){ - if( aXRef[pIdx->aiColumn[i]]>=0 ){ - reg = ++pParse->nMem; - break; - } + if( aXRef[pIdx->aiColumn[i]]>=0 ) break; } } - aRegIdx[j] = reg; + if( inColumn ) nIdx++; } - - /* Allocate a block of register used to store the change record - ** sent to sqlite3GenerateConstraintChecks(). There are either - ** one or two registers for holding the rowid. One rowid register - ** is used if chngRowid is false and two are used if chngRowid is - ** true. Following these are pTab->nCol register holding column - ** data. - */ - regOldRowid = regNewRowid = pParse->nMem + 1; - pParse->nMem += pTab->nCol + 1; - if( chngRowid ){ - regNewRowid++; - pParse->nMem++; + if( nIdxTotal>0 ){ + apIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx + nIdxTotal ); + if( apIdx==0 ) goto update_cleanup; + aIdxUsed = (char*)&apIdx[nIdx]; + } + for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ + if( chngRowid ){ + i = 0; + }else{ + for(i=0; inColumn; i++){ + if( aXRef[pIdx->aiColumn[i]]>=0 ) break; + } + } + if( inColumn ){ + apIdx[nIdx++] = pIdx; + aIdxUsed[j] = 1; + }else{ + aIdxUsed[j] = 0; + } } - regData = regNewRowid+1; - /* Begin generating code. */ @@ -71201,6 +63735,7 @@ SQLITE_PRIVATE void sqlite3Update( if( v==0 ) goto update_cleanup; if( pParse->nested==0 ) sqlite3VdbeCountChanges(v); sqlite3BeginWriteOperation(pParse, 1, iDb); + mem1 = pParse->nMem++; #ifndef SQLITE_OMIT_VIRTUALTABLE /* Virtual tables must be handled separately */ @@ -71213,48 +63748,6 @@ SQLITE_PRIVATE void sqlite3Update( } #endif - /* Start the view context - */ - if( isView ){ - sqlite3AuthContextPush(pParse, &sContext, pTab->zName); - } - - /* Generate the code for triggers. - */ - if( triggers_exist ){ - int iGoto; - - /* Create pseudo-tables for NEW and OLD - */ - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); - sqlite3VdbeAddOp2(v, OP_OpenPseudo, oldIdx, 0); - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pTab->nCol); - sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); - - iGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); - addr = sqlite3VdbeMakeLabel(v); - iBeginBeforeTrigger = sqlite3VdbeCurrentAddr(v); - if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab, - newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){ - goto update_cleanup; - } - iEndBeforeTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); - iBeginAfterTrigger = sqlite3VdbeCurrentAddr(v); - if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, - newIdx, oldIdx, onError, addr, &old_col_mask, &new_col_mask) ){ - goto update_cleanup; - } - iEndAfterTrigger = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); - sqlite3VdbeJumpHere(v, iGoto); - } - - /* If we are trying to update a view, realize that view into - ** a ephemeral table. - */ - if( isView ){ - sqlite3MaterializeView(pParse, pTab->pSelect, pWhere, iCur); - } - /* Resolve the column names in all the expressions in the ** WHERE clause. */ @@ -71262,18 +63755,31 @@ SQLITE_PRIVATE void sqlite3Update( goto update_cleanup; } + /* Start the view context + */ + if( isView ){ + sqlite3AuthContextPush(pParse, &sContext, pTab->zName); + } + + /* If we are trying to update a view, realize that view into + ** a ephemeral table. + */ + if( isView ){ + Select *pView; + pView = sqlite3SelectDup(db, pTab->pSelect); + sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0); + sqlite3SelectDelete(pView); + } + /* Begin the database scan */ - sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, - WHERE_ONEPASS_DESIRED); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); if( pWInfo==0 ) goto update_cleanup; - okOnePass = pWInfo->okOnePass; /* Remember the rowid of every item to be updated. */ - sqlite3VdbeAddOp2(v, IsVirtual(pTab)?OP_VRowid:OP_Rowid, iCur, regOldRowid); - if( !okOnePass ) sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0); + sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0); + sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0); /* End the database scan loop. */ @@ -71282,8 +63788,79 @@ SQLITE_PRIVATE void sqlite3Update( /* Initialize the count of updated rows */ if( db->flags & SQLITE_CountRows && !pParse->trigStack ){ - regRowCount = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + memCnt = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt); + } + + if( triggers_exist ){ + + /* Create pseudo-tables for NEW and OLD + */ + sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0); + sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol); + sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0); + sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol); + + /* The top of the update loop for when there are triggers. + */ + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0); + sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); + sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0); + + if( !isView ){ + /* Open a cursor and make it point to the record that is + ** being updated. + */ + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); + } + sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr); + + /* Generate the OLD table + */ + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); + sqlite3VdbeAddOp(v, OP_RowData, iCur, 0); + sqlite3VdbeAddOp(v, OP_Insert, oldIdx, 0); + + /* Generate the NEW table + */ + if( chngRowid ){ + sqlite3ExprCodeAndCache(pParse, pRowidExpr); + }else{ + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); + } + for(i=0; inCol; i++){ + if( i==pTab->iPKey ){ + sqlite3VdbeAddOp(v, OP_Null, 0, 0); + continue; + } + j = aXRef[i]; + if( j<0 ){ + sqlite3VdbeAddOp(v, OP_Column, iCur, i); + sqlite3ColumnDefault(v, pTab, i); + }else{ + sqlite3ExprCodeAndCache(pParse, pChanges->a[j].pExpr); + } + } + sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); + if( !isView ){ + sqlite3TableAffinityStr(v, pTab); + } + if( pParse->nErr ) goto update_cleanup; + sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); + if( !isView ){ + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); + } + + /* Fire the BEFORE and INSTEAD OF triggers + */ + if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_BEFORE, pTab, + newIdx, oldIdx, onError, addr) ){ + goto update_cleanup; + } + + if( !isView ){ + sqlite3VdbeAddOp(v, OP_MemLoad, mem1, 0); + } } if( !isView && !IsVirtual(pTab) ){ @@ -71293,7 +63870,7 @@ SQLITE_PRIVATE void sqlite3Update( ** action, then we need to open all indices because we might need ** to be deleting some records. */ - if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); + sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); if( onError==OE_Replace ){ openAll = 1; }else{ @@ -71306,178 +63883,114 @@ SQLITE_PRIVATE void sqlite3Update( } } for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ - if( openAll || aRegIdx[i]>0 ){ + if( openAll || aIdxUsed[i] ){ KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); - sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb, - (char*)pKey, P4_KEYINFO_HANDOFF); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + sqlite3VdbeOp3(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, + (char*)pKey, P3_KEYINFO_HANDOFF); assert( pParse->nTab>iCur+i+1 ); } } - } - - /* Jump back to this point if a trigger encounters an IGNORE constraint. */ - if( triggers_exist ){ - sqlite3VdbeResolveLabel(v, addr); - } - /* Top of the update loop */ - if( okOnePass ){ - int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid); - addr = sqlite3VdbeAddOp0(v, OP_Goto); - sqlite3VdbeJumpHere(v, a1); - }else{ - addr = sqlite3VdbeAddOp2(v, OP_FifoRead, regOldRowid, 0); - } - - if( triggers_exist ){ - int regRowid; - int regRow; - int regCols; - - /* Make cursor iCur point to the record that is being updated. - */ - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); - - /* Generate the OLD table - */ - regRowid = sqlite3GetTempReg(pParse); - regRow = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid); - if( !old_col_mask ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regRow); - }else{ - sqlite3VdbeAddOp2(v, OP_RowData, iCur, regRow); - } - sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, regRow, regRowid); - - /* Generate the NEW table - */ - if( chngRowid ){ - sqlite3ExprCodeAndCache(pParse, pRowidExpr, regRowid); - }else{ - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regRowid); - } - regCols = sqlite3GetTempRange(pParse, pTab->nCol); - for(i=0; inCol; i++){ - if( i==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i); - continue; - } - j = aXRef[i]; - if( new_col_mask&((u32)1<a[j].pExpr, regCols+i); - } - }else{ - sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i); - } - } - sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRow); - if( !isView ){ - sqlite3TableAffinityStr(v, pTab); - sqlite3ExprCacheAffinityChange(pParse, regCols, pTab->nCol); - } - sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol); - /* if( pParse->nErr ) goto update_cleanup; */ - sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRow, regRowid); - sqlite3ReleaseTempReg(pParse, regRowid); - sqlite3ReleaseTempReg(pParse, regRow); - - sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger); - sqlite3VdbeJumpHere(v, iEndBeforeTrigger); - } - - if( !isView && !IsVirtual(pTab) ){ /* Loop over every record that needs updating. We have to load ** the old data for each record to be updated because some columns ** might not change and we will need to copy the old value. ** Also, the old data is needed to delete the old index entries. ** So make the cursor point at the old record. */ - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); + if( !triggers_exist ){ + addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0); + sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); + sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0); + } + sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr); + sqlite3VdbeAddOp(v, OP_MemLoad, mem1, 0); /* If the record number will change, push the record number as it ** will be after the update. (The old record number is currently ** on top of the stack.) */ if( chngRowid ){ - sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); - sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); + sqlite3ExprCode(pParse, pRowidExpr); + sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); } /* Compute new data for this record. */ for(i=0; inCol; i++){ if( i==pTab->iPKey ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); continue; } j = aXRef[i]; if( j<0 ){ - sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i); + sqlite3VdbeAddOp(v, OP_Column, iCur, i); sqlite3ColumnDefault(v, pTab, i); }else{ - sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i); + sqlite3ExprCode(pParse, pChanges->a[j].pExpr); } } /* Do constraint checks */ - sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid, - aRegIdx, chngRowid, 1, - onError, addr); + sqlite3GenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, + onError, addr); /* Delete the old indices for the current record. */ - j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid); - sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx); + sqlite3GenerateRowIndexDelete(v, pTab, iCur, aIdxUsed); /* If changing the record number, delete the old record. */ if( chngRowid ){ - sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0); + sqlite3VdbeAddOp(v, OP_Delete, iCur, 0); } - sqlite3VdbeJumpHere(v, j1); /* Create the new index entries and the new record. */ - sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, - aRegIdx, chngRowid, 1, -1, 0); + sqlite3CompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, -1, 0); } /* Increment the row counter */ if( db->flags & SQLITE_CountRows && !pParse->trigStack){ - sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); + sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt); } /* If there are triggers, close all the cursors after each iteration ** through the loop. The fire the after triggers. */ if( triggers_exist ){ - sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger); - sqlite3VdbeJumpHere(v, iEndAfterTrigger); + if( !isView ){ + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + if( openAll || aIdxUsed[i] ) + sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0); + } + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); + } + if( sqlite3CodeRowTrigger(pParse, TK_UPDATE, pChanges, TRIGGER_AFTER, pTab, + newIdx, oldIdx, onError, addr) ){ + goto update_cleanup; + } } /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ - sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); + sqlite3VdbeAddOp(v, OP_Goto, 0, addr); sqlite3VdbeJumpHere(v, addr); - /* Close all tables */ - for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ - if( openAll || aRegIdx[i]>0 ){ - sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0); + /* Close all tables if there were no FOR EACH ROW triggers */ + if( !triggers_exist ){ + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ + if( openAll || aIdxUsed[i] ){ + sqlite3VdbeAddOp(v, OP_Close, iCur+i+1, 0); + } } - } - sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); - if( triggers_exist ){ - sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0); - sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0); + sqlite3VdbeAddOp(v, OP_Close, iCur, 0); + }else{ + sqlite3VdbeAddOp(v, OP_Close, newIdx, 0); + sqlite3VdbeAddOp(v, OP_Close, oldIdx, 0); } /* @@ -71486,14 +63999,15 @@ SQLITE_PRIVATE void sqlite3Update( ** invoke the callback function. */ if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){ - sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); + sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0); + sqlite3VdbeAddOp(v, OP_Callback, 1, 0); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P3_STATIC); } update_cleanup: sqlite3AuthContextPop(&sContext); - sqlite3_free(aRegIdx); + sqlite3_free(apIdx); sqlite3_free(aXRef); sqlite3SrcListDelete(pTabList); sqlite3ExprListDelete(pChanges); @@ -71537,10 +64051,7 @@ static void updateVirtualTable( int ephemTab; /* Table holding the result of the SELECT */ int i; /* Loop counter */ int addr; /* Address of top of loop */ - int iReg; /* First register in set passed to OP_VUpdate */ sqlite3 *db = pParse->db; /* Database connection */ - const char *pVtab = (const char*)pTab->pVtab; - SelectDest dest; /* Construct the SELECT statement that will find the new values for ** all updated rows. @@ -71567,39 +64078,39 @@ static void updateVirtualTable( */ assert( v ); ephemTab = pParse->nTab++; - sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0)); + sqlite3VdbeAddOp(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0)); /* fill the ephemeral table */ - sqlite3SelectDestInit(&dest, SRT_Table, ephemTab); - sqlite3Select(pParse, pSelect, &dest, 0, 0, 0); + sqlite3Select(pParse, pSelect, SRT_Table, ephemTab, 0, 0, 0, 0); - /* Generate code to scan the ephemeral table and call VUpdate. */ - iReg = ++pParse->nMem; - pParse->nMem += pTab->nCol+1; - sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); + /* + ** Generate code to scan the ephemeral table and call VDelete and + ** VInsert + */ + sqlite3VdbeAddOp(v, OP_Rewind, ephemTab, 0); addr = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg); - sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1); - for(i=0; inCol; i++){ - sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i); + sqlite3VdbeAddOp(v, OP_Column, ephemTab, 0); + if( pRowid ){ + sqlite3VdbeAddOp(v, OP_Column, ephemTab, 1); + }else{ + sqlite3VdbeAddOp(v, OP_Dup, 0, 0); } - sqlite3VtabMakeWritable(pParse, pTab); - sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB); - sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr); + for(i=0; inCol; i++){ + sqlite3VdbeAddOp(v, OP_Column, ephemTab, i+1+(pRowid!=0)); + } + pParse->pVirtualLock = pTab; + sqlite3VdbeOp3(v, OP_VUpdate, 0, pTab->nCol+2, + (const char*)pTab->pVtab, P3_VTAB); + sqlite3VdbeAddOp(v, OP_Next, ephemTab, addr); sqlite3VdbeJumpHere(v, addr-1); - sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); + sqlite3VdbeAddOp(v, OP_Close, ephemTab, 0); /* Cleanup */ sqlite3SelectDelete(pSelect); } #endif /* SQLITE_OMIT_VIRTUALTABLE */ -/* Make sure "isView" gets undefined in case this file becomes part of -** the amalgamation - so that subsequent files do not see isView as a -** macro. */ -#undef isView - /************** End of update.c **********************************************/ /************** Begin file vacuum.c ******************************************/ /* @@ -71618,7 +64129,7 @@ static void updateVirtualTable( ** Most of the code in this file may be omitted by defining the ** SQLITE_OMIT_VACUUM macro. ** -** $Id: vacuum.c,v 1.81 2008/07/08 19:34:07 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) @@ -71672,7 +64183,7 @@ static int execExecSql(sqlite3 *db, const char *zSql){ SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){ Vdbe *v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0); + sqlite3VdbeAddOp(v, OP_Vacuum, 0, 0); } return; } @@ -71686,19 +64197,15 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ Btree *pTemp; /* The temporary database we vacuum into */ char *zSql = 0; /* SQL statements */ int saved_flags; /* Saved value of the db->flags */ - int saved_nChange; /* Saved value of db->nChange */ - int saved_nTotalChange; /* Saved value of db->nTotalChange */ Db *pDb = 0; /* Database to detach at end of vacuum */ - int nRes; /* Save the current value of the write-schema flag before setting it. */ saved_flags = db->flags; - saved_nChange = db->nChange; - saved_nTotalChange = db->nTotalChange; db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; if( !db->autoCommit ){ - sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction"); + sqlite3SetString(pzErrMsg, "cannot VACUUM from within a transaction", + (char*)0); rc = SQLITE_ERROR; goto end_of_vacuum; } @@ -71711,12 +64218,6 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ ** sqlite3BtreeCopyFile() is called. ** ** An optimisation would be to use a non-journaled pager. - ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but - ** that actually made the VACUUM run slower. Very little journalling - ** actually occurs when doing a vacuum since the vacuum_db is initially - ** empty. Only the journal header is written. Apparently it takes more - ** time to parse and run the PRAGMA to turn journalling off than it does - ** to write the journal header file. */ zSql = "ATTACH '' AS vacuum_db;"; rc = execSql(db, zSql); @@ -71724,27 +64225,13 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ pDb = &db->aDb[db->nDb-1]; assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 ); pTemp = db->aDb[db->nDb-1].pBt; - - nRes = sqlite3BtreeGetReserve(pMain); - - /* A VACUUM cannot change the pagesize of an encrypted database. */ -#ifdef SQLITE_HAS_CODEC - if( db->nextPagesize ){ - extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*); - int nKey; - char *zKey; - sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey); - if( nKey ) db->nextPagesize = 0; - } -#endif - - if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes) - || sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes) - || db->mallocFailed - ){ + sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), + sqlite3BtreeGetReserve(pMain)); + if( db->mallocFailed ){ rc = SQLITE_NOMEM; goto end_of_vacuum; } + assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) ); rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF"); if( rc!=SQLITE_OK ){ goto end_of_vacuum; @@ -71863,15 +64350,9 @@ SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ rc = sqlite3BtreeCommit(pMain); } - if( rc==SQLITE_OK ){ - rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes); - } - end_of_vacuum: /* Restore the original value of db->flags */ db->flags = saved_flags; - db->nChange = saved_nChange; - db->nTotalChange = saved_nTotalChange; /* Currently there is an SQL level transaction open on the vacuum ** database. No locks are held on any other files (since the main file @@ -71909,7 +64390,7 @@ end_of_vacuum: ************************************************************************* ** This file contains code used to help implement virtual tables. ** -** $Id: vtab.c,v 1.70 2008/06/23 17:44:19 danielk1977 Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -71927,21 +64408,17 @@ static int createModule( nName = strlen(zName); pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1); if( pMod ){ - Module *pDel; char *zCopy = (char *)(&pMod[1]); memcpy(zCopy, zName, nName+1); pMod->zName = zCopy; pMod->pModule = pModule; pMod->pAux = pAux; pMod->xDestroy = xDestroy; - pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod); - if( pDel && pDel->xDestroy ){ - pDel->xDestroy(pDel->pAux); - } - sqlite3_free(pDel); - if( pDel==pMod ){ - db->mallocFailed = 1; + pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod); + if( pMod && pMod->xDestroy ){ + pMod->xDestroy(pMod->pAux); } + sqlite3_free(pMod); sqlite3ResetInternalSchema(db, 0); } rc = sqlite3ApiExit(db, SQLITE_OK); @@ -71994,12 +64471,12 @@ SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){ SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){ pVtab->nRef--; assert(db); - assert( sqlite3SafetyCheckOk(db) ); + assert(!sqlite3SafetyCheck(db)); if( pVtab->nRef==0 ){ if( db->magic==SQLITE_MAGIC_BUSY ){ - (void)sqlite3SafetyOff(db); + sqlite3SafetyOff(db); pVtab->pModule->xDisconnect(pVtab); - (void)sqlite3SafetyOn(db); + sqlite3SafetyOn(db); } else { pVtab->pModule->xDisconnect(pVtab); } @@ -72160,30 +64637,29 @@ SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){ ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. ** - ** The VM register number pParse->regRowid holds the rowid of an - ** entry in the sqlite_master table tht was created for this vtab - ** by sqlite3StartTable(). + ** The top of the stack is the rootpage allocated by sqlite3StartTable(). + ** This value is always 0 and is ignored, a virtual table does not have a + ** rootpage. The next entry on the stack is the rowid of the record + ** in the sqlite_master table. */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " - "WHERE rowid=#%d", + "WHERE rowid=#1", db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTab->zName, pTab->zName, - zStmt, - pParse->regRowid + zStmt ); sqlite3_free(zStmt); v = sqlite3GetVdbe(pParse); - sqlite3ChangeCookie(pParse, iDb); + sqlite3ChangeCookie(db, v, iDb); - sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); + sqlite3VdbeAddOp(v, OP_Expire, 0, 0); zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName); - sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC); - sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, - pTab->zName, strlen(pTab->zName) + 1); + sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 1, zWhere, P3_DYNAMIC); + sqlite3VdbeOp3(v, OP_VCreate, iDb, 0, pTab->zName, strlen(pTab->zName) + 1); } /* If we are rereading the sqlite_master table create the in-memory @@ -72495,15 +64971,8 @@ SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab if( xDestroy ){ rc = xDestroy(pTab->pVtab); } - (void)sqlite3SafetyOn(db); + sqlite3SafetyOn(db); if( rc==SQLITE_OK ){ - int i; - for(i=0; inVTrans; i++){ - if( db->aVTrans[i]==pTab->pVtab ){ - db->aVTrans[i] = db->aVTrans[--db->nVTrans]; - break; - } - } pTab->pVtab = 0; } } @@ -72572,7 +65041,7 @@ SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, int rc2){ ** sqlite3.aVTrans array. Then clear the array itself. */ SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ - callFinaliser(db, offsetof(sqlite3_module,xRollback)); + callFinaliser(db, (int)(&((sqlite3_module *)0)->xRollback)); return SQLITE_OK; } @@ -72581,7 +65050,7 @@ SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){ ** sqlite3.aVTrans array. Then clear the array itself. */ SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){ - callFinaliser(db, offsetof(sqlite3_module,xCommit)); + callFinaliser(db, (int)(&((sqlite3_module *)0)->xCommit)); return SQLITE_OK; } @@ -72703,27 +65172,6 @@ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction( return pNew; } -/* -** Make sure virtual table pTab is contained in the pParse->apVirtualLock[] -** array so that an OP_VBegin will get generated for it. Add pTab to the -** array if it is missing. If pTab is already in the array, this routine -** is a no-op. -*/ -SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ - int i, n; - assert( IsVirtual(pTab) ); - for(i=0; inVtabLock; i++){ - if( pTab==pParse->apVtabLock[i] ) return; - } - n = (pParse->nVtabLock+1)*sizeof(pParse->apVtabLock[0]); - pParse->apVtabLock = sqlite3_realloc(pParse->apVtabLock, n); - if( pParse->apVtabLock ){ - pParse->apVtabLock[pParse->nVtabLock++] = pTab; - }else{ - pParse->db->mallocFailed = 1; - } -} - #endif /* SQLITE_OMIT_VIRTUALTABLE */ /************** End of vtab.c ************************************************/ @@ -72740,13 +65188,13 @@ SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ ** ************************************************************************* ** This module contains C code that generates VDBE code used to process -** the WHERE clause of SQL statements. This module is responsible for +** the WHERE clause of SQL statements. This module is reponsible for ** generating the code that loops through a table looking for applicable ** rows. Indices are selected and used to speed the search when doing ** so is applicable. Because this module is responsible for selecting ** indices, you might also think of this module as the "query optimizer". ** -** $Id: where.c,v 1.317 2008/07/12 14:52:20 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* @@ -72758,10 +65206,8 @@ SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){ ** Trace output macros */ #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) -SQLITE_PRIVATE int sqlite3WhereTrace = 0; -#endif -#if 0 -# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X +SQLITE_API int sqlite3_where_trace = 0; +# define WHERETRACE(X) if(sqlite3_where_trace) sqlite3DebugPrintf X #else # define WHERETRACE(X) #endif @@ -72950,7 +65396,7 @@ static void whereClauseClear(WhereClause *pWC){ ** for freeing the expression p is assumed by the WhereClause object. ** ** WARNING: This routine might reallocate the space used to store -** WhereTerms. All pointers to WhereTerms should be invalidated after +** WhereTerms. All pointers to WhereTerms should be invalided after ** calling this routine. Such pointers may be reinitialized by referencing ** the pWC->a[] array. */ @@ -72959,7 +65405,7 @@ static int whereClauseInsert(WhereClause *pWC, Expr *p, int flags){ int idx; if( pWC->nTerm>=pWC->nSlot ){ WhereTerm *pOld = pWC->a; - pWC->a = sqlite3Malloc( sizeof(pWC->a[0])*pWC->nSlot*2 ); + pWC->a = sqlite3_malloc( sizeof(pWC->a[0])*pWC->nSlot*2 ); if( pWC->a==0 ){ pWC->pParse->db->mallocFailed = 1; if( flags & TERM_DYNAMIC ){ @@ -73113,7 +65559,7 @@ static int allowedOp(int op){ #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;} /* -** Commute a comparison operator. Expressions of the form "X op Y" +** Commute a comparision operator. Expressions of the form "X op Y" ** are converted into "Y op X". ** ** If a collation sequence is associated with either the left or right @@ -73181,14 +65627,13 @@ static WhereTerm *findTerm( ){ WhereTerm *pTerm; int k; - assert( iCur>=0 ); for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){ if( pTerm->leftCursor==iCur && (pTerm->prereqRight & notReady)==0 && pTerm->leftColumn==iColumn && (pTerm->eOperator & op)!=0 ){ - if( pIdx && pTerm->eOperator!=WO_ISNULL ){ + if( iCur>=0 && pIdx && pTerm->eOperator!=WO_ISNULL ){ Expr *pX = pTerm->pExpr; CollSeq *pColl; char idxaff; @@ -73208,9 +65653,8 @@ static WhereTerm *findTerm( pColl = pParse->db->pDfltColl; } - for(j=0; pIdx->aiColumn[j]!=iColumn; j++){ - if( NEVER(j>=pIdx->nColumn) ) return 0; - } + for(j=0; jnColumn && pIdx->aiColumn[j]!=iColumn; j++){} + assert( jnColumn ); if( sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue; } return pTerm; @@ -73250,26 +65694,22 @@ static int isLikeOrGlob( sqlite3 *db, /* The database */ Expr *pExpr, /* Test this expression */ int *pnPattern, /* Number of non-wildcard prefix characters */ - int *pisComplete, /* True if the only wildcard is % in the last character */ - int *pnoCase /* True if uppercase is equivalent to lowercase */ + int *pisComplete /* True if the only wildcard is % in the last character */ ){ const char *z; Expr *pRight, *pLeft; ExprList *pList; int c, cnt; + int noCase; char wc[3]; CollSeq *pColl; - if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){ + if( !sqlite3IsLikeFunction(db, pExpr, &noCase, wc) ){ return 0; } -#ifdef SQLITE_EBCDIC - if( *pnoCase ) return 0; -#endif pList = pExpr->pList; pRight = pList->a[0].pExpr; - if( pRight->op!=TK_STRING - && (pRight->op!=TK_REGISTER || pRight->iColumn!=TK_STRING) ){ + if( pRight->op!=TK_STRING ){ return 0; } pLeft = pList->a[1].pExpr; @@ -73277,13 +65717,15 @@ static int isLikeOrGlob( return 0; } pColl = pLeft->pColl; - assert( pColl!=0 || pLeft->iColumn==-1 ); if( pColl==0 ){ - /* No collation is defined for the ROWID. Use the default. */ + /* TODO: Coverage testing doesn't get this case. Is it actually possible + ** for an expression of type TK_COLUMN to not have an assigned collation + ** sequence at this point? + */ pColl = db->pDfltColl; } - if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) && - (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){ + if( (pColl->type!=SQLITE_COLL_BINARY || noCase) && + (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){ return 0; } sqlite3DequoteExpr(db, pRight); @@ -73354,7 +65796,7 @@ static void transferJoinMarkings(Expr *pDerived, Expr *pBase){ ** a= OR a= OR b= OR ... ** ** The pOrTerm input to this routine corresponds to a single term of -** this OR clause. In order for the term to be a candidate for +** this OR clause. In order for the term to be a condidate for ** conversion to an IN operator, the following must be true: ** ** * The left-hand side of the term must be the column which @@ -73409,7 +65851,7 @@ static int orTermIsOptCandidate(WhereTerm *pOrTerm, int iCursor, int iColumn){ ** This routine merely checks to see if pOrTerm has a duplicate that ** might qualify. If there is a duplicate that has not yet been ** disqualified, then return true. If there are no duplicates, or -** the duplicate has also been disqualified, return false. +** the duplicate has also been disqualifed, return false. */ static int orTermHasOkDuplicate(WhereClause *pOr, WhereTerm *pOrTerm){ if( pOrTerm->flags & TERM_COPIED ){ @@ -73451,10 +65893,8 @@ static void exprAnalyze( Expr *pExpr; Bitmask prereqLeft; Bitmask prereqAll; - Bitmask extraRight = 0; int nPattern; int isComplete; - int noCase; int op; Parse *pParse = pWC->pParse; sqlite3 *db = pParse->db; @@ -73478,10 +65918,7 @@ static void exprAnalyze( } prereqAll = exprTableUsage(pMaskSet, pExpr); if( ExprHasProperty(pExpr, EP_FromJoin) ){ - Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable); - prereqAll |= x; - extraRight = x-1; /* ON clause terms may not be used with an index - ** on left table of a LEFT JOIN. Ticket #3015 */ + prereqAll |= getMask(pMaskSet, pExpr->iRightJoinTable); } pTerm->prereqAll = prereqAll; pTerm->leftCursor = -1; @@ -73576,7 +66013,6 @@ static void exprAnalyze( exprAnalyzeAll(pSrc, &sOr); assert( sOr.nTerm>=2 ); j = 0; - if( db->mallocFailed ) goto or_not_possible; do{ assert( j=0; i--, pOrTerm++){ + for(i=sOr.nTerm-1, pOrTerm=sOr.a; i>=0 && ok; i--, pOrTerm++){ if( (pOrTerm->flags & TERM_OR_OK)==0 ) continue; pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight); pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup, 0); @@ -73629,15 +66065,8 @@ or_not_possible: #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION /* Add constraints to reduce the search space on a LIKE or GLOB ** operator. - ** - ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints - ** - ** x>='abc' AND x<'abd' AND x LIKE 'abc%' - ** - ** The last character of the prefix "abc" is incremented to form the - ** termination condition "abd". */ - if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete, &noCase) ){ + if( isLikeOrGlob(db, pExpr, &nPattern, &isComplete) ){ Expr *pLeft, *pRight; Expr *pStr1, *pStr2; Expr *pNewExpr1, *pNewExpr2; @@ -73653,15 +66082,8 @@ or_not_possible: } pStr2 = sqlite3ExprDup(db, pStr1); if( !db->mallocFailed ){ - u8 c, *pC; assert( pStr2->token.dyn ); - pC = (u8*)&pStr2->token.z[nPattern-1]; - c = *pC; - if( noCase ){ - if( c=='@' ) isComplete = 0; - c = sqlite3UpperToLower[c]; - } - *pC = c + 1; + ++*(u8*)&pStr2->token.z[nPattern-1]; } pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0); idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); @@ -73712,11 +66134,6 @@ or_not_possible: } } #endif /* SQLITE_OMIT_VIRTUALTABLE */ - - /* Prevent ON clause terms of a LEFT JOIN from being used to drive - ** an index for tables to the left of the join. - */ - pTerm->prereqRight |= extraRight; } /* @@ -73822,9 +66239,6 @@ static int isSortingIndex( ** ORDER BY term, that is OK. Just ignore that column of the index */ continue; - }else if( i==pIdx->nColumn ){ - /* Index column i is the rowid. All other terms match. */ - break; }else{ /* If an index column fails to match and is not constrained by == ** then the index cannot satisfy the ORDER BY constraint. @@ -73902,7 +66316,7 @@ static int sortableByRowid( /* ** Prepare a crude estimate of the logarithm of the input value. ** The results need not be exact. This is only used for estimating -** the total cost of performing operations with O(logN) or O(NlogN) +** the total cost of performing operatings with O(logN) or O(NlogN) ** complexity. Because N is just a guess, it is no great tragedy if ** logN is a little off. */ @@ -73925,7 +66339,7 @@ static double estLog(double N){ #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG) static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ int i; - if( !sqlite3WhereTrace ) return; + if( !sqlite3_where_trace ) return; for(i=0; inConstraint; i++){ sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n", i, @@ -73943,7 +66357,7 @@ static void TRACE_IDX_INPUTS(sqlite3_index_info *p){ } static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){ int i; - if( !sqlite3WhereTrace ) return; + if( !sqlite3_where_trace ) return; for(i=0; inConstraint; i++){ sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n", i, @@ -74010,10 +66424,8 @@ static double bestVirtualIndex( ** to this virtual table */ for(i=nTerm=0, pTerm=pWC->a; inTerm; i++, pTerm++){ if( pTerm->leftCursor != pSrc->iCursor ) continue; - if( (pTerm->eOperator&(pTerm->eOperator-1))==0 ); - testcase( pTerm->eOperator==WO_IN ); - testcase( pTerm->eOperator==WO_ISNULL ); - if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue; + if( pTerm->eOperator==WO_IN ) continue; + if( pTerm->eOperator==WO_ISNULL ) continue; nTerm++; } @@ -74060,10 +66472,8 @@ static double bestVirtualIndex( for(i=j=0, pTerm=pWC->a; inTerm; i++, pTerm++){ if( pTerm->leftCursor != pSrc->iCursor ) continue; - if( (pTerm->eOperator&(pTerm->eOperator-1))==0 ); - testcase( pTerm->eOperator==WO_IN ); - testcase( pTerm->eOperator==WO_ISNULL ); - if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue; + if( pTerm->eOperator==WO_IN ) continue; + if( pTerm->eOperator==WO_ISNULL ) continue; pIdxCons[j].iColumn = pTerm->leftColumn; pIdxCons[j].iTermOffset = i; pIdxCons[j].op = pTerm->eOperator; @@ -74148,27 +66558,20 @@ static double bestVirtualIndex( *(int*)&pIdxInfo->nOrderBy = 0; } - (void)sqlite3SafetyOff(pParse->db); + sqlite3SafetyOff(pParse->db); WHERETRACE(("xBestIndex for %s\n", pTab->zName)); TRACE_IDX_INPUTS(pIdxInfo); rc = pTab->pVtab->pModule->xBestIndex(pTab->pVtab, pIdxInfo); TRACE_IDX_OUTPUTS(pIdxInfo); - (void)sqlite3SafetyOn(pParse->db); - - for(i=0; inConstraint; i++){ - if( !pIdxInfo->aConstraint[i].usable && pUsage[i].argvIndex>0 ){ - sqlite3ErrorMsg(pParse, - "table %s: xBestIndex returned an invalid plan", pTab->zName); - return 0.0; - } - } - if( rc!=SQLITE_OK ){ if( rc==SQLITE_NOMEM ){ pParse->db->mallocFailed = 1; }else { sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); } + sqlite3SafetyOn(pParse->db); + }else{ + rc = sqlite3SafetyOn(pParse->db); } *(int*)&pIdxInfo->nOrderBy = nOrderBy; @@ -74217,7 +66620,7 @@ static double bestIndex( int eqTermMask; /* Mask of valid equality operators */ double cost; /* Cost of using pProbe */ - WHERETRACE(("bestIndex: tbl=%s notReady=%llx\n", pSrc->pTab->zName, notReady)); + WHERETRACE(("bestIndex: tbl=%s notReady=%x\n", pSrc->pTab->zName, notReady)); lowestCost = SQLITE_BIG_DBL; pProbe = pSrc->pTab->pIndex; @@ -74339,7 +66742,7 @@ static double bestIndex( flags |= WHERE_COLUMN_IN; if( pExpr->pSelect!=0 ){ inMultiplier *= 25; - }else if( ALWAYS(pExpr->pList) ){ + }else if( pExpr->pList!=0 ){ inMultiplier *= pExpr->pList->nExpr + 1; } } @@ -74455,7 +66858,7 @@ static double bestIndex( */ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ if( pTerm - && ALWAYS((pTerm->flags & TERM_CODED)==0) + && (pTerm->flags & TERM_CODED)==0 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin)) ){ pTerm->flags |= TERM_CODED; @@ -74469,17 +66872,20 @@ static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){ } /* -** Apply the affinities associated with the first n columns of index -** pIdx to the values in the n registers starting at base. +** Generate code that builds a probe for an index. +** +** There should be nColumn values on the stack. The index +** to be probed is pIdx. Pop the values from the stack and +** replace them all with a single record that is the index +** problem. */ -static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){ - if( n>0 ){ - Vdbe *v = pParse->pVdbe; - assert( v!=0 ); - sqlite3VdbeAddOp2(v, OP_Affinity, base, n); - sqlite3IndexAffinityStr(v, pIdx); - sqlite3ExprCacheAffinityChange(pParse, base, n); - } +static void buildIndexProbe( + Vdbe *v, /* Generate code into this VM */ + int nColumn, /* The number of columns to check for NULL */ + Index *pIdx /* Index that we will be searching */ +){ + sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); + sqlite3IndexAffinityStr(v, pIdx); } @@ -74488,30 +66894,23 @@ static void codeApplyAffinity(Parse *pParse, int base, int n, Index *pIdx){ ** term can be either X=expr or X IN (...). pTerm is the term to be ** coded. ** -** The current value for the constraint is left in register iReg. +** The current value for the constraint is left on the top of the stack. ** ** For a constraint of the form X=expr, the expression is evaluated and its ** result is left on the stack. For constraints of the form X IN (...) ** this routine sets up a loop that will iterate over all values of X. */ -static int codeEqualityTerm( +static void codeEqualityTerm( Parse *pParse, /* The parsing context */ WhereTerm *pTerm, /* The term of the WHERE clause to be coded */ - WhereLevel *pLevel, /* When level of the FROM clause we are working on */ - int iTarget /* Attempt to leave results in this register */ + WhereLevel *pLevel /* When level of the FROM clause we are working on */ ){ Expr *pX = pTerm->pExpr; Vdbe *v = pParse->pVdbe; - int iReg; /* Register holding results */ - - if( iTarget<=0 ){ - iReg = iTarget = sqlite3GetTempReg(pParse); - } if( pX->op==TK_EQ ){ - iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget); + sqlite3ExprCode(pParse, pX->pRight); }else if( pX->op==TK_ISNULL ){ - iReg = iTarget; - sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); + sqlite3VdbeAddOp(v, OP_Null, 0, 0); #ifndef SQLITE_OMIT_SUBQUERY }else{ int eType; @@ -74519,11 +66918,10 @@ static int codeEqualityTerm( struct InLoop *pIn; assert( pX->op==TK_IN ); - iReg = iTarget; - eType = sqlite3FindInIndex(pParse, pX, 0); + eType = sqlite3FindInIndex(pParse, pX, 1); iTab = pX->iTable; - sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); - VdbeComment((v, "%.*s", pX->span.n, pX->span.z)); + sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0); + VdbeComment((v, "# %.*s", pX->span.n, pX->span.z)); if( pLevel->nIn==0 ){ pLevel->nxt = sqlite3VdbeMakeLabel(v); } @@ -74532,21 +66930,17 @@ static int codeEqualityTerm( sizeof(pLevel->aInLoop[0])*pLevel->nIn); pIn = pLevel->aInLoop; if( pIn ){ + int op = ((eType==IN_INDEX_ROWID)?OP_Rowid:OP_Column); pIn += pLevel->nIn - 1; pIn->iCur = iTab; - if( eType==IN_INDEX_ROWID ){ - pIn->topAddr = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg); - }else{ - pIn->topAddr = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg); - } - sqlite3VdbeAddOp1(v, OP_IsNull, iReg); + pIn->topAddr = sqlite3VdbeAddOp(v, op, iTab, 0); + sqlite3VdbeAddOp(v, OP_IsNull, -1, 0); }else{ pLevel->nIn = 0; } #endif } disableTerm(pLevel, pTerm); - return iReg; } /* @@ -74572,50 +66966,55 @@ static int codeEqualityTerm( ** this routine allocates an additional nEq memory cells for internal ** use. */ -static int codeAllEqualityTerms( +static void codeAllEqualityTerms( Parse *pParse, /* Parsing context */ WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */ WhereClause *pWC, /* The WHERE clause */ - Bitmask notReady, /* Which parts of FROM have not yet been coded */ - int nExtraReg /* Number of extra registers to allocate */ + Bitmask notReady /* Which parts of FROM have not yet been coded */ ){ int nEq = pLevel->nEq; /* The number of == or IN constraints to code */ + int termsInMem = 0; /* If true, store value in mem[] cells */ Vdbe *v = pParse->pVdbe; /* The virtual machine under construction */ Index *pIdx = pLevel->pIdx; /* The index being used for this loop */ int iCur = pLevel->iTabCur; /* The cursor of the table */ WhereTerm *pTerm; /* A single constraint term */ int j; /* Loop counter */ - int regBase; /* Base register */ /* Figure out how many memory cells we will need then allocate them. ** We always need at least one used to store the loop terminator ** value. If there are IN operators we'll need one for each == or ** IN constraint. */ - pLevel->iMem = pParse->nMem + 1; - regBase = pParse->nMem + 2; - pParse->nMem += pLevel->nEq + 2 + nExtraReg; + pLevel->iMem = pParse->nMem++; + if( pLevel->flags & WHERE_COLUMN_IN ){ + pParse->nMem += pLevel->nEq; + termsInMem = 1; + } /* Evaluate the equality constraints */ assert( pIdx->nColumn>=nEq ); for(j=0; jaiColumn[j]; pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx); - if( NEVER(pTerm==0) ) break; + if( pTerm==0 ) break; assert( (pTerm->flags & TERM_CODED)==0 ); - r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j); - if( r1!=regBase+j ){ - sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j); - } - testcase( pTerm->eOperator & WO_ISNULL ); - testcase( pTerm->eOperator & WO_IN ); + codeEqualityTerm(pParse, pTerm, pLevel); if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk); + sqlite3VdbeAddOp(v, OP_IsNull, termsInMem ? -1 : -(j+1), pLevel->brk); + } + if( termsInMem ){ + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem+j+1, 1); + } + } + + /* Make sure all the constraint values are on the top of the stack + */ + if( termsInMem ){ + for(j=0; jiMem+j+1, 0); } } - return regBase; } #if defined(SQLITE_TEST) @@ -74640,7 +67039,13 @@ static void whereInfoFree(WhereInfo *pWInfo){ for(i=0; inLevel; i++){ sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo; if( pInfo ){ - assert( pInfo->needToFreeIdxStr==0 ); + if( pInfo->needToFreeIdxStr ){ + /* Coverage: Don't think this can be reached. By the time this + ** function is called, the index-strings have been passed + ** to the vdbe layer for deletion. + */ + sqlite3_free(pInfo->idxStr); + } sqlite3_free(pInfo); } } @@ -74741,8 +67146,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( Parse *pParse, /* The parser context */ SrcList *pTabList, /* A list of all tables to be scanned */ Expr *pWhere, /* The WHERE clause */ - ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */ - u8 wflags /* One of the WHERE_* flags defined in sqliteInt.h */ + ExprList **ppOrderBy /* An ORDER BY clause, or NULL */ ){ int i; /* Loop counter */ WhereInfo *pWInfo; /* Will become the return value of this function */ @@ -74757,7 +67161,6 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( int iFrom; /* First unused FROM clause element */ int andFlags; /* AND-ed combination of all wc.a[].flags */ sqlite3 *db; /* Database connection */ - ExprList *pOrderBy = 0; /* The number of tables in the FROM clause is limited by the number of ** bits in a Bitmask @@ -74767,16 +67170,11 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( return 0; } - if( ppOrderBy ){ - pOrderBy = *ppOrderBy; - } - /* Split the WHERE clause into separate subexpressions where each ** subexpression is separated by an AND operator. */ initMaskSet(&maskSet); whereClauseInit(&wc, pParse, &maskSet); - sqlite3ExprCodeConstants(pParse, pWhere); whereSplit(&wc, pWhere, TK_AND); /* Allocate and initialize the WhereInfo structure that will become the @@ -74797,40 +67195,18 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ** expression and either jump over all of the code or fall thru. */ if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){ - sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1); pWhere = 0; } - /* Assign a bit from the bitmask to every term in the FROM clause. - ** - ** When assigning bitmask values to FROM clause cursors, it must be - ** the case that if X is the bitmask for the N-th FROM clause term then - ** the bitmask for all FROM clause terms to the left of the N-th term - ** is (X-1). An expression from the ON clause of a LEFT JOIN can use - ** its Expr.iRightJoinTable value to find the bitmask of the right table - ** of the join. Subtracting one from the right table bitmask gives a - ** bitmask for all tables to the left of the join. Knowing the bitmask - ** for all tables to the left of a left join is important. Ticket #3015. - */ - for(i=0; inSrc; i++){ - createMask(&maskSet, pTabList->a[i].iCursor); - } -#ifndef NDEBUG - { - Bitmask toTheLeft = 0; - for(i=0; inSrc; i++){ - Bitmask m = getMask(&maskSet, pTabList->a[i].iCursor); - assert( (m-1)==toTheLeft ); - toTheLeft |= m; - } - } -#endif - /* Analyze all of the subexpressions. Note that exprAnalyze() might ** add new virtual terms onto the end of the WHERE clause. We do not ** want to analyze these virtual terms, so start analyzing at the end ** and work forward so that the added virtual terms are never processed. */ + for(i=0; inSrc; i++){ + createMask(&maskSet, pTabList->a[i].iCursor); + } exprAnalyzeAll(pTabList, &wc); if( db->mallocFailed ){ goto whereBeginNoMem; @@ -74922,7 +67298,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( } if( doNotReorder ) break; } - WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ, + WHERETRACE(("*** Optimizer choose table %d for loop %d\n", bestJ, pLevel-pWInfo->a)); if( (bestFlags & WHERE_ORDERBY)!=0 ){ *ppOrderBy = 0; @@ -74950,17 +67326,6 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( *ppOrderBy = 0; } - /* If the caller is an UPDATE or DELETE statement that is requesting - ** to use a one-pass algorithm, determine if this is appropriate. - ** The one-pass algorithm only works if the WHERE clause constraints - ** the statement to update a single row. - */ - assert( (wflags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 ); - if( (wflags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){ - pWInfo->okOnePass = 1; - pWInfo->a[0].flags &= ~WHERE_IDX_ONLY; - } - /* Open all tables in the pTabList and any indices selected for ** searching those tables. */ @@ -74994,7 +67359,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( pLevel->flags & WHERE_ORDERBY ){ zMsg = sqlite3MPrintf(db, "%z ORDER BY", zMsg); } - sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC); + sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC); } #endif /* SQLITE_OMIT_EXPLAIN */ pTabItem = &pTabList->a[pLevel->iFrom]; @@ -75004,18 +67369,16 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( #ifndef SQLITE_OMIT_VIRTUALTABLE if( pLevel->pBestIdx ){ int iCur = pTabItem->iCursor; - sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, - (const char*)pTab->pVtab, P4_VTAB); + sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB); }else #endif if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){ - int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead; - sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op); - if( !pWInfo->okOnePass && pTab->nCol<(sizeof(Bitmask)*8) ){ + sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead); + if( pTab->nCol<(sizeof(Bitmask)*8) ){ Bitmask b = pTabItem->colUsed; int n = 0; for(; b; b=b>>1, n++){} - sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-2, n); + sqlite3VdbeChangeP2(v, sqlite3VdbeCurrentAddr(v)-1, n); assert( n<=pTab->nCol ); } }else{ @@ -75025,10 +67388,11 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( (pIx = pLevel->pIdx)!=0 ){ KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx); assert( pIx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIx->nColumn+1); - sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb, - (char*)pKey, P4_KEYINFO_HANDOFF); - VdbeComment((v, "%s", pIx->zName)); + sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + VdbeComment((v, "# %s", pIx->zName)); + sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum, + (char*)pKey, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1); } sqlite3CodeVerifySchema(pParse, iDb); } @@ -75073,9 +67437,10 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ** row of the left table of the join. */ if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ - pLevel->iLeftJoin = ++pParse->nMem; - sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); - VdbeComment((v, "init LEFT JOIN no-match flag")); + if( !pParse->nMem ) pParse->nMem++; + pLevel->iLeftJoin = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin); + VdbeComment((v, "# init LEFT JOIN no-match flag")); } #ifndef SQLITE_OMIT_VIRTUALTABLE @@ -75084,7 +67449,6 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ** to access the data. */ int j; - int iReg; /* P3 Value for OP_VFilter */ sqlite3_index_info *pBestIdx = pLevel->pBestIdx; int nConstraint = pBestIdx->nConstraint; struct sqlite3_index_constraint_usage *aUsage = @@ -75092,29 +67456,23 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( const struct sqlite3_index_constraint *aConstraint = pBestIdx->aConstraint; - iReg = sqlite3GetTempRange(pParse, nConstraint+2); - pParse->disableColCache++; for(j=1; j<=nConstraint; j++){ int k; for(k=0; kdisableColCache ); - sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1); + sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight); break; } } if( k==nConstraint ) break; } - assert( pParse->disableColCache ); - pParse->disableColCache--; - sqlite3VdbeAddOp2(v, OP_Integer, pBestIdx->idxNum, iReg); - sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1); - sqlite3VdbeAddOp4(v, OP_VFilter, iCur, brk, iReg, pBestIdx->idxStr, - pBestIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC); - sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2); + sqlite3VdbeAddOp(v, OP_Integer, j-1, 0); + sqlite3VdbeAddOp(v, OP_Integer, pBestIdx->idxNum, 0); + sqlite3VdbeOp3(v, OP_VFilter, iCur, brk, pBestIdx->idxStr, + pBestIdx->needToFreeIdxStr ? P3_MPRINTF : P3_STATIC); pBestIdx->needToFreeIdxStr = 0; - for(j=0; jnConstraint; j++){ if( aUsage[j].omit ){ int iTerm = aConstraint[j].iTermOffset; disableTerm(pLevel, &wc.a[iTerm]); @@ -75132,16 +67490,15 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( ** we reference multiple rows using a "rowid IN (...)" ** construct. */ - int r1; pTerm = findTerm(&wc, iCur, -1, notReady, WO_EQ|WO_IN, 0); assert( pTerm!=0 ); assert( pTerm->pExpr!=0 ); assert( pTerm->leftCursor==iCur ); assert( omitTable==0 ); - r1 = codeEqualityTerm(pParse, pTerm, pLevel, 0); + codeEqualityTerm(pParse, pTerm, pLevel); nxt = pLevel->nxt; - sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, nxt); - sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1); + sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt); + sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt); VdbeComment((v, "pk")); pLevel->op = OP_Noop; }else if( pLevel->flags & WHERE_ROWID_RANGE ){ @@ -75161,27 +67518,25 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( } if( pStart ){ Expr *pX; - int r1, regFree1; pX = pStart->pExpr; assert( pX!=0 ); assert( pStart->leftCursor==iCur ); - r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, ®Free1); - sqlite3VdbeAddOp3(v, OP_ForceInt, r1, brk, - pX->op==TK_LE || pX->op==TK_GT); - sqlite3VdbeAddOp3(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk, r1); + sqlite3ExprCode(pParse, pX->pRight); + sqlite3VdbeAddOp(v, OP_ForceInt, pX->op==TK_LE || pX->op==TK_GT, brk); + sqlite3VdbeAddOp(v, bRev ? OP_MoveLt : OP_MoveGe, iCur, brk); VdbeComment((v, "pk")); - sqlite3ReleaseTempReg(pParse, regFree1); disableTerm(pLevel, pStart); }else{ - sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk); + sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk); } if( pEnd ){ Expr *pX; pX = pEnd->pExpr; assert( pX!=0 ); assert( pEnd->leftCursor==iCur ); - pLevel->iMem = ++pParse->nMem; - sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem); + sqlite3ExprCode(pParse, pX->pRight); + pLevel->iMem = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); if( pX->op==TK_LT || pX->op==TK_GT ){ testOp = bRev ? OP_Le : OP_Ge; }else{ @@ -75194,220 +67549,223 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( pLevel->p1 = iCur; pLevel->p2 = start; if( testOp!=OP_Noop ){ - int r1 = sqlite3GetTempReg(pParse); - sqlite3VdbeAddOp2(v, OP_Rowid, iCur, r1); - /* sqlite3VdbeAddOp2(v, OP_SCopy, pLevel->iMem, 0); */ - sqlite3VdbeAddOp3(v, testOp, pLevel->iMem, brk, r1); - sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL); - sqlite3ReleaseTempReg(pParse, r1); + sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); + sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); + sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk); } - }else if( pLevel->flags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){ - /* Case 3: A scan using an index. - ** - ** The WHERE clause may contain zero or more equality - ** terms ("==" or "IN" operators) that refer to the N - ** left-most columns of the index. It may also contain - ** inequality constraints (>, <, >= or <=) on the indexed - ** column that immediately follows the N equalities. Only - ** the right-most column can be an inequality - the rest must - ** use the "==" and "IN" operators. For example, if the - ** index is on (x,y,z), then the following clauses are all - ** optimized: - ** - ** x=5 - ** x=5 AND y=10 - ** x=5 AND y<10 - ** x=5 AND y>5 AND y<10 - ** x=5 AND y=5 AND z<=10 - ** - ** The z<10 term of the following cannot be used, only - ** the x=5 term: - ** - ** x=5 AND z<10 - ** - ** N may be zero if there are inequality constraints. - ** If there are no inequality constraints, then N is at - ** least one. + }else if( pLevel->flags & WHERE_COLUMN_RANGE ){ + /* Case 3: The WHERE clause term that refers to the right-most + ** column of the index is an inequality. For example, if + ** the index is on (x,y,z) and the WHERE clause is of the + ** form "x=5 AND y<10" then this case is used. Only the + ** right-most column can be an inequality - the rest must + ** use the "==" and "IN" operators. ** ** This case is also used when there are no WHERE clause ** constraints but an index is selected anyway, in order ** to force the output order to conform to an ORDER BY. - */ - int aStartOp[] = { - 0, - 0, - OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */ - OP_Last, /* 3: (!start_constraints && startEq && bRev) */ - OP_MoveGt, /* 4: (start_constraints && !startEq && !bRev) */ - OP_MoveLt, /* 5: (start_constraints && !startEq && bRev) */ - OP_MoveGe, /* 6: (start_constraints && startEq && !bRev) */ - OP_MoveLe /* 7: (start_constraints && startEq && bRev) */ - }; - int aEndOp[] = { - OP_Noop, /* 0: (!end_constraints) */ - OP_IdxGE, /* 1: (end_constraints && !bRev) */ - OP_IdxLT /* 2: (end_constraints && bRev) */ - }; + */ + int start; int nEq = pLevel->nEq; - int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */ - int regBase; /* Base register holding constraint values */ - int r1; /* Temp register */ - WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */ - WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */ - int startEq; /* True if range start uses ==, >= or <= */ - int endEq; /* True if range end uses ==, >= or <= */ - int start_constraints; /* Start of range is constrained */ - int k = pIdx->aiColumn[nEq]; /* Column for inequality constraints */ - int nConstraint; /* Number of constraint terms */ - int op; + int topEq=0; /* True if top limit uses ==. False is strictly < */ + int btmEq=0; /* True if btm limit uses ==. False if strictly > */ + int topOp, btmOp; /* Operators for the top and bottom search bounds */ + int testOp; + int topLimit = (pLevel->flags & WHERE_TOP_LIMIT)!=0; + int btmLimit = (pLevel->flags & WHERE_BTM_LIMIT)!=0; /* Generate code to evaluate all constraint terms using == or IN - ** and store the values of those terms in an array of registers - ** starting at regBase. + ** and level the values of those terms on the stack. + */ + codeAllEqualityTerms(pParse, pLevel, &wc, notReady); + + /* Duplicate the equality term values because they will all be + ** used twice: once to make the termination key and once to make the + ** start key. + */ + for(j=0; j or >= + ** operator and the top bound is a < or <= operator. For a descending + ** index the operators are reversed. + */ + if( pIdx->aSortOrder[nEq]==SQLITE_SO_ASC ){ + topOp = WO_LT|WO_LE; + btmOp = WO_GT|WO_GE; + }else{ + topOp = WO_GT|WO_GE; + btmOp = WO_LT|WO_LE; + SWAP(int, topLimit, btmLimit); + } + + /* Generate the termination key. This is the key value that + ** will end the search. There is no termination key if there + ** are no equality terms and no "X<..." term. + ** + ** 2002-Dec-04: On a reverse-order scan, the so-called "termination" + ** key computed here really ends up being the start key. */ - regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2); nxt = pLevel->nxt; - - /* If this loop satisfies a sort order (pOrderBy) request that - ** was passed to this function to implement a "SELECT min(x) ..." - ** query, then the caller will only allow the loop to run for - ** a single iteration. This means that the first row returned - ** should not have a NULL value stored in 'x'. If column 'x' is - ** the first one after the nEq equality constraints in the index, - ** this requires some special handling. - */ - if( (wflags&WHERE_ORDERBY_MIN)!=0 - && (pLevel->flags&WHERE_ORDERBY) - && (pIdx->nColumn>nEq) - ){ - assert( pOrderBy->nExpr==1 ); - assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); - isMinQuery = 1; + if( topLimit ){ + Expr *pX; + int k = pIdx->aiColumn[j]; + pTerm = findTerm(&wc, iCur, k, notReady, topOp, pIdx); + assert( pTerm!=0 ); + pX = pTerm->pExpr; + assert( (pTerm->flags & TERM_CODED)==0 ); + sqlite3ExprCode(pParse, pX->pRight); + sqlite3VdbeAddOp(v, OP_IsNull, -(nEq*2+1), nxt); + topEq = pTerm->eOperator & (WO_LE|WO_GE); + disableTerm(pLevel, pTerm); + testOp = OP_IdxGE; + }else{ + testOp = nEq>0 ? OP_IdxGE : OP_Noop; + topEq = 1; } - - /* Find any inequality constraint terms for the start and end - ** of the range. - */ - if( pLevel->flags & WHERE_TOP_LIMIT ){ - pRangeEnd = findTerm(&wc, iCur, k, notReady, (WO_LT|WO_LE), pIdx); - } - if( pLevel->flags & WHERE_BTM_LIMIT ){ - pRangeStart = findTerm(&wc, iCur, k, notReady, (WO_GT|WO_GE), pIdx); - } - - /* If we are doing a reverse order scan on an ascending index, or - ** a forward order scan on a descending index, interchange the - ** start and end terms (pRangeStart and pRangeEnd). - */ - if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){ - SWAP(WhereTerm *, pRangeEnd, pRangeStart); - } - - testcase( pRangeStart && pRangeStart->eOperator & WO_LE ); - testcase( pRangeStart && pRangeStart->eOperator & WO_GE ); - testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE ); - testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE ); - startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE); - endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE); - start_constraints = pRangeStart || nEq>0; - - /* Seek the index cursor to the start of the range. */ - nConstraint = nEq; - if( pRangeStart ){ - int dcc = pParse->disableColCache; - if( pRangeEnd ){ - pParse->disableColCache++; + if( testOp!=OP_Noop ){ + int nCol = nEq + topLimit; + pLevel->iMem = pParse->nMem++; + buildIndexProbe(v, nCol, pIdx); + if( bRev ){ + int op = topEq ? OP_MoveLe : OP_MoveLt; + sqlite3VdbeAddOp(v, op, iIdxCur, nxt); + }else{ + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); } - sqlite3ExprCode(pParse, pRangeStart->pExpr->pRight, regBase+nEq); - pParse->disableColCache = dcc; - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt); - nConstraint++; - }else if( isMinQuery ){ - sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); - nConstraint++; - startEq = 0; - start_constraints = 1; + }else if( bRev ){ + sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk); } - codeApplyAffinity(pParse, regBase, nConstraint, pIdx); - op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev]; - assert( op!=0 ); - testcase( op==OP_Rewind ); - testcase( op==OP_Last ); - testcase( op==OP_MoveGt ); - testcase( op==OP_MoveGe ); - testcase( op==OP_MoveLe ); - testcase( op==OP_MoveLt ); - sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, - SQLITE_INT_TO_PTR(nConstraint), P4_INT32); - /* Load the value for the inequality constraint at the end of the - ** range (if any). + /* Generate the start key. This is the key that defines the lower + ** bound on the search. There is no start key if there are no + ** equality terms and if there is no "X>..." term. In + ** that case, generate a "Rewind" instruction in place of the + ** start key search. + ** + ** 2002-Dec-04: In the case of a reverse-order search, the so-called + ** "start" key really ends up being used as the termination key. */ - nConstraint = nEq; - if( pRangeEnd ){ - sqlite3ExprCode(pParse, pRangeEnd->pExpr->pRight, regBase+nEq); - sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt); - codeApplyAffinity(pParse, regBase, nEq+1, pIdx); - nConstraint++; + if( btmLimit ){ + Expr *pX; + int k = pIdx->aiColumn[j]; + pTerm = findTerm(&wc, iCur, k, notReady, btmOp, pIdx); + assert( pTerm!=0 ); + pX = pTerm->pExpr; + assert( (pTerm->flags & TERM_CODED)==0 ); + sqlite3ExprCode(pParse, pX->pRight); + sqlite3VdbeAddOp(v, OP_IsNull, -(nEq+1), nxt); + btmEq = pTerm->eOperator & (WO_LE|WO_GE); + disableTerm(pLevel, pTerm); + }else{ + btmEq = 1; + } + if( nEq>0 || btmLimit ){ + int nCol = nEq + btmLimit; + buildIndexProbe(v, nCol, pIdx); + if( bRev ){ + pLevel->iMem = pParse->nMem++; + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); + testOp = OP_IdxLT; + }else{ + int op = btmEq ? OP_MoveGe : OP_MoveGt; + sqlite3VdbeAddOp(v, op, iIdxCur, nxt); + } + }else if( bRev ){ + testOp = OP_Noop; + }else{ + sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk); } - /* Top of the loop body */ - pLevel->p2 = sqlite3VdbeCurrentAddr(v); - - /* Check if the index cursor is past the end of the range. */ - op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)]; - testcase( op==OP_Noop ); - testcase( op==OP_IdxGE ); - testcase( op==OP_IdxLT ); - sqlite3VdbeAddOp4(v, op, iIdxCur, nxt, regBase, - SQLITE_INT_TO_PTR(nConstraint), P4_INT32); - sqlite3VdbeChangeP5(v, endEq!=bRev); - - /* If there are inequality constraints, check that the value - ** of the table column that the inequality contrains is not NULL. - ** If it is, jump to the next iteration of the loop. + /* Generate the the top of the loop. If there is a termination + ** key we have to test for that key and abort at the top of the + ** loop. */ - r1 = sqlite3GetTempReg(pParse); - testcase( pLevel->flags & WHERE_BTM_LIMIT ); - testcase( pLevel->flags & WHERE_TOP_LIMIT ); - if( pLevel->flags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){ - sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1); - sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont); + start = sqlite3VdbeCurrentAddr(v); + if( testOp!=OP_Noop ){ + sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); + sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt); + if( (topEq && !bRev) || (!btmEq && bRev) ){ + sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC); + } + } + if( topLimit | btmLimit ){ + sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq); + sqlite3VdbeAddOp(v, OP_IsNull, 1, cont); } - - /* Seek the table cursor, if required */ if( !omitTable ){ - sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1); - sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1); /* Deferred seek */ + sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0); + sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0); } - sqlite3ReleaseTempReg(pParse, r1); - /* Record the instruction used to terminate the loop. Disable - ** WHERE clause terms made redundant by the index range scan. + /* Record the instruction used to terminate the loop. */ pLevel->op = bRev ? OP_Prev : OP_Next; pLevel->p1 = iIdxCur; - disableTerm(pLevel, pRangeStart); - disableTerm(pLevel, pRangeEnd); + pLevel->p2 = start; + }else if( pLevel->flags & WHERE_COLUMN_EQ ){ + /* Case 4: There is an index and all terms of the WHERE clause that + ** refer to the index using the "==" or "IN" operators. + */ + int start; + int nEq = pLevel->nEq; + + /* Generate code to evaluate all constraint terms using == or IN + ** and leave the values of those terms on the stack. + */ + codeAllEqualityTerms(pParse, pLevel, &wc, notReady); + nxt = pLevel->nxt; + + /* Generate a single key that will be used to both start and terminate + ** the search + */ + buildIndexProbe(v, nEq, pIdx); + sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 0); + + /* Generate code (1) to move to the first matching element of the table. + ** Then generate code (2) that jumps to "nxt" after the cursor is past + ** the last matching element of the table. The code (1) is executed + ** once to initialize the search, the code (2) is executed before each + ** iteration of the scan to see if the scan has finished. */ + if( bRev ){ + /* Scan in reverse order */ + sqlite3VdbeAddOp(v, OP_MoveLe, iIdxCur, nxt); + start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); + sqlite3VdbeAddOp(v, OP_IdxLT, iIdxCur, nxt); + pLevel->op = OP_Prev; + }else{ + /* Scan in the forward order */ + sqlite3VdbeAddOp(v, OP_MoveGe, iIdxCur, nxt); + start = sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); + sqlite3VdbeOp3(v, OP_IdxGE, iIdxCur, nxt, "+", P3_STATIC); + pLevel->op = OP_Next; + } + if( !omitTable ){ + sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0); + sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0); + } + pLevel->p1 = iIdxCur; + pLevel->p2 = start; }else{ - /* Case 4: There is no usable index. We must do a complete + /* Case 5: There is no usable index. We must do a complete ** scan of the entire table. */ assert( omitTable==0 ); assert( bRev==0 ); pLevel->op = OP_Next; pLevel->p1 = iCur; - pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk); + pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk); } notReady &= ~getMask(&maskSet, iCur); + sqlite3VdbeAddOp(v, OP_StackDepth, -1, 0); /* Insert code to test every subexpression that can be completely ** computed using the current set of tables. */ for(pTerm=wc.a, j=wc.nTerm; j>0; j--, pTerm++){ Expr *pE; - testcase( pTerm->flags & TERM_VIRTUAL ); - testcase( pTerm->flags & TERM_CODED ); if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & notReady)!=0 ) continue; pE = pTerm->pExpr; @@ -75415,7 +67773,7 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ continue; } - sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pE, cont, 1); pTerm->flags |= TERM_CODED; } @@ -75424,17 +67782,13 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( */ if( pLevel->iLeftJoin ){ pLevel->top = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); - VdbeComment((v, "record LEFT JOIN hit")); - sqlite3ExprClearColumnCache(pParse, pLevel->iTabCur); - sqlite3ExprClearColumnCache(pParse, pLevel->iIdxCur); + sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin); + VdbeComment((v, "# record LEFT JOIN hit")); for(pTerm=wc.a, j=0; jflags & TERM_VIRTUAL ); - testcase( pTerm->flags & TERM_CODED ); if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & notReady)!=0 ) continue; assert( pTerm->pExpr ); - sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL); + sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1); pTerm->flags |= TERM_CODED; } } @@ -75465,8 +67819,6 @@ SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin( } sqlite3_query_plan[nQPlan++] = ' '; } - testcase( pLevel->flags & WHERE_ROWID_EQ ); - testcase( pLevel->flags & WHERE_ROWID_RANGE ); if( pLevel->flags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){ memcpy(&sqlite3_query_plan[nQPlan], "* ", 2); nQPlan += 2; @@ -75515,12 +67867,11 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ /* Generate loop termination code. */ - sqlite3ExprClearColumnCache(pWInfo->pParse, -1); for(i=pTabList->nSrc-1; i>=0; i--){ pLevel = &pWInfo->a[i]; sqlite3VdbeResolveLabel(v, pLevel->cont); if( pLevel->op!=OP_Noop ){ - sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2); + sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2); } if( pLevel->nIn ){ struct InLoop *pIn; @@ -75528,7 +67879,7 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ sqlite3VdbeResolveLabel(v, pLevel->nxt); for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){ sqlite3VdbeJumpHere(v, pIn->topAddr+1); - sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr); + sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr); sqlite3VdbeJumpHere(v, pIn->topAddr-1); } sqlite3_free(pLevel->aInLoop); @@ -75536,12 +67887,12 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ sqlite3VdbeResolveLabel(v, pLevel->brk); if( pLevel->iLeftJoin ){ int addr; - addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); - sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); + addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0); + sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0); if( pLevel->iIdxCur>=0 ){ - sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); + sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0); } - sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top); + sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top); sqlite3VdbeJumpHere(v, addr); } } @@ -75558,11 +67909,11 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ Table *pTab = pTabItem->pTab; assert( pTab!=0 ); if( pTab->isEphem || pTab->pSelect ) continue; - if( !pWInfo->okOnePass && (pLevel->flags & WHERE_IDX_ONLY)==0 ){ - sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); + if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){ + sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0); } if( pLevel->pIdx!=0 ){ - sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); + sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0); } /* If this scan uses an index, make code substitutions to read data @@ -75619,8 +67970,8 @@ SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){ /* Driver template for the LEMON parser generator. ** The author disclaims copyright to this source code. */ -/* First off, code is included that follows the "include" declaration -** in the input grammar file. */ +/* First off, code is include which follows the "include" declaration +** in the input file. */ /* @@ -75722,8 +68073,11 @@ typedef union { TriggerStep* yy243; struct TrigEvent yy370; SrcList* yy373; + Expr * yy386; struct {int value; int mask;} yy405; + Token yy410; IdList* yy432; + int yy495; } YYMINORTYPE; #ifndef YYSTACKDEPTH #define YYSTACKDEPTH 100 @@ -75732,18 +68086,16 @@ typedef union { #define sqlite3ParserARG_PDECL ,Parse *pParse #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse #define sqlite3ParserARG_STORE yypParser->pParse = pParse -#define YYNSTATE 589 -#define YYNRULE 313 +#define YYNSTATE 588 +#define YYNRULE 312 +#define YYERRORSYMBOL 138 +#define YYERRSYMDT yy495 #define YYFALLBACK 1 #define YY_NO_ACTION (YYNSTATE+YYNRULE+2) #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1) #define YY_ERROR_ACTION (YYNSTATE+YYNRULE) -/* The yyzerominor constant is used to initialize instances of -** YYMINORTYPE objects to zero. */ -static const YYMINORTYPE yyzerominor; - -/* Next are the tables used to determine what action to take based on the +/* Next are that tables used to determine what action to take based on the ** current state and lookahead token. These tables are used to implement ** functions that take a state number and lookahead value and return an ** action integer. @@ -75791,416 +68143,416 @@ static const YYMINORTYPE yyzerominor; ** yy_default[] Default action for each state. */ static const YYACTIONTYPE yy_action[] = { - /* 0 */ 292, 903, 124, 588, 409, 172, 2, 418, 61, 61, - /* 10 */ 61, 61, 519, 63, 63, 63, 63, 64, 64, 65, - /* 20 */ 65, 65, 66, 210, 447, 212, 425, 431, 68, 63, - /* 30 */ 63, 63, 63, 64, 64, 65, 65, 65, 66, 210, - /* 40 */ 391, 388, 396, 451, 60, 59, 297, 435, 436, 432, - /* 50 */ 432, 62, 62, 61, 61, 61, 61, 263, 63, 63, - /* 60 */ 63, 63, 64, 64, 65, 65, 65, 66, 210, 292, - /* 70 */ 493, 494, 418, 489, 208, 82, 67, 420, 69, 154, - /* 80 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66, - /* 90 */ 210, 67, 462, 69, 154, 425, 431, 574, 264, 58, - /* 100 */ 64, 64, 65, 65, 65, 66, 210, 397, 398, 422, - /* 110 */ 422, 422, 292, 60, 59, 297, 435, 436, 432, 432, - /* 120 */ 62, 62, 61, 61, 61, 61, 317, 63, 63, 63, - /* 130 */ 63, 64, 64, 65, 65, 65, 66, 210, 425, 431, - /* 140 */ 94, 65, 65, 65, 66, 210, 396, 210, 414, 34, - /* 150 */ 56, 298, 442, 443, 410, 418, 60, 59, 297, 435, - /* 160 */ 436, 432, 432, 62, 62, 61, 61, 61, 61, 208, - /* 170 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66, - /* 180 */ 210, 292, 372, 524, 295, 572, 113, 408, 522, 451, - /* 190 */ 331, 317, 407, 20, 244, 340, 519, 396, 478, 531, - /* 200 */ 505, 447, 212, 571, 570, 245, 530, 425, 431, 149, - /* 210 */ 150, 397, 398, 414, 41, 211, 151, 533, 488, 489, - /* 220 */ 418, 568, 569, 420, 292, 60, 59, 297, 435, 436, - /* 230 */ 432, 432, 62, 62, 61, 61, 61, 61, 317, 63, - /* 240 */ 63, 63, 63, 64, 64, 65, 65, 65, 66, 210, - /* 250 */ 425, 431, 447, 333, 215, 422, 422, 422, 363, 299, - /* 260 */ 414, 41, 397, 398, 366, 567, 211, 292, 60, 59, - /* 270 */ 297, 435, 436, 432, 432, 62, 62, 61, 61, 61, - /* 280 */ 61, 396, 63, 63, 63, 63, 64, 64, 65, 65, - /* 290 */ 65, 66, 210, 425, 431, 491, 300, 524, 474, 66, - /* 300 */ 210, 214, 474, 229, 411, 286, 534, 20, 449, 523, - /* 310 */ 168, 60, 59, 297, 435, 436, 432, 432, 62, 62, - /* 320 */ 61, 61, 61, 61, 474, 63, 63, 63, 63, 64, - /* 330 */ 64, 65, 65, 65, 66, 210, 209, 480, 317, 77, - /* 340 */ 292, 239, 300, 55, 484, 490, 397, 398, 181, 547, - /* 350 */ 494, 345, 348, 349, 67, 152, 69, 154, 339, 524, - /* 360 */ 414, 35, 350, 241, 221, 370, 425, 431, 579, 20, - /* 370 */ 164, 118, 243, 343, 248, 344, 176, 322, 442, 443, - /* 380 */ 414, 3, 80, 252, 60, 59, 297, 435, 436, 432, - /* 390 */ 432, 62, 62, 61, 61, 61, 61, 174, 63, 63, - /* 400 */ 63, 63, 64, 64, 65, 65, 65, 66, 210, 292, - /* 410 */ 221, 550, 236, 487, 510, 353, 317, 118, 243, 343, - /* 420 */ 248, 344, 176, 181, 317, 532, 345, 348, 349, 252, - /* 430 */ 223, 415, 155, 464, 511, 425, 431, 350, 414, 34, - /* 440 */ 465, 211, 177, 175, 160, 525, 414, 34, 338, 549, - /* 450 */ 449, 323, 168, 60, 59, 297, 435, 436, 432, 432, - /* 460 */ 62, 62, 61, 61, 61, 61, 415, 63, 63, 63, - /* 470 */ 63, 64, 64, 65, 65, 65, 66, 210, 292, 542, - /* 480 */ 335, 517, 504, 541, 456, 572, 302, 19, 331, 144, - /* 490 */ 317, 390, 317, 330, 2, 362, 457, 294, 483, 373, - /* 500 */ 269, 268, 252, 571, 425, 431, 589, 391, 388, 458, - /* 510 */ 208, 495, 414, 49, 414, 49, 303, 586, 894, 230, - /* 520 */ 894, 496, 60, 59, 297, 435, 436, 432, 432, 62, - /* 530 */ 62, 61, 61, 61, 61, 201, 63, 63, 63, 63, - /* 540 */ 64, 64, 65, 65, 65, 66, 210, 292, 317, 181, - /* 550 */ 439, 255, 345, 348, 349, 370, 153, 583, 308, 251, - /* 560 */ 309, 452, 76, 350, 78, 382, 211, 426, 427, 415, - /* 570 */ 414, 27, 319, 425, 431, 440, 1, 22, 586, 893, - /* 580 */ 396, 893, 544, 478, 320, 263, 438, 438, 429, 430, - /* 590 */ 415, 60, 59, 297, 435, 436, 432, 432, 62, 62, - /* 600 */ 61, 61, 61, 61, 237, 63, 63, 63, 63, 64, - /* 610 */ 64, 65, 65, 65, 66, 210, 292, 428, 583, 374, - /* 620 */ 224, 93, 517, 9, 159, 396, 557, 396, 456, 67, - /* 630 */ 396, 69, 154, 399, 400, 401, 320, 328, 438, 438, - /* 640 */ 457, 336, 425, 431, 361, 397, 398, 320, 433, 438, - /* 650 */ 438, 582, 291, 458, 238, 327, 318, 222, 546, 292, - /* 660 */ 60, 59, 297, 435, 436, 432, 432, 62, 62, 61, - /* 670 */ 61, 61, 61, 225, 63, 63, 63, 63, 64, 64, - /* 680 */ 65, 65, 65, 66, 210, 425, 431, 482, 313, 392, - /* 690 */ 397, 398, 397, 398, 207, 397, 398, 825, 273, 517, - /* 700 */ 251, 200, 292, 60, 59, 297, 435, 436, 432, 432, - /* 710 */ 62, 62, 61, 61, 61, 61, 470, 63, 63, 63, - /* 720 */ 63, 64, 64, 65, 65, 65, 66, 210, 425, 431, - /* 730 */ 171, 160, 263, 263, 304, 415, 276, 395, 274, 263, - /* 740 */ 517, 517, 263, 517, 192, 292, 60, 70, 297, 435, - /* 750 */ 436, 432, 432, 62, 62, 61, 61, 61, 61, 379, - /* 760 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66, - /* 770 */ 210, 425, 431, 384, 559, 305, 306, 251, 415, 320, - /* 780 */ 560, 438, 438, 561, 540, 360, 540, 387, 292, 196, - /* 790 */ 59, 297, 435, 436, 432, 432, 62, 62, 61, 61, - /* 800 */ 61, 61, 371, 63, 63, 63, 63, 64, 64, 65, - /* 810 */ 65, 65, 66, 210, 425, 431, 396, 275, 251, 251, - /* 820 */ 172, 250, 418, 415, 386, 367, 178, 179, 180, 469, - /* 830 */ 311, 123, 156, 5, 297, 435, 436, 432, 432, 62, - /* 840 */ 62, 61, 61, 61, 61, 317, 63, 63, 63, 63, - /* 850 */ 64, 64, 65, 65, 65, 66, 210, 72, 324, 194, - /* 860 */ 4, 317, 263, 317, 296, 263, 415, 414, 28, 317, - /* 870 */ 257, 317, 321, 72, 324, 317, 4, 119, 165, 177, - /* 880 */ 296, 397, 398, 414, 23, 414, 32, 418, 321, 326, - /* 890 */ 421, 414, 53, 414, 52, 317, 158, 414, 98, 451, - /* 900 */ 317, 263, 317, 277, 317, 326, 378, 471, 261, 317, - /* 910 */ 259, 18, 478, 445, 445, 451, 317, 414, 96, 75, - /* 920 */ 74, 469, 414, 101, 414, 102, 414, 112, 73, 315, - /* 930 */ 316, 414, 114, 420, 294, 75, 74, 481, 414, 16, - /* 940 */ 381, 317, 279, 467, 73, 315, 316, 72, 324, 420, - /* 950 */ 4, 208, 317, 183, 296, 317, 186, 128, 84, 208, - /* 960 */ 8, 341, 321, 414, 99, 422, 422, 422, 423, 424, - /* 970 */ 11, 623, 380, 307, 414, 33, 413, 414, 97, 326, - /* 980 */ 412, 422, 422, 422, 423, 424, 11, 415, 413, 451, - /* 990 */ 415, 162, 412, 317, 499, 500, 226, 227, 228, 104, - /* 1000 */ 448, 476, 317, 173, 507, 317, 509, 508, 317, 75, - /* 1010 */ 74, 329, 205, 21, 281, 414, 24, 418, 73, 315, - /* 1020 */ 316, 282, 317, 420, 414, 54, 460, 414, 115, 317, - /* 1030 */ 414, 116, 502, 203, 147, 549, 514, 468, 128, 202, - /* 1040 */ 317, 473, 204, 317, 414, 117, 317, 477, 317, 584, - /* 1050 */ 317, 414, 25, 317, 249, 422, 422, 422, 423, 424, - /* 1060 */ 11, 506, 414, 36, 512, 414, 37, 317, 414, 26, - /* 1070 */ 414, 38, 414, 39, 526, 414, 40, 317, 254, 317, - /* 1080 */ 128, 317, 418, 317, 256, 377, 278, 268, 585, 414, - /* 1090 */ 42, 293, 317, 352, 317, 128, 208, 513, 258, 414, - /* 1100 */ 43, 414, 44, 414, 29, 414, 30, 545, 260, 128, - /* 1110 */ 317, 553, 317, 173, 414, 45, 414, 46, 317, 262, - /* 1120 */ 383, 554, 317, 91, 564, 317, 91, 317, 581, 189, - /* 1130 */ 290, 357, 414, 47, 414, 48, 267, 365, 368, 369, - /* 1140 */ 414, 31, 270, 271, 414, 10, 272, 414, 50, 414, - /* 1150 */ 51, 556, 566, 280, 283, 284, 578, 146, 419, 405, - /* 1160 */ 231, 505, 444, 325, 516, 463, 163, 446, 552, 394, - /* 1170 */ 466, 563, 246, 515, 518, 520, 402, 403, 404, 7, - /* 1180 */ 314, 84, 232, 334, 347, 83, 332, 57, 170, 79, - /* 1190 */ 213, 461, 125, 85, 337, 342, 492, 502, 497, 301, - /* 1200 */ 498, 416, 105, 219, 247, 218, 503, 501, 233, 220, - /* 1210 */ 287, 234, 527, 528, 235, 529, 417, 521, 354, 288, - /* 1220 */ 184, 121, 185, 240, 535, 475, 242, 356, 187, 479, - /* 1230 */ 188, 358, 537, 88, 190, 548, 364, 193, 132, 376, - /* 1240 */ 555, 375, 133, 134, 135, 310, 562, 138, 136, 575, - /* 1250 */ 576, 577, 580, 100, 393, 406, 217, 142, 624, 625, - /* 1260 */ 103, 141, 265, 166, 167, 434, 71, 453, 441, 437, - /* 1270 */ 450, 143, 538, 157, 120, 454, 161, 472, 455, 169, - /* 1280 */ 459, 81, 6, 12, 13, 92, 95, 126, 216, 127, - /* 1290 */ 111, 485, 486, 17, 86, 346, 106, 122, 253, 107, - /* 1300 */ 87, 108, 182, 245, 355, 145, 351, 536, 129, 359, - /* 1310 */ 312, 130, 543, 173, 539, 266, 191, 109, 289, 551, - /* 1320 */ 195, 14, 131, 198, 197, 558, 137, 199, 139, 140, - /* 1330 */ 15, 565, 89, 90, 573, 110, 385, 206, 148, 389, - /* 1340 */ 285, 587, + /* 0 */ 292, 89, 397, 93, 158, 164, 350, 511, 82, 82, + /* 10 */ 82, 82, 215, 84, 84, 84, 84, 85, 85, 86, + /* 20 */ 86, 86, 87, 210, 437, 310, 497, 482, 90, 84, + /* 30 */ 84, 84, 84, 85, 85, 86, 86, 86, 87, 210, + /* 40 */ 432, 420, 349, 420, 81, 77, 301, 472, 471, 481, + /* 50 */ 481, 83, 83, 82, 82, 82, 82, 210, 84, 84, + /* 60 */ 84, 84, 85, 85, 86, 86, 86, 87, 210, 292, + /* 70 */ 469, 310, 511, 400, 508, 76, 492, 491, 577, 564, + /* 80 */ 84, 84, 84, 84, 85, 85, 86, 86, 86, 87, + /* 90 */ 210, 395, 394, 219, 581, 497, 482, 486, 485, 75, + /* 100 */ 118, 283, 314, 282, 316, 175, 502, 502, 502, 361, + /* 110 */ 455, 453, 276, 81, 77, 301, 472, 471, 481, 481, + /* 120 */ 83, 83, 82, 82, 82, 82, 488, 84, 84, 84, + /* 130 */ 84, 85, 85, 86, 86, 86, 87, 210, 292, 219, + /* 140 */ 375, 520, 524, 428, 511, 194, 118, 283, 314, 282, + /* 150 */ 316, 175, 9, 391, 222, 375, 450, 89, 276, 93, + /* 160 */ 158, 521, 530, 36, 497, 482, 85, 85, 86, 86, + /* 170 */ 86, 87, 210, 222, 305, 455, 453, 530, 45, 549, + /* 180 */ 370, 292, 81, 77, 301, 472, 471, 481, 481, 83, + /* 190 */ 83, 82, 82, 82, 82, 475, 84, 84, 84, 84, + /* 200 */ 85, 85, 86, 86, 86, 87, 210, 497, 482, 511, + /* 210 */ 388, 505, 155, 296, 258, 449, 224, 335, 213, 439, + /* 220 */ 294, 440, 435, 179, 292, 81, 77, 301, 472, 471, + /* 230 */ 481, 481, 83, 83, 82, 82, 82, 82, 222, 84, + /* 240 */ 84, 84, 84, 85, 85, 86, 86, 86, 87, 210, + /* 250 */ 497, 482, 450, 448, 226, 250, 287, 522, 824, 441, + /* 260 */ 545, 188, 95, 1, 169, 260, 578, 450, 81, 77, + /* 270 */ 301, 472, 471, 481, 481, 83, 83, 82, 82, 82, + /* 280 */ 82, 377, 84, 84, 84, 84, 85, 85, 86, 86, + /* 290 */ 86, 87, 210, 247, 353, 249, 88, 292, 522, 174, + /* 300 */ 358, 432, 113, 369, 254, 255, 450, 443, 221, 389, + /* 310 */ 170, 161, 152, 430, 215, 321, 344, 440, 435, 526, + /* 320 */ 546, 149, 151, 497, 482, 450, 235, 392, 327, 583, + /* 330 */ 20, 469, 440, 435, 373, 508, 173, 172, 171, 65, + /* 340 */ 239, 81, 77, 301, 472, 471, 481, 481, 83, 83, + /* 350 */ 82, 82, 82, 82, 295, 84, 84, 84, 84, 85, + /* 360 */ 85, 86, 86, 86, 87, 210, 292, 502, 502, 502, + /* 370 */ 460, 440, 435, 167, 248, 375, 323, 326, 313, 490, + /* 380 */ 167, 375, 529, 323, 326, 313, 546, 328, 576, 157, + /* 390 */ 440, 435, 497, 482, 328, 484, 20, 530, 42, 366, + /* 400 */ 18, 466, 466, 530, 42, 366, 124, 466, 466, 292, + /* 410 */ 81, 77, 301, 472, 471, 481, 481, 83, 83, 82, + /* 420 */ 82, 82, 82, 522, 84, 84, 84, 84, 85, 85, + /* 430 */ 86, 86, 86, 87, 210, 497, 482, 80, 167, 340, + /* 440 */ 555, 323, 326, 313, 319, 340, 901, 139, 552, 8, + /* 450 */ 341, 2, 328, 81, 77, 301, 472, 471, 481, 481, + /* 460 */ 83, 83, 82, 82, 82, 82, 205, 84, 84, 84, + /* 470 */ 84, 85, 85, 86, 86, 86, 87, 210, 292, 533, + /* 480 */ 375, 496, 406, 57, 86, 86, 86, 87, 210, 375, + /* 490 */ 79, 375, 63, 375, 405, 547, 89, 168, 93, 158, + /* 500 */ 400, 159, 530, 32, 497, 482, 528, 404, 124, 480, + /* 510 */ 450, 530, 32, 530, 45, 530, 24, 450, 395, 463, + /* 520 */ 268, 264, 81, 77, 301, 472, 471, 481, 481, 83, + /* 530 */ 83, 82, 82, 82, 82, 522, 84, 84, 84, 84, + /* 540 */ 85, 85, 86, 86, 86, 87, 210, 292, 300, 375, + /* 550 */ 462, 390, 546, 2, 208, 375, 450, 303, 263, 622, + /* 560 */ 266, 410, 20, 425, 450, 443, 89, 424, 93, 158, + /* 570 */ 191, 530, 25, 497, 482, 440, 435, 530, 42, 352, + /* 580 */ 382, 222, 440, 435, 272, 150, 582, 418, 441, 357, + /* 590 */ 188, 81, 77, 301, 472, 471, 481, 481, 83, 83, + /* 600 */ 82, 82, 82, 82, 522, 84, 84, 84, 84, 85, + /* 610 */ 85, 86, 86, 86, 87, 210, 292, 401, 320, 331, + /* 620 */ 270, 440, 435, 406, 366, 539, 466, 466, 365, 440, + /* 630 */ 435, 580, 561, 457, 892, 405, 892, 559, 579, 91, + /* 640 */ 530, 3, 497, 482, 464, 87, 210, 565, 404, 261, + /* 650 */ 345, 359, 403, 457, 891, 566, 891, 535, 573, 292, + /* 660 */ 81, 77, 301, 472, 471, 481, 481, 83, 83, 82, + /* 670 */ 82, 82, 82, 550, 84, 84, 84, 84, 85, 85, + /* 680 */ 86, 86, 86, 87, 210, 497, 482, 409, 544, 574, + /* 690 */ 385, 415, 211, 550, 519, 518, 539, 368, 571, 535, + /* 700 */ 562, 506, 292, 81, 77, 301, 472, 471, 481, 481, + /* 710 */ 83, 83, 82, 82, 82, 82, 375, 84, 84, 84, + /* 720 */ 84, 85, 85, 86, 86, 86, 87, 210, 497, 482, + /* 730 */ 366, 557, 466, 466, 306, 279, 443, 221, 530, 41, + /* 740 */ 535, 387, 229, 535, 535, 292, 81, 94, 301, 472, + /* 750 */ 471, 481, 481, 83, 83, 82, 82, 82, 82, 375, + /* 760 */ 84, 84, 84, 84, 85, 85, 86, 86, 86, 87, + /* 770 */ 210, 497, 482, 477, 551, 309, 189, 279, 308, 312, + /* 780 */ 147, 530, 10, 588, 516, 317, 445, 445, 292, 318, + /* 790 */ 77, 301, 472, 471, 481, 481, 83, 83, 82, 82, + /* 800 */ 82, 82, 375, 84, 84, 84, 84, 85, 85, 86, + /* 810 */ 86, 86, 87, 210, 497, 482, 553, 478, 279, 91, + /* 820 */ 570, 279, 279, 542, 530, 39, 433, 431, 429, 567, + /* 830 */ 19, 164, 145, 511, 301, 472, 471, 481, 481, 83, + /* 840 */ 83, 82, 82, 82, 82, 186, 84, 84, 84, 84, + /* 850 */ 85, 85, 86, 86, 86, 87, 210, 69, 354, 375, + /* 860 */ 4, 375, 21, 375, 299, 470, 511, 168, 375, 363, + /* 870 */ 334, 375, 364, 69, 354, 62, 4, 525, 375, 522, + /* 880 */ 299, 530, 26, 530, 34, 530, 117, 375, 364, 346, + /* 890 */ 530, 49, 228, 530, 51, 375, 153, 174, 511, 432, + /* 900 */ 530, 27, 375, 553, 375, 346, 459, 570, 22, 530, + /* 910 */ 40, 438, 330, 124, 124, 432, 375, 530, 116, 61, + /* 920 */ 66, 567, 516, 317, 530, 35, 530, 115, 68, 379, + /* 930 */ 378, 511, 540, 508, 223, 61, 66, 531, 530, 54, + /* 940 */ 523, 375, 381, 215, 68, 379, 378, 69, 354, 508, + /* 950 */ 4, 215, 295, 375, 299, 375, 367, 276, 199, 261, + /* 960 */ 517, 215, 364, 530, 48, 502, 502, 502, 500, 499, + /* 970 */ 12, 548, 375, 586, 380, 530, 28, 530, 31, 346, + /* 980 */ 585, 502, 502, 502, 500, 499, 12, 307, 123, 432, + /* 990 */ 442, 177, 522, 304, 530, 38, 231, 233, 234, 103, + /* 1000 */ 238, 555, 375, 281, 160, 375, 363, 375, 230, 61, + /* 1010 */ 66, 503, 166, 271, 236, 124, 196, 204, 68, 379, + /* 1020 */ 378, 232, 375, 508, 530, 23, 375, 530, 43, 530, + /* 1030 */ 33, 375, 468, 203, 489, 448, 261, 261, 522, 163, + /* 1040 */ 277, 375, 176, 375, 530, 53, 251, 375, 530, 29, + /* 1050 */ 375, 522, 375, 530, 37, 502, 502, 502, 500, 499, + /* 1060 */ 12, 214, 458, 530, 52, 530, 98, 375, 55, 530, + /* 1070 */ 96, 217, 530, 101, 530, 102, 375, 493, 498, 540, + /* 1080 */ 261, 375, 540, 375, 535, 374, 245, 255, 555, 530, + /* 1090 */ 112, 293, 375, 507, 375, 290, 215, 261, 530, 114, + /* 1100 */ 375, 261, 375, 530, 46, 530, 16, 162, 161, 261, + /* 1110 */ 375, 165, 375, 261, 530, 99, 530, 44, 537, 291, + /* 1120 */ 384, 501, 530, 50, 530, 47, 252, 274, 446, 564, + /* 1130 */ 253, 362, 530, 97, 530, 30, 360, 356, 504, 256, + /* 1140 */ 311, 119, 246, 351, 343, 522, 342, 262, 399, 265, + /* 1150 */ 376, 267, 237, 269, 225, 6, 534, 587, 148, 538, + /* 1160 */ 510, 325, 280, 285, 240, 417, 515, 444, 584, 541, + /* 1170 */ 452, 461, 347, 259, 315, 561, 487, 184, 465, 532, + /* 1180 */ 494, 200, 108, 454, 426, 436, 423, 422, 73, 421, + /* 1190 */ 7, 383, 297, 137, 71, 128, 62, 241, 333, 514, + /* 1200 */ 70, 336, 74, 120, 130, 372, 242, 371, 243, 509, + /* 1210 */ 244, 133, 513, 134, 135, 136, 483, 355, 190, 447, + /* 1220 */ 337, 193, 64, 56, 298, 473, 411, 111, 289, 197, + /* 1230 */ 198, 142, 568, 563, 558, 398, 339, 201, 92, 393, + /* 1240 */ 220, 202, 322, 127, 207, 543, 275, 209, 496, 554, + /* 1250 */ 536, 278, 288, 78, 414, 218, 17, 100, 212, 479, + /* 1260 */ 575, 121, 72, 332, 572, 527, 284, 556, 156, 302, + /* 1270 */ 140, 216, 104, 122, 132, 324, 105, 560, 273, 329, + /* 1280 */ 110, 109, 206, 512, 11, 67, 260, 13, 338, 5, + /* 1290 */ 396, 143, 126, 195, 402, 407, 412, 154, 419, 125, + /* 1300 */ 348, 416, 168, 257, 427, 144, 107, 192, 434, 286, + /* 1310 */ 451, 456, 138, 59, 60, 187, 58, 15, 467, 474, + /* 1320 */ 185, 183, 495, 129, 141, 180, 569, 182, 131, 178, + /* 1330 */ 624, 623, 14, 106, 408, 413, 181, 476, 386, 146, + /* 1340 */ 227, }; static const YYCODETYPE yy_lookahead[] = { - /* 0 */ 16, 139, 140, 141, 168, 21, 144, 23, 69, 70, - /* 10 */ 71, 72, 176, 74, 75, 76, 77, 78, 79, 80, - /* 20 */ 81, 82, 83, 84, 78, 79, 42, 43, 73, 74, + /* 0 */ 16, 217, 218, 219, 220, 21, 223, 23, 69, 70, + /* 10 */ 71, 72, 110, 74, 75, 76, 77, 78, 79, 80, + /* 20 */ 81, 82, 83, 84, 169, 16, 42, 43, 73, 74, /* 30 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - /* 40 */ 1, 2, 23, 58, 60, 61, 62, 63, 64, 65, - /* 50 */ 66, 67, 68, 69, 70, 71, 72, 147, 74, 75, + /* 40 */ 58, 99, 100, 101, 60, 61, 62, 63, 64, 65, + /* 50 */ 66, 67, 68, 69, 70, 71, 72, 84, 74, 75, /* 60 */ 76, 77, 78, 79, 80, 81, 82, 83, 84, 16, - /* 70 */ 185, 186, 88, 88, 110, 22, 217, 92, 219, 220, + /* 70 */ 88, 16, 88, 147, 92, 22, 42, 43, 185, 186, /* 80 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - /* 90 */ 84, 217, 218, 219, 220, 42, 43, 238, 188, 46, - /* 100 */ 78, 79, 80, 81, 82, 83, 84, 88, 89, 124, - /* 110 */ 125, 126, 16, 60, 61, 62, 63, 64, 65, 66, - /* 120 */ 67, 68, 69, 70, 71, 72, 147, 74, 75, 76, - /* 130 */ 77, 78, 79, 80, 81, 82, 83, 84, 42, 43, - /* 140 */ 44, 80, 81, 82, 83, 84, 23, 84, 169, 170, - /* 150 */ 19, 164, 165, 166, 23, 23, 60, 61, 62, 63, - /* 160 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 110, - /* 170 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - /* 180 */ 84, 16, 123, 147, 150, 147, 21, 167, 168, 58, - /* 190 */ 211, 147, 156, 157, 92, 216, 176, 23, 147, 176, - /* 200 */ 177, 78, 79, 165, 166, 103, 183, 42, 43, 78, - /* 210 */ 79, 88, 89, 169, 170, 228, 180, 181, 169, 88, - /* 220 */ 88, 98, 99, 92, 16, 60, 61, 62, 63, 64, - /* 230 */ 65, 66, 67, 68, 69, 70, 71, 72, 147, 74, + /* 90 */ 84, 165, 166, 84, 181, 42, 43, 63, 64, 46, + /* 100 */ 91, 92, 93, 94, 95, 96, 124, 125, 126, 164, + /* 110 */ 165, 166, 103, 60, 61, 62, 63, 64, 65, 66, + /* 120 */ 67, 68, 69, 70, 71, 72, 92, 74, 75, 76, + /* 130 */ 77, 78, 79, 80, 81, 82, 83, 84, 16, 84, + /* 140 */ 147, 30, 20, 18, 23, 90, 91, 92, 93, 94, + /* 150 */ 95, 96, 19, 227, 228, 147, 23, 217, 103, 219, + /* 160 */ 220, 50, 169, 170, 42, 43, 78, 79, 80, 81, + /* 170 */ 82, 83, 84, 228, 164, 165, 166, 169, 170, 181, + /* 180 */ 55, 16, 60, 61, 62, 63, 64, 65, 66, 67, + /* 190 */ 68, 69, 70, 71, 72, 169, 74, 75, 76, 77, + /* 200 */ 78, 79, 80, 81, 82, 83, 84, 42, 43, 88, + /* 210 */ 142, 143, 147, 102, 221, 11, 148, 209, 210, 94, + /* 220 */ 150, 88, 89, 155, 16, 60, 61, 62, 63, 64, + /* 230 */ 65, 66, 67, 68, 69, 70, 71, 72, 228, 74, /* 240 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - /* 250 */ 42, 43, 78, 209, 210, 124, 125, 126, 224, 208, - /* 260 */ 169, 170, 88, 89, 230, 227, 228, 16, 60, 61, + /* 250 */ 42, 43, 23, 49, 92, 14, 158, 189, 133, 161, + /* 260 */ 162, 163, 19, 19, 155, 103, 23, 23, 60, 61, /* 270 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, - /* 280 */ 72, 23, 74, 75, 76, 77, 78, 79, 80, 81, - /* 290 */ 82, 83, 84, 42, 43, 160, 16, 147, 161, 83, - /* 300 */ 84, 210, 161, 153, 169, 158, 156, 157, 161, 162, - /* 310 */ 163, 60, 61, 62, 63, 64, 65, 66, 67, 68, - /* 320 */ 69, 70, 71, 72, 161, 74, 75, 76, 77, 78, - /* 330 */ 79, 80, 81, 82, 83, 84, 192, 200, 147, 131, - /* 340 */ 16, 200, 16, 199, 20, 169, 88, 89, 90, 185, - /* 350 */ 186, 93, 94, 95, 217, 22, 219, 220, 147, 147, - /* 360 */ 169, 170, 104, 200, 84, 147, 42, 43, 156, 157, - /* 370 */ 90, 91, 92, 93, 94, 95, 96, 164, 165, 166, - /* 380 */ 169, 170, 131, 103, 60, 61, 62, 63, 64, 65, - /* 390 */ 66, 67, 68, 69, 70, 71, 72, 155, 74, 75, - /* 400 */ 76, 77, 78, 79, 80, 81, 82, 83, 84, 16, - /* 410 */ 84, 11, 221, 20, 30, 16, 147, 91, 92, 93, - /* 420 */ 94, 95, 96, 90, 147, 181, 93, 94, 95, 103, - /* 430 */ 212, 189, 155, 27, 50, 42, 43, 104, 169, 170, - /* 440 */ 34, 228, 43, 201, 202, 181, 169, 170, 206, 49, - /* 450 */ 161, 162, 163, 60, 61, 62, 63, 64, 65, 66, - /* 460 */ 67, 68, 69, 70, 71, 72, 189, 74, 75, 76, - /* 470 */ 77, 78, 79, 80, 81, 82, 83, 84, 16, 25, - /* 480 */ 211, 147, 20, 29, 12, 147, 102, 19, 211, 21, - /* 490 */ 147, 141, 147, 216, 144, 41, 24, 98, 20, 99, - /* 500 */ 100, 101, 103, 165, 42, 43, 0, 1, 2, 37, - /* 510 */ 110, 39, 169, 170, 169, 170, 182, 19, 20, 190, - /* 520 */ 22, 49, 60, 61, 62, 63, 64, 65, 66, 67, - /* 530 */ 68, 69, 70, 71, 72, 155, 74, 75, 76, 77, - /* 540 */ 78, 79, 80, 81, 82, 83, 84, 16, 147, 90, - /* 550 */ 20, 20, 93, 94, 95, 147, 155, 59, 215, 225, - /* 560 */ 215, 20, 130, 104, 132, 227, 228, 42, 43, 189, - /* 570 */ 169, 170, 16, 42, 43, 20, 19, 22, 19, 20, - /* 580 */ 23, 22, 18, 147, 106, 147, 108, 109, 63, 64, - /* 590 */ 189, 60, 61, 62, 63, 64, 65, 66, 67, 68, - /* 600 */ 69, 70, 71, 72, 147, 74, 75, 76, 77, 78, - /* 610 */ 79, 80, 81, 82, 83, 84, 16, 92, 59, 55, - /* 620 */ 212, 21, 147, 19, 147, 23, 188, 23, 12, 217, - /* 630 */ 23, 219, 220, 7, 8, 9, 106, 186, 108, 109, - /* 640 */ 24, 147, 42, 43, 208, 88, 89, 106, 92, 108, - /* 650 */ 109, 244, 245, 37, 147, 39, 147, 182, 94, 16, + /* 280 */ 72, 213, 74, 75, 76, 77, 78, 79, 80, 81, + /* 290 */ 82, 83, 84, 52, 224, 54, 131, 16, 189, 43, + /* 300 */ 230, 58, 21, 99, 100, 101, 23, 78, 79, 241, + /* 310 */ 201, 202, 22, 20, 110, 206, 186, 88, 89, 20, + /* 320 */ 147, 78, 79, 42, 43, 23, 153, 98, 147, 156, + /* 330 */ 157, 88, 88, 89, 147, 92, 99, 100, 101, 131, + /* 340 */ 190, 60, 61, 62, 63, 64, 65, 66, 67, 68, + /* 350 */ 69, 70, 71, 72, 98, 74, 75, 76, 77, 78, + /* 360 */ 79, 80, 81, 82, 83, 84, 16, 124, 125, 126, + /* 370 */ 20, 88, 89, 90, 133, 147, 93, 94, 95, 160, + /* 380 */ 90, 147, 80, 93, 94, 95, 147, 104, 169, 155, + /* 390 */ 88, 89, 42, 43, 104, 156, 157, 169, 170, 106, + /* 400 */ 19, 108, 109, 169, 170, 106, 22, 108, 109, 16, + /* 410 */ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, + /* 420 */ 70, 71, 72, 189, 74, 75, 76, 77, 78, 79, + /* 430 */ 80, 81, 82, 83, 84, 42, 43, 44, 90, 211, + /* 440 */ 161, 93, 94, 95, 216, 211, 139, 140, 141, 68, + /* 450 */ 216, 144, 104, 60, 61, 62, 63, 64, 65, 66, + /* 460 */ 67, 68, 69, 70, 71, 72, 19, 74, 75, 76, + /* 470 */ 77, 78, 79, 80, 81, 82, 83, 84, 16, 200, + /* 480 */ 147, 97, 12, 21, 80, 81, 82, 83, 84, 147, + /* 490 */ 130, 147, 132, 147, 24, 20, 217, 22, 219, 220, + /* 500 */ 147, 155, 169, 170, 42, 43, 20, 37, 22, 39, + /* 510 */ 23, 169, 170, 169, 170, 169, 170, 23, 165, 49, + /* 520 */ 14, 147, 60, 61, 62, 63, 64, 65, 66, 67, + /* 530 */ 68, 69, 70, 71, 72, 189, 74, 75, 76, 77, + /* 540 */ 78, 79, 80, 81, 82, 83, 84, 16, 215, 147, + /* 550 */ 141, 20, 147, 144, 210, 147, 23, 215, 52, 112, + /* 560 */ 54, 156, 157, 25, 23, 78, 217, 29, 219, 220, + /* 570 */ 155, 169, 170, 42, 43, 88, 89, 169, 170, 41, + /* 580 */ 227, 228, 88, 89, 147, 180, 181, 238, 161, 162, + /* 590 */ 163, 60, 61, 62, 63, 64, 65, 66, 67, 68, + /* 600 */ 69, 70, 71, 72, 189, 74, 75, 76, 77, 78, + /* 610 */ 79, 80, 81, 82, 83, 84, 16, 168, 147, 211, + /* 620 */ 20, 88, 89, 12, 106, 176, 108, 109, 213, 88, + /* 630 */ 89, 176, 177, 19, 20, 24, 22, 20, 183, 22, + /* 640 */ 169, 170, 42, 43, 20, 83, 84, 114, 37, 147, + /* 650 */ 39, 236, 20, 19, 20, 114, 22, 147, 147, 16, /* 660 */ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, - /* 670 */ 70, 71, 72, 145, 74, 75, 76, 77, 78, 79, - /* 680 */ 80, 81, 82, 83, 84, 42, 43, 80, 142, 143, - /* 690 */ 88, 89, 88, 89, 148, 88, 89, 133, 14, 147, - /* 700 */ 225, 155, 16, 60, 61, 62, 63, 64, 65, 66, - /* 710 */ 67, 68, 69, 70, 71, 72, 114, 74, 75, 76, + /* 670 */ 70, 71, 72, 59, 74, 75, 76, 77, 78, 79, + /* 680 */ 80, 81, 82, 83, 84, 42, 43, 167, 168, 22, + /* 690 */ 188, 59, 182, 59, 91, 92, 176, 16, 203, 147, + /* 700 */ 7, 8, 16, 60, 61, 62, 63, 64, 65, 66, + /* 710 */ 67, 68, 69, 70, 71, 72, 147, 74, 75, 76, /* 720 */ 77, 78, 79, 80, 81, 82, 83, 84, 42, 43, - /* 730 */ 201, 202, 147, 147, 182, 189, 52, 147, 54, 147, - /* 740 */ 147, 147, 147, 147, 155, 16, 60, 61, 62, 63, - /* 750 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 213, + /* 730 */ 106, 147, 108, 109, 182, 225, 78, 79, 169, 170, + /* 740 */ 147, 239, 147, 147, 147, 16, 60, 61, 62, 63, + /* 750 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 147, /* 760 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - /* 770 */ 84, 42, 43, 188, 188, 182, 182, 225, 189, 106, - /* 780 */ 188, 108, 109, 188, 99, 100, 101, 241, 16, 155, + /* 770 */ 84, 42, 43, 92, 147, 182, 22, 225, 182, 182, + /* 780 */ 113, 169, 170, 0, 1, 2, 124, 125, 16, 80, /* 790 */ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, - /* 800 */ 71, 72, 213, 74, 75, 76, 77, 78, 79, 80, - /* 810 */ 81, 82, 83, 84, 42, 43, 23, 133, 225, 225, - /* 820 */ 21, 225, 23, 189, 239, 236, 99, 100, 101, 22, - /* 830 */ 242, 243, 155, 191, 62, 63, 64, 65, 66, 67, - /* 840 */ 68, 69, 70, 71, 72, 147, 74, 75, 76, 77, - /* 850 */ 78, 79, 80, 81, 82, 83, 84, 16, 17, 22, - /* 860 */ 19, 147, 147, 147, 23, 147, 189, 169, 170, 147, - /* 870 */ 14, 147, 31, 16, 17, 147, 19, 147, 19, 43, - /* 880 */ 23, 88, 89, 169, 170, 169, 170, 88, 31, 48, - /* 890 */ 147, 169, 170, 169, 170, 147, 89, 169, 170, 58, - /* 900 */ 147, 147, 147, 188, 147, 48, 188, 114, 52, 147, - /* 910 */ 54, 19, 147, 124, 125, 58, 147, 169, 170, 78, - /* 920 */ 79, 114, 169, 170, 169, 170, 169, 170, 87, 88, - /* 930 */ 89, 169, 170, 92, 98, 78, 79, 80, 169, 170, - /* 940 */ 91, 147, 188, 22, 87, 88, 89, 16, 17, 92, - /* 950 */ 19, 110, 147, 155, 23, 147, 155, 22, 121, 110, - /* 960 */ 68, 80, 31, 169, 170, 124, 125, 126, 127, 128, - /* 970 */ 129, 112, 123, 208, 169, 170, 107, 169, 170, 48, - /* 980 */ 111, 124, 125, 126, 127, 128, 129, 189, 107, 58, - /* 990 */ 189, 5, 111, 147, 7, 8, 10, 11, 12, 13, - /* 1000 */ 161, 20, 147, 22, 178, 147, 91, 92, 147, 78, - /* 1010 */ 79, 147, 26, 19, 28, 169, 170, 23, 87, 88, - /* 1020 */ 89, 35, 147, 92, 169, 170, 147, 169, 170, 147, - /* 1030 */ 169, 170, 97, 47, 113, 49, 20, 203, 22, 53, - /* 1040 */ 147, 147, 56, 147, 169, 170, 147, 147, 147, 20, - /* 1050 */ 147, 169, 170, 147, 147, 124, 125, 126, 127, 128, - /* 1060 */ 129, 147, 169, 170, 178, 169, 170, 147, 169, 170, - /* 1070 */ 169, 170, 169, 170, 147, 169, 170, 147, 20, 147, - /* 1080 */ 22, 147, 88, 147, 147, 99, 100, 101, 59, 169, - /* 1090 */ 170, 105, 147, 20, 147, 22, 110, 178, 147, 169, - /* 1100 */ 170, 169, 170, 169, 170, 169, 170, 20, 147, 22, - /* 1110 */ 147, 20, 147, 22, 169, 170, 169, 170, 147, 147, - /* 1120 */ 134, 20, 147, 22, 20, 147, 22, 147, 20, 232, - /* 1130 */ 22, 233, 169, 170, 169, 170, 147, 147, 147, 147, - /* 1140 */ 169, 170, 147, 147, 169, 170, 147, 169, 170, 169, - /* 1150 */ 170, 147, 147, 147, 147, 147, 147, 191, 161, 149, - /* 1160 */ 193, 177, 229, 223, 161, 172, 6, 229, 194, 146, - /* 1170 */ 172, 194, 172, 172, 172, 161, 146, 146, 146, 22, - /* 1180 */ 154, 121, 194, 118, 173, 119, 116, 120, 112, 130, - /* 1190 */ 222, 152, 152, 98, 115, 98, 171, 97, 171, 40, - /* 1200 */ 179, 189, 19, 84, 171, 226, 171, 173, 195, 226, - /* 1210 */ 174, 196, 171, 171, 197, 171, 198, 179, 15, 174, - /* 1220 */ 151, 60, 151, 204, 152, 205, 204, 152, 151, 205, - /* 1230 */ 152, 38, 152, 130, 151, 184, 152, 184, 19, 15, - /* 1240 */ 194, 152, 187, 187, 187, 152, 194, 184, 187, 33, - /* 1250 */ 152, 152, 137, 159, 1, 20, 175, 214, 112, 112, - /* 1260 */ 175, 214, 234, 112, 112, 92, 19, 11, 20, 107, - /* 1270 */ 20, 19, 235, 19, 32, 20, 112, 114, 20, 22, - /* 1280 */ 20, 22, 117, 22, 117, 237, 237, 19, 44, 20, - /* 1290 */ 240, 20, 20, 231, 19, 44, 19, 243, 20, 19, - /* 1300 */ 19, 19, 96, 103, 16, 21, 44, 17, 98, 36, - /* 1310 */ 246, 45, 45, 22, 51, 133, 98, 19, 5, 1, - /* 1320 */ 122, 19, 102, 14, 113, 17, 113, 115, 102, 122, - /* 1330 */ 19, 123, 68, 68, 20, 14, 57, 135, 19, 3, - /* 1340 */ 136, 4, + /* 800 */ 71, 72, 147, 74, 75, 76, 77, 78, 79, 80, + /* 810 */ 81, 82, 83, 84, 42, 43, 107, 20, 225, 22, + /* 820 */ 111, 225, 225, 147, 169, 170, 7, 8, 9, 22, + /* 830 */ 19, 21, 21, 23, 62, 63, 64, 65, 66, 67, + /* 840 */ 68, 69, 70, 71, 72, 155, 74, 75, 76, 77, + /* 850 */ 78, 79, 80, 81, 82, 83, 84, 16, 17, 147, + /* 860 */ 19, 147, 19, 147, 23, 20, 23, 22, 147, 147, + /* 870 */ 16, 147, 31, 16, 17, 121, 19, 178, 147, 189, + /* 880 */ 23, 169, 170, 169, 170, 169, 170, 147, 31, 48, + /* 890 */ 169, 170, 145, 169, 170, 147, 89, 43, 88, 58, + /* 900 */ 169, 170, 147, 107, 147, 48, 20, 111, 22, 169, + /* 910 */ 170, 20, 20, 22, 22, 58, 147, 169, 170, 78, + /* 920 */ 79, 114, 1, 2, 169, 170, 169, 170, 87, 88, + /* 930 */ 89, 88, 147, 92, 212, 78, 79, 80, 169, 170, + /* 940 */ 178, 147, 91, 110, 87, 88, 89, 16, 17, 92, + /* 950 */ 19, 110, 98, 147, 23, 147, 123, 103, 155, 147, + /* 960 */ 178, 110, 31, 169, 170, 124, 125, 126, 127, 128, + /* 970 */ 129, 147, 147, 27, 123, 169, 170, 169, 170, 48, + /* 980 */ 34, 124, 125, 126, 127, 128, 129, 242, 243, 58, + /* 990 */ 161, 5, 189, 208, 169, 170, 10, 11, 12, 13, + /* 1000 */ 188, 161, 147, 147, 155, 147, 147, 147, 147, 78, + /* 1010 */ 79, 147, 26, 20, 28, 22, 232, 155, 87, 88, + /* 1020 */ 89, 35, 147, 92, 169, 170, 147, 169, 170, 169, + /* 1030 */ 170, 147, 147, 47, 147, 49, 147, 147, 189, 53, + /* 1040 */ 200, 147, 56, 147, 169, 170, 147, 147, 169, 170, + /* 1050 */ 147, 189, 147, 169, 170, 124, 125, 126, 127, 128, + /* 1060 */ 129, 192, 147, 169, 170, 169, 170, 147, 199, 169, + /* 1070 */ 170, 212, 169, 170, 169, 170, 147, 188, 188, 147, + /* 1080 */ 147, 147, 147, 147, 147, 99, 100, 101, 161, 169, + /* 1090 */ 170, 105, 147, 20, 147, 22, 110, 147, 169, 170, + /* 1100 */ 147, 147, 147, 169, 170, 169, 170, 201, 202, 147, + /* 1110 */ 147, 155, 147, 147, 169, 170, 169, 170, 244, 245, + /* 1120 */ 134, 188, 169, 170, 169, 170, 147, 200, 185, 186, + /* 1130 */ 147, 147, 169, 170, 169, 170, 147, 147, 188, 147, + /* 1140 */ 208, 147, 188, 208, 147, 189, 233, 147, 147, 147, + /* 1150 */ 188, 147, 147, 147, 188, 191, 161, 172, 191, 172, + /* 1160 */ 161, 173, 225, 172, 193, 149, 194, 229, 172, 161, + /* 1170 */ 229, 194, 38, 234, 98, 177, 137, 6, 146, 172, + /* 1180 */ 171, 112, 240, 152, 146, 152, 33, 146, 237, 146, + /* 1190 */ 22, 154, 152, 19, 237, 214, 121, 194, 118, 189, + /* 1200 */ 119, 116, 120, 60, 184, 15, 195, 152, 196, 194, + /* 1210 */ 197, 187, 198, 187, 187, 187, 194, 152, 184, 184, + /* 1220 */ 15, 151, 130, 130, 40, 179, 152, 19, 174, 152, + /* 1230 */ 151, 214, 171, 171, 171, 152, 152, 151, 98, 152, + /* 1240 */ 222, 151, 115, 152, 84, 179, 204, 226, 97, 205, + /* 1250 */ 205, 204, 174, 19, 235, 226, 231, 159, 44, 171, + /* 1260 */ 171, 32, 19, 3, 20, 20, 171, 173, 112, 246, + /* 1270 */ 20, 175, 175, 243, 19, 44, 19, 114, 20, 44, + /* 1280 */ 19, 19, 96, 4, 117, 22, 103, 22, 16, 117, + /* 1290 */ 17, 21, 98, 22, 20, 20, 20, 19, 51, 45, + /* 1300 */ 36, 11, 22, 133, 45, 19, 19, 98, 20, 5, + /* 1310 */ 1, 20, 102, 19, 68, 122, 68, 19, 107, 92, + /* 1320 */ 113, 14, 17, 102, 122, 112, 123, 115, 113, 112, + /* 1330 */ 112, 112, 19, 14, 20, 20, 135, 1, 57, 19, + /* 1340 */ 136, }; -#define YY_SHIFT_USE_DFLT (-62) +#define YY_SHIFT_USE_DFLT (-99) #define YY_SHIFT_MAX 389 static const short yy_shift_ofst[] = { - /* 0 */ 39, 841, 986, -16, 841, 931, 931, 258, 123, -36, - /* 10 */ 96, 931, 931, 931, 931, 931, -45, 400, 174, 19, - /* 20 */ 132, -54, -54, 53, 165, 208, 251, 324, 393, 462, - /* 30 */ 531, 600, 643, 686, 643, 643, 643, 643, 643, 643, - /* 40 */ 643, 643, 643, 643, 643, 643, 643, 643, 643, 643, + /* 0 */ 921, 841, 986, -16, 841, 931, 931, 283, 229, -98, + /* 10 */ 393, 931, 931, 931, 931, 931, -45, 204, 487, 494, + /* 20 */ 121, 658, 658, 53, 122, 165, 281, 208, 462, 600, + /* 30 */ 531, 350, 643, 643, 643, 643, 643, 643, 643, 643, + /* 40 */ 643, 643, 643, 643, 643, 643, 643, 686, 643, 643, /* 50 */ 643, 643, 729, 772, 772, 857, 931, 931, 931, 931, /* 60 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931, /* 70 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931, /* 80 */ 931, 931, 931, 931, 931, 931, 931, 931, 931, 931, /* 90 */ 931, 931, 931, 931, 931, 931, -61, -61, 6, 6, - /* 100 */ 280, 22, 61, 399, 564, 19, 19, 19, 19, 19, - /* 110 */ 19, 19, 216, 132, 63, -62, -62, -62, 131, 326, - /* 120 */ 472, 472, 498, 559, 506, 799, 19, 799, 19, 19, - /* 130 */ 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, - /* 140 */ 19, 849, 59, -36, -36, -36, -62, -62, -62, -15, - /* 150 */ -15, 333, 459, 478, 557, 530, 541, 616, 602, 793, - /* 160 */ 604, 607, 626, 19, 19, 881, 19, 19, 994, 19, - /* 170 */ 19, 807, 19, 19, 673, 807, 19, 19, 384, 384, - /* 180 */ 384, 19, 19, 673, 19, 19, 673, 19, 454, 685, - /* 190 */ 19, 19, 673, 19, 19, 19, 673, 19, 19, 19, - /* 200 */ 673, 673, 19, 19, 19, 19, 19, 468, 869, 921, - /* 210 */ 132, 789, 789, 432, 406, 406, 406, 836, 406, 132, - /* 220 */ 406, 132, 935, 837, 837, 1160, 1160, 1160, 1160, 1157, - /* 230 */ -36, 1060, 1065, 1066, 1070, 1067, 1059, 1076, 1076, 1095, - /* 240 */ 1079, 1095, 1079, 1097, 1097, 1159, 1097, 1100, 1097, 1183, - /* 250 */ 1119, 1119, 1159, 1097, 1097, 1097, 1183, 1203, 1076, 1203, - /* 260 */ 1076, 1203, 1076, 1076, 1193, 1103, 1203, 1076, 1161, 1161, - /* 270 */ 1219, 1060, 1076, 1224, 1224, 1224, 1224, 1060, 1161, 1219, - /* 280 */ 1076, 1216, 1216, 1076, 1076, 1115, -62, -62, -62, -62, - /* 290 */ -62, -62, 525, 684, 727, 856, 859, 556, 555, 981, - /* 300 */ 102, 987, 915, 1016, 1058, 1073, 1087, 1091, 1101, 1104, - /* 310 */ 892, 1108, 1029, 1253, 1235, 1146, 1147, 1151, 1152, 1173, - /* 320 */ 1162, 1247, 1248, 1250, 1252, 1256, 1254, 1255, 1257, 1258, - /* 330 */ 1260, 1259, 1165, 1261, 1167, 1259, 1163, 1268, 1269, 1164, - /* 340 */ 1271, 1272, 1242, 1244, 1275, 1251, 1277, 1278, 1280, 1281, - /* 350 */ 1262, 1282, 1206, 1200, 1288, 1290, 1284, 1210, 1273, 1263, - /* 360 */ 1266, 1291, 1267, 1182, 1218, 1298, 1313, 1318, 1220, 1264, - /* 370 */ 1265, 1198, 1302, 1211, 1309, 1212, 1308, 1213, 1226, 1207, - /* 380 */ 1311, 1208, 1314, 1321, 1279, 1202, 1204, 1319, 1336, 1337, + /* 100 */ 55, 88, 404, 125, 854, 494, 494, 494, 494, 494, + /* 110 */ 494, 494, 562, 121, -27, -99, -99, -99, 243, 9, + /* 120 */ 470, 470, 614, 634, 494, 494, 494, 810, 851, 494, + /* 130 */ 494, 494, 494, 494, 494, 494, 494, 494, 494, 783, + /* 140 */ 810, 494, 833, -98, -98, -98, -99, -99, -99, -18, + /* 150 */ 290, -18, 348, 541, 611, 533, 302, 624, 244, 299, + /* 160 */ 293, 133, 807, 494, 494, 518, 494, 494, 494, 518, + /* 170 */ 807, 111, 111, 111, 494, 494, 494, 819, 494, 518, + /* 180 */ 494, 494, 494, 494, 494, 494, 518, 494, 843, 494, + /* 190 */ 494, 518, 494, 494, 494, 494, -58, 538, 494, 518, + /* 200 */ 494, 494, 494, 494, 518, 709, 494, 121, 946, 946, + /* 210 */ 121, 384, 946, 946, 667, 796, 256, 754, 946, 121, + /* 220 */ 360, 662, 662, 754, 811, 1134, 1076, 1039, 1171, 1069, + /* 230 */ 1069, 1171, 1153, 1171, 1171, 1168, 1153, 1069, 1174, -98, + /* 240 */ 1075, 1080, 1081, 1085, 1082, 1143, 1075, 1190, 1190, 1190, + /* 250 */ 1190, 1069, 1075, 1174, 1143, 1143, 1069, 1205, 1092, 1093, + /* 260 */ 1184, 1069, 1069, 1205, 1069, 1069, 1205, 1069, 1205, 1208, + /* 270 */ 1076, 1076, 1069, 1076, 1140, 1127, 1184, 1140, 1127, 1160, + /* 280 */ 1160, 1208, 1076, 1076, 1151, 1076, -99, -99, -99, -99, + /* 290 */ -99, -99, 34, 241, 506, 237, 603, 381, 693, 447, + /* 300 */ 617, 681, 632, 797, 845, 886, 891, 1073, 993, 892, + /* 310 */ 162, 475, 486, 1234, 1214, 1229, 1243, 1260, 1244, 1245, + /* 320 */ 1156, 1250, 1255, 1231, 1257, 1258, 1261, 1163, 1235, 1262, + /* 330 */ 1186, 1263, 1279, 1167, 1183, 1265, 1172, 1272, 1273, 1270, + /* 340 */ 1263, 1274, 1194, 1275, 1271, 1276, 1278, 1264, 1247, 1254, + /* 350 */ 1290, 1280, 1259, 1170, 1286, 1209, 1287, 1288, 1304, 1309, + /* 360 */ 1210, 1291, 1246, 1248, 1294, 1193, 1211, 1298, 1227, 1207, + /* 370 */ 1307, 1212, 1305, 1213, 1215, 1217, 1221, 1202, 1218, 1219, + /* 380 */ 1313, 1203, 1314, 1315, 1319, 1281, 1201, 1204, 1336, 1320, }; -#define YY_REDUCE_USE_DFLT (-165) +#define YY_REDUCE_USE_DFLT (-218) #define YY_REDUCE_MAX 291 static const short yy_reduce_ofst[] = { - /* 0 */ -138, 277, 546, 137, 401, -21, 44, 36, 38, 242, - /* 10 */ -141, 191, 91, 269, 343, 345, -126, 589, 338, 150, - /* 20 */ 147, -13, 213, 412, 412, 412, 412, 412, 412, 412, - /* 30 */ 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, - /* 40 */ 412, 412, 412, 412, 412, 412, 412, 412, 412, 412, - /* 50 */ 412, 412, 412, 412, 412, 211, 698, 714, 716, 722, - /* 60 */ 724, 728, 748, 753, 755, 757, 762, 769, 794, 805, - /* 70 */ 808, 846, 855, 858, 861, 875, 882, 893, 896, 899, - /* 80 */ 901, 903, 906, 920, 930, 932, 934, 936, 945, 947, - /* 90 */ 963, 965, 971, 975, 978, 980, 412, 412, 412, 412, - /* 100 */ 20, 412, 412, 23, 34, 334, 475, 552, 593, 594, - /* 110 */ 585, 212, 412, 289, 412, 412, 412, 412, 135, -164, - /* 120 */ -115, 164, 407, 407, 350, 141, 51, 163, 596, -90, - /* 130 */ 436, 218, 765, 438, 586, 592, 595, 715, 718, 408, - /* 140 */ 754, 380, 634, 677, 798, 801, 144, 529, 588, 49, - /* 150 */ 176, 244, 264, 329, 457, 329, 329, 451, 477, 494, - /* 160 */ 507, 509, 528, 590, 730, 642, 509, 743, 839, 864, - /* 170 */ 879, 834, 894, 900, 329, 834, 907, 914, 826, 886, - /* 180 */ 919, 927, 937, 329, 951, 961, 329, 972, 897, 898, - /* 190 */ 989, 990, 329, 991, 992, 995, 329, 996, 999, 1004, - /* 200 */ 329, 329, 1005, 1006, 1007, 1008, 1009, 1010, 966, 967, - /* 210 */ 997, 933, 938, 940, 993, 998, 1000, 984, 1001, 1003, - /* 220 */ 1002, 1014, 1011, 974, 977, 1023, 1030, 1031, 1032, 1026, - /* 230 */ 1012, 988, 1013, 1015, 1017, 1018, 968, 1039, 1040, 1019, - /* 240 */ 1020, 1022, 1024, 1025, 1027, 1021, 1033, 1034, 1035, 1036, - /* 250 */ 979, 983, 1038, 1041, 1042, 1044, 1045, 1069, 1072, 1071, - /* 260 */ 1075, 1077, 1078, 1080, 1028, 1037, 1083, 1084, 1051, 1053, - /* 270 */ 1043, 1046, 1089, 1055, 1056, 1057, 1061, 1052, 1063, 1047, - /* 280 */ 1093, 1048, 1049, 1098, 1099, 1050, 1094, 1081, 1085, 1062, - /* 290 */ 1054, 1064, + /* 0 */ 307, 234, 68, 279, 346, 8, 228, 405, -74, 109, + /* 10 */ 349, 408, -7, 344, 333, 342, -216, 415, 353, 173, + /* 20 */ 98, 10, -55, -60, -60, -60, -60, -60, -60, -60, + /* 30 */ -60, -60, -60, -60, -60, -60, -60, -60, -60, -60, + /* 40 */ -60, -60, -60, -60, -60, -60, -60, -60, -60, -60, + /* 50 */ -60, -60, -60, -60, -60, 471, 569, 612, 655, 712, + /* 60 */ 714, 716, 721, 724, 731, 740, 748, 755, 757, 769, + /* 70 */ 794, 806, 808, 825, 855, 858, 860, 875, 879, 402, + /* 80 */ 884, 894, 896, 900, 903, 905, 920, 929, 934, 936, + /* 90 */ 945, 947, 953, 955, 963, 965, -60, -60, -60, -60, + /* 100 */ 520, -60, -60, 70, 455, 510, 502, 552, 239, 593, + /* 110 */ 596, 597, -60, 427, -60, -60, -60, -60, 219, 449, + /* 120 */ 943, -107, 874, 874, 937, 935, 966, 927, 956, 859, + /* 130 */ 962, 954, 932, 950, 933, 890, 889, 785, 722, 409, + /* 140 */ 840, 812, 690, 803, 849, 862, 745, 906, 869, -145, + /* 150 */ -87, 26, -2, 65, 130, 181, 187, 150, 374, 150, + /* 160 */ 150, 437, 495, 511, 584, 150, 595, 627, 676, 150, + /* 170 */ 495, 699, 762, 782, 824, 856, 861, 747, 187, 150, + /* 180 */ 864, 885, 887, 899, 915, 979, 150, 983, 829, 984, + /* 190 */ 989, 150, 990, 992, 994, 997, 913, 784, 1000, 150, + /* 200 */ 1001, 1002, 1004, 1005, 150, 964, 1006, 995, 985, 987, + /* 210 */ 999, 988, 991, 996, 971, 967, 998, 972, 1007, 1008, + /* 220 */ -217, 938, 941, 977, 1016, 939, 1009, 942, 1032, 1031, + /* 230 */ 1033, 1038, 951, 1041, 1043, 1037, 957, 1040, 981, 1010, + /* 240 */ 1003, 1011, 1012, 1013, 1014, 1020, 1015, 1024, 1026, 1027, + /* 250 */ 1028, 1055, 1022, 1017, 1034, 1035, 1065, 1070, 1018, 1019, + /* 260 */ 1046, 1074, 1077, 1079, 1083, 1084, 1086, 1087, 1090, 1054, + /* 270 */ 1061, 1062, 1091, 1063, 1042, 1044, 1066, 1047, 1045, 1021, + /* 280 */ 1029, 1078, 1088, 1089, 1094, 1095, 1025, 1098, 1096, 1097, + /* 290 */ 1030, 1023, }; static const YYACTIONTYPE yy_default[] = { - /* 0 */ 595, 820, 902, 710, 902, 820, 902, 902, 848, 714, - /* 10 */ 877, 818, 902, 902, 902, 902, 792, 902, 848, 902, - /* 20 */ 626, 848, 848, 743, 902, 902, 902, 902, 902, 902, - /* 30 */ 902, 902, 744, 902, 822, 817, 813, 815, 814, 821, - /* 40 */ 745, 734, 741, 748, 726, 861, 750, 751, 757, 758, - /* 50 */ 878, 876, 780, 779, 798, 902, 902, 902, 902, 902, - /* 60 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 70 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 80 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 90 */ 902, 902, 902, 902, 902, 902, 782, 804, 781, 791, - /* 100 */ 619, 783, 784, 679, 614, 902, 902, 902, 902, 902, - /* 110 */ 902, 902, 785, 902, 786, 799, 800, 801, 902, 902, - /* 120 */ 902, 902, 902, 902, 595, 710, 902, 710, 902, 902, - /* 130 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 140 */ 902, 902, 902, 902, 902, 902, 704, 714, 895, 902, - /* 150 */ 902, 670, 902, 902, 902, 902, 902, 902, 902, 902, - /* 160 */ 902, 902, 602, 600, 902, 702, 902, 902, 628, 902, - /* 170 */ 902, 712, 902, 902, 717, 718, 902, 902, 902, 902, - /* 180 */ 902, 902, 902, 616, 902, 902, 691, 902, 854, 902, - /* 190 */ 902, 902, 868, 902, 902, 902, 866, 902, 902, 902, - /* 200 */ 693, 753, 834, 902, 881, 883, 902, 902, 702, 711, - /* 210 */ 902, 902, 902, 816, 737, 737, 737, 649, 737, 902, - /* 220 */ 737, 902, 652, 747, 747, 599, 599, 599, 599, 669, - /* 230 */ 902, 747, 738, 740, 730, 742, 902, 719, 719, 727, - /* 240 */ 729, 727, 729, 681, 681, 666, 681, 652, 681, 826, - /* 250 */ 831, 831, 666, 681, 681, 681, 826, 611, 719, 611, - /* 260 */ 719, 611, 719, 719, 858, 860, 611, 719, 683, 683, - /* 270 */ 759, 747, 719, 690, 690, 690, 690, 747, 683, 759, - /* 280 */ 719, 880, 880, 719, 719, 888, 636, 654, 654, 863, - /* 290 */ 895, 900, 902, 902, 902, 902, 766, 902, 902, 902, - /* 300 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 310 */ 841, 902, 902, 902, 902, 771, 767, 902, 768, 902, - /* 320 */ 696, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 330 */ 902, 819, 902, 731, 902, 739, 902, 902, 902, 902, - /* 340 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 350 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 360 */ 856, 857, 902, 902, 902, 902, 902, 902, 902, 902, - /* 370 */ 902, 902, 902, 902, 902, 902, 902, 902, 902, 902, - /* 380 */ 902, 902, 902, 902, 887, 902, 902, 890, 596, 902, - /* 390 */ 590, 593, 592, 594, 598, 601, 623, 624, 625, 603, - /* 400 */ 604, 605, 606, 607, 608, 609, 615, 617, 635, 637, - /* 410 */ 621, 639, 700, 701, 763, 694, 695, 699, 622, 774, - /* 420 */ 765, 769, 770, 772, 773, 787, 788, 790, 796, 803, - /* 430 */ 806, 789, 794, 795, 797, 802, 805, 697, 698, 809, - /* 440 */ 629, 630, 633, 634, 844, 846, 845, 847, 632, 631, - /* 450 */ 775, 778, 811, 812, 869, 870, 871, 872, 873, 807, - /* 460 */ 720, 810, 793, 732, 735, 736, 733, 703, 713, 722, - /* 470 */ 723, 724, 725, 708, 709, 715, 728, 761, 762, 716, - /* 480 */ 705, 706, 707, 808, 764, 776, 777, 640, 641, 771, - /* 490 */ 642, 643, 644, 682, 685, 686, 687, 645, 664, 667, - /* 500 */ 668, 646, 653, 647, 648, 655, 656, 657, 660, 661, - /* 510 */ 662, 663, 658, 659, 827, 828, 832, 830, 829, 650, - /* 520 */ 651, 665, 638, 627, 620, 671, 674, 675, 676, 677, - /* 530 */ 678, 680, 672, 673, 618, 610, 612, 721, 850, 859, - /* 540 */ 855, 851, 852, 853, 613, 823, 824, 684, 755, 756, - /* 550 */ 849, 862, 864, 760, 865, 867, 892, 688, 689, 692, - /* 560 */ 833, 874, 746, 749, 752, 754, 835, 836, 837, 838, - /* 570 */ 839, 842, 843, 840, 875, 879, 882, 884, 885, 886, - /* 580 */ 889, 891, 896, 897, 898, 901, 899, 597, 591, + /* 0 */ 594, 819, 900, 709, 900, 900, 819, 900, 846, 713, + /* 10 */ 875, 900, 817, 900, 900, 900, 791, 900, 846, 900, + /* 20 */ 625, 846, 846, 742, 900, 900, 900, 900, 900, 900, + /* 30 */ 900, 900, 757, 744, 749, 820, 816, 876, 874, 750, + /* 40 */ 813, 859, 821, 743, 756, 733, 812, 900, 740, 747, + /* 50 */ 725, 814, 779, 778, 797, 900, 900, 900, 900, 900, + /* 60 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 70 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 80 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 90 */ 900, 900, 900, 900, 900, 900, 781, 803, 780, 790, + /* 100 */ 618, 782, 783, 613, 678, 900, 900, 900, 900, 900, + /* 110 */ 900, 900, 784, 900, 785, 798, 799, 800, 900, 900, + /* 120 */ 900, 900, 900, 900, 900, 900, 900, 709, 900, 900, + /* 130 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 594, + /* 140 */ 709, 900, 900, 900, 900, 900, 893, 713, 703, 900, + /* 150 */ 669, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 160 */ 900, 900, 711, 833, 900, 752, 881, 900, 900, 716, + /* 170 */ 717, 900, 900, 900, 900, 900, 879, 601, 900, 692, + /* 180 */ 900, 900, 900, 900, 599, 900, 864, 900, 627, 900, + /* 190 */ 900, 866, 900, 900, 900, 900, 900, 852, 900, 690, + /* 200 */ 900, 900, 900, 900, 615, 701, 900, 900, 736, 736, + /* 210 */ 900, 651, 736, 736, 710, 701, 648, 746, 736, 900, + /* 220 */ 815, 900, 900, 746, 900, 856, 680, 886, 598, 718, + /* 230 */ 718, 598, 878, 598, 598, 668, 878, 718, 758, 900, + /* 240 */ 746, 737, 739, 729, 741, 682, 746, 689, 689, 689, + /* 250 */ 689, 718, 746, 758, 682, 682, 718, 610, 900, 858, + /* 260 */ 665, 718, 718, 610, 718, 718, 610, 718, 610, 825, + /* 270 */ 680, 680, 718, 680, 726, 728, 665, 726, 728, 830, + /* 280 */ 830, 825, 680, 680, 651, 680, 861, 635, 653, 653, + /* 290 */ 893, 898, 900, 900, 900, 900, 900, 839, 900, 765, + /* 300 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 310 */ 900, 900, 900, 900, 900, 900, 900, 595, 900, 900, + /* 320 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 330 */ 900, 738, 900, 900, 900, 730, 900, 900, 900, 900, + /* 340 */ 818, 900, 900, 900, 900, 900, 900, 900, 900, 854, + /* 350 */ 900, 855, 900, 900, 900, 900, 900, 900, 900, 900, + /* 360 */ 900, 900, 900, 900, 900, 900, 695, 900, 900, 900, + /* 370 */ 900, 900, 900, 767, 900, 900, 900, 900, 766, 770, + /* 380 */ 900, 900, 900, 900, 900, 885, 900, 900, 900, 888, + /* 390 */ 639, 835, 836, 609, 837, 840, 611, 792, 809, 719, + /* 400 */ 841, 636, 806, 896, 871, 870, 869, 868, 838, 634, + /* 410 */ 616, 720, 867, 614, 848, 899, 811, 608, 873, 857, + /* 420 */ 853, 607, 606, 877, 849, 850, 605, 851, 612, 604, + /* 430 */ 810, 603, 777, 602, 774, 624, 880, 640, 822, 823, + /* 440 */ 623, 630, 631, 845, 843, 844, 683, 754, 755, 847, + /* 450 */ 622, 860, 842, 633, 882, 632, 629, 897, 600, 628, + /* 460 */ 647, 862, 589, 686, 808, 597, 697, 696, 883, 770, + /* 470 */ 759, 804, 801, 663, 796, 641, 593, 794, 863, 646, + /* 480 */ 685, 793, 788, 865, 884, 805, 802, 887, 795, 890, + /* 490 */ 642, 789, 787, 687, 644, 688, 652, 786, 691, 772, + /* 500 */ 771, 832, 769, 768, 872, 591, 667, 889, 764, 745, + /* 510 */ 773, 621, 596, 698, 694, 748, 592, 656, 659, 660, + /* 520 */ 661, 662, 693, 657, 763, 658, 807, 775, 826, 706, + /* 530 */ 762, 705, 827, 704, 831, 829, 715, 894, 828, 649, + /* 540 */ 761, 650, 760, 664, 637, 626, 619, 727, 655, 670, + /* 550 */ 895, 673, 590, 700, 714, 708, 645, 707, 674, 751, + /* 560 */ 724, 654, 666, 675, 684, 723, 722, 721, 676, 753, + /* 570 */ 699, 712, 776, 834, 702, 643, 638, 681, 620, 677, + /* 580 */ 679, 671, 672, 617, 732, 735, 734, 731, }; #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0])) @@ -76209,7 +68561,7 @@ static const YYACTIONTYPE yy_default[] = { ** ** %fallback ID X Y Z. ** -** appears in the grammar, then ID becomes a fallback token for X, Y, +** appears in the grammer, then ID becomes a fallback token for X, Y, ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser ** but it does not parse, the type of the token is changed to ID and ** the parse is retried before an error is thrown. @@ -76746,70 +69098,69 @@ static const char *const yyRuleName[] = { /* 246 */ "cmd ::= VACUUM nm", /* 247 */ "cmd ::= PRAGMA nm dbnm EQ nmnum", /* 248 */ "cmd ::= PRAGMA nm dbnm EQ ON", - /* 249 */ "cmd ::= PRAGMA nm dbnm EQ DELETE", - /* 250 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", - /* 251 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", - /* 252 */ "cmd ::= PRAGMA nm dbnm", - /* 253 */ "nmnum ::= plus_num", - /* 254 */ "nmnum ::= nm", - /* 255 */ "plus_num ::= plus_opt number", - /* 256 */ "minus_num ::= MINUS number", - /* 257 */ "number ::= INTEGER|FLOAT", - /* 258 */ "plus_opt ::= PLUS", - /* 259 */ "plus_opt ::=", - /* 260 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END", - /* 261 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", - /* 262 */ "trigger_time ::= BEFORE", - /* 263 */ "trigger_time ::= AFTER", - /* 264 */ "trigger_time ::= INSTEAD OF", - /* 265 */ "trigger_time ::=", - /* 266 */ "trigger_event ::= DELETE|INSERT", - /* 267 */ "trigger_event ::= UPDATE", - /* 268 */ "trigger_event ::= UPDATE OF inscollist", - /* 269 */ "foreach_clause ::=", - /* 270 */ "foreach_clause ::= FOR EACH ROW", - /* 271 */ "when_clause ::=", - /* 272 */ "when_clause ::= WHEN expr", - /* 273 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", - /* 274 */ "trigger_cmd_list ::=", - /* 275 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt", - /* 276 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP", - /* 277 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select", - /* 278 */ "trigger_cmd ::= DELETE FROM nm where_opt", - /* 279 */ "trigger_cmd ::= select", - /* 280 */ "expr ::= RAISE LP IGNORE RP", - /* 281 */ "expr ::= RAISE LP raisetype COMMA nm RP", - /* 282 */ "raisetype ::= ROLLBACK", - /* 283 */ "raisetype ::= ABORT", - /* 284 */ "raisetype ::= FAIL", - /* 285 */ "cmd ::= DROP TRIGGER ifexists fullname", - /* 286 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", - /* 287 */ "cmd ::= DETACH database_kw_opt expr", - /* 288 */ "key_opt ::=", - /* 289 */ "key_opt ::= KEY expr", - /* 290 */ "database_kw_opt ::= DATABASE", - /* 291 */ "database_kw_opt ::=", - /* 292 */ "cmd ::= REINDEX", - /* 293 */ "cmd ::= REINDEX nm dbnm", - /* 294 */ "cmd ::= ANALYZE", - /* 295 */ "cmd ::= ANALYZE nm dbnm", - /* 296 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", - /* 297 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column", - /* 298 */ "add_column_fullname ::= fullname", - /* 299 */ "kwcolumn_opt ::=", - /* 300 */ "kwcolumn_opt ::= COLUMNKW", - /* 301 */ "cmd ::= create_vtab", - /* 302 */ "cmd ::= create_vtab LP vtabarglist RP", - /* 303 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm", - /* 304 */ "vtabarglist ::= vtabarg", - /* 305 */ "vtabarglist ::= vtabarglist COMMA vtabarg", - /* 306 */ "vtabarg ::=", - /* 307 */ "vtabarg ::= vtabarg vtabargtoken", - /* 308 */ "vtabargtoken ::= ANY", - /* 309 */ "vtabargtoken ::= lp anylist RP", - /* 310 */ "lp ::= LP", - /* 311 */ "anylist ::=", - /* 312 */ "anylist ::= anylist ANY", + /* 249 */ "cmd ::= PRAGMA nm dbnm EQ minus_num", + /* 250 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP", + /* 251 */ "cmd ::= PRAGMA nm dbnm", + /* 252 */ "nmnum ::= plus_num", + /* 253 */ "nmnum ::= nm", + /* 254 */ "plus_num ::= plus_opt number", + /* 255 */ "minus_num ::= MINUS number", + /* 256 */ "number ::= INTEGER|FLOAT", + /* 257 */ "plus_opt ::= PLUS", + /* 258 */ "plus_opt ::=", + /* 259 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END", + /* 260 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause", + /* 261 */ "trigger_time ::= BEFORE", + /* 262 */ "trigger_time ::= AFTER", + /* 263 */ "trigger_time ::= INSTEAD OF", + /* 264 */ "trigger_time ::=", + /* 265 */ "trigger_event ::= DELETE|INSERT", + /* 266 */ "trigger_event ::= UPDATE", + /* 267 */ "trigger_event ::= UPDATE OF inscollist", + /* 268 */ "foreach_clause ::=", + /* 269 */ "foreach_clause ::= FOR EACH ROW", + /* 270 */ "when_clause ::=", + /* 271 */ "when_clause ::= WHEN expr", + /* 272 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI", + /* 273 */ "trigger_cmd_list ::=", + /* 274 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt", + /* 275 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP", + /* 276 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select", + /* 277 */ "trigger_cmd ::= DELETE FROM nm where_opt", + /* 278 */ "trigger_cmd ::= select", + /* 279 */ "expr ::= RAISE LP IGNORE RP", + /* 280 */ "expr ::= RAISE LP raisetype COMMA nm RP", + /* 281 */ "raisetype ::= ROLLBACK", + /* 282 */ "raisetype ::= ABORT", + /* 283 */ "raisetype ::= FAIL", + /* 284 */ "cmd ::= DROP TRIGGER ifexists fullname", + /* 285 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt", + /* 286 */ "cmd ::= DETACH database_kw_opt expr", + /* 287 */ "key_opt ::=", + /* 288 */ "key_opt ::= KEY expr", + /* 289 */ "database_kw_opt ::= DATABASE", + /* 290 */ "database_kw_opt ::=", + /* 291 */ "cmd ::= REINDEX", + /* 292 */ "cmd ::= REINDEX nm dbnm", + /* 293 */ "cmd ::= ANALYZE", + /* 294 */ "cmd ::= ANALYZE nm dbnm", + /* 295 */ "cmd ::= ALTER TABLE fullname RENAME TO nm", + /* 296 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column", + /* 297 */ "add_column_fullname ::= fullname", + /* 298 */ "kwcolumn_opt ::=", + /* 299 */ "kwcolumn_opt ::= COLUMNKW", + /* 300 */ "cmd ::= create_vtab", + /* 301 */ "cmd ::= create_vtab LP vtabarglist RP", + /* 302 */ "create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm", + /* 303 */ "vtabarglist ::= vtabarg", + /* 304 */ "vtabarglist ::= vtabarglist COMMA vtabarg", + /* 305 */ "vtabarg ::=", + /* 306 */ "vtabarg ::= vtabarg vtabargtoken", + /* 307 */ "vtabargtoken ::= ANY", + /* 308 */ "vtabargtoken ::= lp anylist RP", + /* 309 */ "lp ::= LP", + /* 310 */ "anylist ::=", + /* 311 */ "anylist ::= anylist ANY", }; #endif /* NDEBUG */ @@ -76878,69 +69229,57 @@ static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){ ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ - case 155: /* select */ - case 189: /* oneselect */ - case 206: /* seltablist_paren */ -{ -sqlite3SelectDelete((yypminor->yy219)); -} + case 155: + case 189: + case 206: +{sqlite3SelectDelete((yypminor->yy219));} break; - case 169: /* term */ - case 170: /* expr */ - case 194: /* where_opt */ - case 196: /* having_opt */ - case 204: /* on_opt */ - case 210: /* sortitem */ - case 218: /* escape */ - case 221: /* case_operand */ - case 223: /* case_else */ - case 235: /* when_clause */ - case 238: /* key_opt */ -{ -sqlite3ExprDelete((yypminor->yy172)); -} + case 169: + case 170: + case 194: + case 196: + case 204: + case 210: + case 218: + case 221: + case 223: + case 235: +{sqlite3ExprDelete((yypminor->yy172));} break; - case 174: /* idxlist_opt */ - case 182: /* idxlist */ - case 192: /* selcollist */ - case 195: /* groupby_opt */ - case 197: /* orderby_opt */ - case 199: /* sclp */ - case 209: /* sortlist */ - case 211: /* nexprlist */ - case 212: /* setlist */ - case 215: /* itemlist */ - case 216: /* exprlist */ - case 222: /* case_exprlist */ -{ -sqlite3ExprListDelete((yypminor->yy174)); -} + case 174: + case 182: + case 192: + case 195: + case 197: + case 199: + case 209: + case 211: + case 212: + case 215: + case 216: + case 222: +{sqlite3ExprListDelete((yypminor->yy174));} break; - case 188: /* fullname */ - case 193: /* from */ - case 201: /* seltablist */ - case 202: /* stl_prefix */ -{ -sqlite3SrcListDelete((yypminor->yy373)); -} + case 188: + case 193: + case 201: + case 202: +{sqlite3SrcListDelete((yypminor->yy373));} break; - case 205: /* using_opt */ - case 208: /* inscollist */ - case 214: /* inscollist_opt */ -{ -sqlite3IdListDelete((yypminor->yy432)); -} + case 205: + case 208: + case 214: +{sqlite3IdListDelete((yypminor->yy432));} break; - case 231: /* trigger_cmd_list */ - case 236: /* trigger_cmd */ -{ -sqlite3DeleteTriggerStep((yypminor->yy243)); -} + case 231: + case 236: +{sqlite3DeleteTriggerStep((yypminor->yy243));} break; - case 233: /* trigger_event */ -{ -sqlite3IdListDelete((yypminor->yy370).b); -} + case 233: +{sqlite3IdListDelete((yypminor->yy370).b);} + break; + case 238: +{sqlite3ExprDelete((yypminor->yy386));} break; default: break; /* If no destructor action specified: do nothing */ } @@ -77015,7 +69354,9 @@ static int yy_find_shift_action( if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } - assert( iLookAhead!=YYNOCODE ); + if( iLookAhead==YYNOCODE ){ + return YY_NO_ACTION; + } i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ if( iLookAhead>0 ){ @@ -77066,26 +69407,21 @@ static int yy_find_reduce_action( YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; -#ifdef YYERRORSYMBOL - if( stateno>YY_REDUCE_MAX ){ + /* int stateno = pParser->yystack[pParser->yyidx].stateno; */ + + if( stateno>YY_REDUCE_MAX || + (i = yy_reduce_ofst[stateno])==YY_REDUCE_USE_DFLT ){ return yy_default[stateno]; } -#else - assert( stateno<=YY_REDUCE_MAX ); -#endif - i = yy_reduce_ofst[stateno]; - assert( i!=YY_REDUCE_USE_DFLT ); - assert( iLookAhead!=YYNOCODE ); + if( iLookAhead==YYNOCODE ){ + return YY_NO_ACTION; + } i += iLookAhead; -#ifdef YYERRORSYMBOL if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ return yy_default[stateno]; + }else{ + return yy_action[i]; } -#else - assert( i>=0 && iyyidx++; @@ -77406,7 +69742,6 @@ static const struct { { 143, 5 }, { 143, 5 }, { 143, 5 }, - { 143, 5 }, { 143, 6 }, { 143, 3 }, { 227, 1 }, @@ -77510,8 +69845,7 @@ static void yy_reduce( ** from wireshark this week. Clearly they are stressing Lemon in ways ** that it has not been previously stressed... (SQLite ticket #2172) */ - /*memset(&yygotominor, 0, sizeof(yygotominor));*/ - yygotominor = yyzerominor; + memset(&yygotominor, 0, sizeof(yygotominor)); switch( yyruleno ){ @@ -77523,302 +69857,303 @@ static void yy_reduce( ** #line ** break; */ - case 0: /* input ::= cmdlist */ - case 1: /* cmdlist ::= cmdlist ecmd */ - case 2: /* cmdlist ::= ecmd */ - case 4: /* ecmd ::= SEMI */ - case 5: /* ecmd ::= explain cmdx SEMI */ - case 10: /* trans_opt ::= */ - case 11: /* trans_opt ::= TRANSACTION */ - case 12: /* trans_opt ::= TRANSACTION nm */ - case 20: /* cmd ::= create_table create_table_args */ - case 28: /* columnlist ::= columnlist COMMA column */ - case 29: /* columnlist ::= column */ - case 37: /* type ::= */ - case 44: /* signed ::= plus_num */ - case 45: /* signed ::= minus_num */ - case 46: /* carglist ::= carglist carg */ - case 47: /* carglist ::= */ - case 48: /* carg ::= CONSTRAINT nm ccons */ - case 49: /* carg ::= ccons */ - case 55: /* ccons ::= NULL onconf */ - case 82: /* conslist ::= conslist COMMA tcons */ - case 83: /* conslist ::= conslist tcons */ - case 84: /* conslist ::= tcons */ - case 85: /* tcons ::= CONSTRAINT nm */ - case 258: /* plus_opt ::= PLUS */ - case 259: /* plus_opt ::= */ - case 269: /* foreach_clause ::= */ - case 270: /* foreach_clause ::= FOR EACH ROW */ - case 290: /* database_kw_opt ::= DATABASE */ - case 291: /* database_kw_opt ::= */ - case 299: /* kwcolumn_opt ::= */ - case 300: /* kwcolumn_opt ::= COLUMNKW */ - case 304: /* vtabarglist ::= vtabarg */ - case 305: /* vtabarglist ::= vtabarglist COMMA vtabarg */ - case 307: /* vtabarg ::= vtabarg vtabargtoken */ - case 311: /* anylist ::= */ + case 0: + case 1: + case 2: + case 4: + case 5: + case 10: + case 11: + case 12: + case 20: + case 28: + case 29: + case 37: + case 44: + case 45: + case 46: + case 47: + case 48: + case 49: + case 55: + case 82: + case 83: + case 84: + case 85: + case 257: + case 258: + case 268: + case 269: + case 289: + case 290: + case 298: + case 299: + case 303: + case 304: + case 306: + case 310: { } break; - case 3: /* cmdx ::= cmd */ + case 3: { sqlite3FinishCoding(pParse); } break; - case 6: /* explain ::= */ + case 6: { sqlite3BeginParse(pParse, 0); } break; - case 7: /* explain ::= EXPLAIN */ + case 7: { sqlite3BeginParse(pParse, 1); } break; - case 8: /* explain ::= EXPLAIN QUERY PLAN */ + case 8: { sqlite3BeginParse(pParse, 2); } break; - case 9: /* cmd ::= BEGIN transtype trans_opt */ + case 9: {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);} break; - case 13: /* transtype ::= */ + case 13: {yygotominor.yy46 = TK_DEFERRED;} break; - case 14: /* transtype ::= DEFERRED */ - case 15: /* transtype ::= IMMEDIATE */ - case 16: /* transtype ::= EXCLUSIVE */ - case 107: /* multiselect_op ::= UNION */ - case 109: /* multiselect_op ::= EXCEPT|INTERSECT */ + case 14: + case 15: + case 16: + case 107: + case 109: {yygotominor.yy46 = yymsp[0].major;} break; - case 17: /* cmd ::= COMMIT trans_opt */ - case 18: /* cmd ::= END trans_opt */ + case 17: + case 18: {sqlite3CommitTransaction(pParse);} break; - case 19: /* cmd ::= ROLLBACK trans_opt */ + case 19: {sqlite3RollbackTransaction(pParse);} break; - case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */ + case 21: { - sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46); + sqlite3StartTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46); } break; - case 22: /* ifnotexists ::= */ - case 25: /* temp ::= */ - case 63: /* autoinc ::= */ - case 77: /* init_deferred_pred_opt ::= */ - case 79: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ - case 90: /* defer_subclause_opt ::= */ - case 101: /* ifexists ::= */ - case 112: /* distinct ::= ALL */ - case 113: /* distinct ::= */ - case 213: /* between_op ::= BETWEEN */ - case 216: /* in_op ::= IN */ + case 22: + case 25: + case 63: + case 77: + case 79: + case 90: + case 101: + case 112: + case 113: + case 213: + case 216: {yygotominor.yy46 = 0;} break; - case 23: /* ifnotexists ::= IF NOT EXISTS */ - case 24: /* temp ::= TEMP */ - case 64: /* autoinc ::= AUTOINCR */ - case 78: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ - case 100: /* ifexists ::= IF EXISTS */ - case 111: /* distinct ::= DISTINCT */ - case 214: /* between_op ::= NOT BETWEEN */ - case 217: /* in_op ::= NOT IN */ + case 23: + case 24: + case 64: + case 78: + case 100: + case 111: + case 214: + case 217: {yygotominor.yy46 = 1;} break; - case 26: /* create_table_args ::= LP columnlist conslist_opt RP */ + case 26: { - sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0); + sqlite3EndTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy0,0); } break; - case 27: /* create_table_args ::= AS select */ + case 27: { sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219); sqlite3SelectDelete(yymsp[0].minor.yy219); } break; - case 30: /* column ::= columnid type carglist */ + case 30: { - yygotominor.yy0.z = yymsp[-2].minor.yy0.z; - yygotominor.yy0.n = (pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n; + yygotominor.yy410.z = yymsp[-2].minor.yy410.z; + yygotominor.yy410.n = (pParse->sLastToken.z-yymsp[-2].minor.yy410.z) + pParse->sLastToken.n; } break; - case 31: /* columnid ::= nm */ + case 31: { - sqlite3AddColumn(pParse,&yymsp[0].minor.yy0); - yygotominor.yy0 = yymsp[0].minor.yy0; + sqlite3AddColumn(pParse,&yymsp[0].minor.yy410); + yygotominor.yy410 = yymsp[0].minor.yy410; } break; - case 32: /* id ::= ID */ - case 33: /* ids ::= ID|STRING */ - case 34: /* nm ::= ID */ - case 35: /* nm ::= STRING */ - case 36: /* nm ::= JOIN_KW */ - case 39: /* typetoken ::= typename */ - case 42: /* typename ::= ids */ - case 119: /* as ::= AS nm */ - case 120: /* as ::= ids */ - case 131: /* dbnm ::= DOT nm */ - case 241: /* idxitem ::= nm */ - case 243: /* collate ::= COLLATE ids */ - case 253: /* nmnum ::= plus_num */ - case 254: /* nmnum ::= nm */ - case 255: /* plus_num ::= plus_opt number */ - case 256: /* minus_num ::= MINUS number */ - case 257: /* number ::= INTEGER|FLOAT */ -{yygotominor.yy0 = yymsp[0].minor.yy0;} + case 32: + case 33: + case 34: + case 35: + case 36: + case 256: +{yygotominor.yy410 = yymsp[0].minor.yy0;} break; - case 38: /* type ::= typetoken */ -{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);} + case 38: +{sqlite3AddColumnType(pParse,&yymsp[0].minor.yy410);} break; - case 40: /* typetoken ::= typename LP signed RP */ + case 39: + case 42: + case 119: + case 120: + case 131: + case 241: + case 243: + case 252: + case 253: + case 254: + case 255: +{yygotominor.yy410 = yymsp[0].minor.yy410;} + break; + case 40: { - yygotominor.yy0.z = yymsp[-3].minor.yy0.z; - yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z; + yygotominor.yy410.z = yymsp[-3].minor.yy410.z; + yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy410.z; } break; - case 41: /* typetoken ::= typename LP signed COMMA signed RP */ + case 41: { - yygotominor.yy0.z = yymsp[-5].minor.yy0.z; - yygotominor.yy0.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z; + yygotominor.yy410.z = yymsp[-5].minor.yy410.z; + yygotominor.yy410.n = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy410.z; } break; - case 43: /* typename ::= typename ids */ -{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);} + case 43: +{yygotominor.yy410.z=yymsp[-1].minor.yy410.z; yygotominor.yy410.n=yymsp[0].minor.yy410.n+(yymsp[0].minor.yy410.z-yymsp[-1].minor.yy410.z);} break; - case 50: /* ccons ::= DEFAULT term */ - case 52: /* ccons ::= DEFAULT PLUS term */ + case 50: + case 52: {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);} break; - case 51: /* ccons ::= DEFAULT LP expr RP */ + case 51: {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);} break; - case 53: /* ccons ::= DEFAULT MINUS term */ + case 53: { Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0); sqlite3AddDefaultValue(pParse,p); } break; - case 54: /* ccons ::= DEFAULT id */ + case 54: { - Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0); + Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy410); sqlite3AddDefaultValue(pParse,p); } break; - case 56: /* ccons ::= NOT NULL onconf */ + case 56: {sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);} break; - case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ + case 57: {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);} break; - case 58: /* ccons ::= UNIQUE onconf */ + case 58: {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);} break; - case 59: /* ccons ::= CHECK LP expr RP */ + case 59: {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);} break; - case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */ -{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);} + case 60: +{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy410,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);} break; - case 61: /* ccons ::= defer_subclause */ + case 61: {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);} break; - case 62: /* ccons ::= COLLATE ids */ -{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);} + case 62: +{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy410);} break; - case 65: /* refargs ::= */ + case 65: { yygotominor.yy46 = OE_Restrict * 0x010101; } break; - case 66: /* refargs ::= refargs refarg */ + case 66: { yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; } break; - case 67: /* refarg ::= MATCH nm */ + case 67: { yygotominor.yy405.value = 0; yygotominor.yy405.mask = 0x000000; } break; - case 68: /* refarg ::= ON DELETE refact */ + case 68: { yygotominor.yy405.value = yymsp[0].minor.yy46; yygotominor.yy405.mask = 0x0000ff; } break; - case 69: /* refarg ::= ON UPDATE refact */ + case 69: { yygotominor.yy405.value = yymsp[0].minor.yy46<<8; yygotominor.yy405.mask = 0x00ff00; } break; - case 70: /* refarg ::= ON INSERT refact */ + case 70: { yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; } break; - case 71: /* refact ::= SET NULL */ + case 71: { yygotominor.yy46 = OE_SetNull; } break; - case 72: /* refact ::= SET DEFAULT */ + case 72: { yygotominor.yy46 = OE_SetDflt; } break; - case 73: /* refact ::= CASCADE */ + case 73: { yygotominor.yy46 = OE_Cascade; } break; - case 74: /* refact ::= RESTRICT */ + case 74: { yygotominor.yy46 = OE_Restrict; } break; - case 75: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ - case 76: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ - case 91: /* defer_subclause_opt ::= defer_subclause */ - case 93: /* onconf ::= ON CONFLICT resolvetype */ - case 95: /* orconf ::= OR resolvetype */ - case 96: /* resolvetype ::= raisetype */ - case 166: /* insert_cmd ::= INSERT orconf */ + case 75: + case 76: + case 91: + case 93: + case 95: + case 96: + case 166: {yygotominor.yy46 = yymsp[0].minor.yy46;} break; - case 80: /* conslist_opt ::= */ -{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;} + case 80: +{yygotominor.yy410.n = 0; yygotominor.yy410.z = 0;} break; - case 81: /* conslist_opt ::= COMMA conslist */ -{yygotominor.yy0 = yymsp[-1].minor.yy0;} + case 81: +{yygotominor.yy410 = yymsp[-1].minor.yy0;} break; - case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */ + case 86: {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);} break; - case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */ + case 87: {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);} break; - case 88: /* tcons ::= CHECK LP expr RP onconf */ + case 88: {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);} break; - case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */ + case 89: { - sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46); + sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy174, &yymsp[-3].minor.yy410, yymsp[-2].minor.yy174, yymsp[-1].minor.yy46); sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy46); } break; - case 92: /* onconf ::= */ - case 94: /* orconf ::= */ + case 92: + case 94: {yygotominor.yy46 = OE_Default;} break; - case 97: /* resolvetype ::= IGNORE */ + case 97: {yygotominor.yy46 = OE_Ignore;} break; - case 98: /* resolvetype ::= REPLACE */ - case 167: /* insert_cmd ::= REPLACE */ + case 98: + case 167: {yygotominor.yy46 = OE_Replace;} break; - case 99: /* cmd ::= DROP TABLE ifexists fullname */ + case 99: { sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46); } break; - case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */ + case 102: { - sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy219, yymsp[-6].minor.yy46, yymsp[-4].minor.yy46); + sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, yymsp[0].minor.yy219, yymsp[-6].minor.yy46, yymsp[-4].minor.yy46); } break; - case 103: /* cmd ::= DROP VIEW ifexists fullname */ + case 103: { sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46); } break; - case 104: /* cmd ::= select */ + case 104: { - SelectDest dest = {SRT_Callback, 0, 0, 0, 0}; - sqlite3Select(pParse, yymsp[0].minor.yy219, &dest, 0, 0, 0); + sqlite3Select(pParse, yymsp[0].minor.yy219, SRT_Callback, 0, 0, 0, 0, 0); sqlite3SelectDelete(yymsp[0].minor.yy219); } break; - case 105: /* select ::= oneselect */ - case 128: /* seltablist_paren ::= select */ + case 105: + case 128: {yygotominor.yy219 = yymsp[0].minor.yy219;} break; - case 106: /* select ::= select multiselect_op oneselect */ + case 106: { if( yymsp[0].minor.yy219 ){ yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46; @@ -77829,249 +70164,249 @@ static void yy_reduce( yygotominor.yy219 = yymsp[0].minor.yy219; } break; - case 108: /* multiselect_op ::= UNION ALL */ + case 108: {yygotominor.yy46 = TK_ALL;} break; - case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ + case 110: { yygotominor.yy219 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy174,yymsp[-5].minor.yy373,yymsp[-4].minor.yy172,yymsp[-3].minor.yy174,yymsp[-2].minor.yy172,yymsp[-1].minor.yy174,yymsp[-7].minor.yy46,yymsp[0].minor.yy234.pLimit,yymsp[0].minor.yy234.pOffset); } break; - case 114: /* sclp ::= selcollist COMMA */ - case 238: /* idxlist_opt ::= LP idxlist RP */ + case 114: + case 238: {yygotominor.yy174 = yymsp[-1].minor.yy174;} break; - case 115: /* sclp ::= */ - case 141: /* orderby_opt ::= */ - case 149: /* groupby_opt ::= */ - case 231: /* exprlist ::= */ - case 237: /* idxlist_opt ::= */ + case 115: + case 141: + case 149: + case 231: + case 237: {yygotominor.yy174 = 0;} break; - case 116: /* selcollist ::= sclp expr as */ + case 116: { - yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0); + yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy410.n?&yymsp[0].minor.yy410:0); } break; - case 117: /* selcollist ::= sclp STAR */ + case 117: { Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0); yygotominor.yy174 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy174, p, 0); } break; - case 118: /* selcollist ::= sclp nm DOT STAR */ + case 118: { Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0); - Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); + Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410); Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0); yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174, pDot, 0); } break; - case 121: /* as ::= */ -{yygotominor.yy0.n = 0;} + case 121: +{yygotominor.yy410.n = 0;} break; - case 122: /* from ::= */ + case 122: {yygotominor.yy373 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy373));} break; - case 123: /* from ::= FROM seltablist */ + case 123: { yygotominor.yy373 = yymsp[0].minor.yy373; sqlite3SrcListShiftJoinType(yygotominor.yy373); } break; - case 124: /* stl_prefix ::= seltablist joinop */ + case 124: { yygotominor.yy373 = yymsp[-1].minor.yy373; if( yygotominor.yy373 && yygotominor.yy373->nSrc>0 ) yygotominor.yy373->a[yygotominor.yy373->nSrc-1].jointype = yymsp[0].minor.yy46; } break; - case 125: /* stl_prefix ::= */ + case 125: {yygotominor.yy373 = 0;} break; - case 126: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */ + case 126: { - yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy373,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy172,yymsp[0].minor.yy432); + yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy373,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,0,yymsp[-1].minor.yy172,yymsp[0].minor.yy432); } break; - case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */ + case 127: { - yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy373,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy219,yymsp[-1].minor.yy172,yymsp[0].minor.yy432); + yygotominor.yy373 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy373,0,0,&yymsp[-2].minor.yy410,yymsp[-4].minor.yy219,yymsp[-1].minor.yy172,yymsp[0].minor.yy432); } break; - case 129: /* seltablist_paren ::= seltablist */ + case 129: { sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373); yygotominor.yy219 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy373,0,0,0,0,0,0,0); } break; - case 130: /* dbnm ::= */ -{yygotominor.yy0.z=0; yygotominor.yy0.n=0;} + case 130: +{yygotominor.yy410.z=0; yygotominor.yy410.n=0;} break; - case 132: /* fullname ::= nm dbnm */ -{yygotominor.yy373 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);} + case 132: +{yygotominor.yy373 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);} break; - case 133: /* joinop ::= COMMA|JOIN */ + case 133: { yygotominor.yy46 = JT_INNER; } break; - case 134: /* joinop ::= JOIN_KW JOIN */ + case 134: { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); } break; - case 135: /* joinop ::= JOIN_KW nm JOIN */ -{ yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); } + case 135: +{ yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy410,0); } break; - case 136: /* joinop ::= JOIN_KW nm nm JOIN */ -{ yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); } + case 136: +{ yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy410,&yymsp[-1].minor.yy410); } break; - case 137: /* on_opt ::= ON expr */ - case 145: /* sortitem ::= expr */ - case 152: /* having_opt ::= HAVING expr */ - case 159: /* where_opt ::= WHERE expr */ - case 174: /* expr ::= term */ - case 202: /* escape ::= ESCAPE expr */ - case 226: /* case_else ::= ELSE expr */ - case 228: /* case_operand ::= expr */ + case 137: + case 145: + case 152: + case 159: + case 174: + case 202: + case 226: + case 228: {yygotominor.yy172 = yymsp[0].minor.yy172;} break; - case 138: /* on_opt ::= */ - case 151: /* having_opt ::= */ - case 158: /* where_opt ::= */ - case 203: /* escape ::= */ - case 227: /* case_else ::= */ - case 229: /* case_operand ::= */ + case 138: + case 151: + case 158: + case 203: + case 227: + case 229: {yygotominor.yy172 = 0;} break; - case 139: /* using_opt ::= USING LP inscollist RP */ - case 171: /* inscollist_opt ::= LP inscollist RP */ + case 139: + case 171: {yygotominor.yy432 = yymsp[-1].minor.yy432;} break; - case 140: /* using_opt ::= */ - case 170: /* inscollist_opt ::= */ + case 140: + case 170: {yygotominor.yy432 = 0;} break; - case 142: /* orderby_opt ::= ORDER BY sortlist */ - case 150: /* groupby_opt ::= GROUP BY nexprlist */ - case 230: /* exprlist ::= nexprlist */ + case 142: + case 150: + case 230: {yygotominor.yy174 = yymsp[0].minor.yy174;} break; - case 143: /* sortlist ::= sortlist COMMA sortitem sortorder */ + case 143: { yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0); if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46; } break; - case 144: /* sortlist ::= sortitem sortorder */ + case 144: { yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy172,0); if( yygotominor.yy174 && yygotominor.yy174->a ) yygotominor.yy174->a[0].sortOrder = yymsp[0].minor.yy46; } break; - case 146: /* sortorder ::= ASC */ - case 148: /* sortorder ::= */ + case 146: + case 148: {yygotominor.yy46 = SQLITE_SO_ASC;} break; - case 147: /* sortorder ::= DESC */ + case 147: {yygotominor.yy46 = SQLITE_SO_DESC;} break; - case 153: /* limit_opt ::= */ + case 153: {yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;} break; - case 154: /* limit_opt ::= LIMIT expr */ + case 154: {yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;} break; - case 155: /* limit_opt ::= LIMIT expr OFFSET expr */ + case 155: {yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;} break; - case 156: /* limit_opt ::= LIMIT expr COMMA expr */ + case 156: {yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;} break; - case 157: /* cmd ::= DELETE FROM fullname where_opt */ + case 157: {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);} break; - case 160: /* cmd ::= UPDATE orconf fullname SET setlist where_opt */ + case 160: { - sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,"set list"); + sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy174,SQLITE_MAX_COLUMN,"set list"); sqlite3Update(pParse,yymsp[-3].minor.yy373,yymsp[-1].minor.yy174,yymsp[0].minor.yy172,yymsp[-4].minor.yy46); } break; - case 161: /* setlist ::= setlist COMMA nm EQ expr */ -{yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy0);} + case 161: +{yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);} break; - case 162: /* setlist ::= nm EQ expr */ -{yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy0);} + case 162: +{yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);} break; - case 163: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */ + case 163: {sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);} break; - case 164: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */ + case 164: {sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);} break; - case 165: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */ + case 165: {sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);} break; - case 168: /* itemlist ::= itemlist COMMA expr */ - case 232: /* nexprlist ::= nexprlist COMMA expr */ + case 168: + case 232: {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);} break; - case 169: /* itemlist ::= expr */ - case 233: /* nexprlist ::= expr */ + case 169: + case 233: {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,0);} break; - case 172: /* inscollist ::= inscollist COMMA nm */ -{yygotominor.yy432 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy432,&yymsp[0].minor.yy0);} + case 172: +{yygotominor.yy432 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);} break; - case 173: /* inscollist ::= nm */ -{yygotominor.yy432 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);} + case 173: +{yygotominor.yy432 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy410);} break; - case 175: /* expr ::= LP expr RP */ + case 175: {yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); } break; - case 176: /* term ::= NULL */ - case 181: /* term ::= INTEGER|FLOAT|BLOB */ - case 182: /* term ::= STRING */ + case 176: + case 181: + case 182: {yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);} break; - case 177: /* expr ::= ID */ - case 178: /* expr ::= JOIN_KW */ + case 177: + case 178: {yygotominor.yy172 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);} break; - case 179: /* expr ::= nm DOT nm */ + case 179: { - Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); - Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0); + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410); + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410); yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0); } break; - case 180: /* expr ::= nm DOT nm DOT nm */ + case 180: { - Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0); - Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0); - Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0); + Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy410); + Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy410); + Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy410); Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0); yygotominor.yy172 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0); } break; - case 183: /* expr ::= REGISTER */ + case 183: {yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);} break; - case 184: /* expr ::= VARIABLE */ + case 184: { Token *pToken = &yymsp[0].minor.yy0; Expr *pExpr = yygotominor.yy172 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken); sqlite3ExprAssignVarNumber(pParse, pExpr); } break; - case 185: /* expr ::= expr COLLATE ids */ + case 185: { - yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy0); + yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy410); } break; - case 186: /* expr ::= CAST LP expr AS typetoken RP */ + case 186: { - yygotominor.yy172 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy0); + yygotominor.yy172 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy172, 0, &yymsp[-1].minor.yy410); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); } break; - case 187: /* expr ::= ID LP distinct exprlist RP */ + case 187: { if( yymsp[-1].minor.yy174 && yymsp[-1].minor.yy174->nExpr>SQLITE_MAX_FUNCTION_ARG ){ sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0); @@ -78083,13 +70418,13 @@ static void yy_reduce( } } break; - case 188: /* expr ::= ID LP STAR RP */ + case 188: { yygotominor.yy172 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); } break; - case 189: /* term ::= CTIME_KW */ + case 189: { /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are ** treated as functions that return constants */ @@ -78100,25 +70435,25 @@ static void yy_reduce( } } break; - case 190: /* expr ::= expr AND expr */ - case 191: /* expr ::= expr OR expr */ - case 192: /* expr ::= expr LT|GT|GE|LE expr */ - case 193: /* expr ::= expr EQ|NE expr */ - case 194: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ - case 195: /* expr ::= expr PLUS|MINUS expr */ - case 196: /* expr ::= expr STAR|SLASH|REM expr */ - case 197: /* expr ::= expr CONCAT expr */ + case 190: + case 191: + case 192: + case 193: + case 194: + case 195: + case 196: + case 197: {yygotominor.yy172 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy172,yymsp[0].minor.yy172,0);} break; - case 198: /* likeop ::= LIKE_KW */ - case 200: /* likeop ::= MATCH */ + case 198: + case 200: {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;} break; - case 199: /* likeop ::= NOT LIKE_KW */ - case 201: /* likeop ::= NOT MATCH */ + case 199: + case 201: {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;} break; - case 204: /* expr ::= expr likeop expr escape */ + case 204: { ExprList *pList; pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy172, 0); @@ -78132,50 +70467,50 @@ static void yy_reduce( if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc; } break; - case 205: /* expr ::= expr ISNULL|NOTNULL */ + case 205: { yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 206: /* expr ::= expr IS NULL */ + case 206: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 207: /* expr ::= expr NOT NULL */ + case 207: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 208: /* expr ::= expr IS NOT NULL */ + case 208: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 209: /* expr ::= NOT expr */ - case 210: /* expr ::= BITNOT expr */ + case 209: + case 210: { yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span); } break; - case 211: /* expr ::= MINUS expr */ + case 211: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span); } break; - case 212: /* expr ::= PLUS expr */ + case 212: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy172->span); } break; - case 215: /* expr ::= expr between_op expr AND expr */ + case 215: { ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0); pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0); @@ -78189,12 +70524,12 @@ static void yy_reduce( sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span); } break; - case 218: /* expr ::= expr in_op LP exprlist RP */ + case 218: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pList = yymsp[-1].minor.yy174; - sqlite3ExprSetHeight(pParse, yygotominor.yy172); + sqlite3ExprSetHeight(yygotominor.yy172); }else{ sqlite3ExprListDelete(yymsp[-1].minor.yy174); } @@ -78202,24 +70537,24 @@ static void yy_reduce( sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 219: /* expr ::= LP select RP */ + case 219: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pSelect = yymsp[-1].minor.yy219; - sqlite3ExprSetHeight(pParse, yygotominor.yy172); + sqlite3ExprSetHeight(yygotominor.yy172); }else{ sqlite3SelectDelete(yymsp[-1].minor.yy219); } sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); } break; - case 220: /* expr ::= expr in_op LP select RP */ + case 220: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pSelect = yymsp[-1].minor.yy219; - sqlite3ExprSetHeight(pParse, yygotominor.yy172); + sqlite3ExprSetHeight(yygotominor.yy172); }else{ sqlite3SelectDelete(yymsp[-1].minor.yy219); } @@ -78227,160 +70562,159 @@ static void yy_reduce( sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 221: /* expr ::= expr in_op nm dbnm */ + case 221: { - SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); + SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410); yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy172, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0); - sqlite3ExprSetHeight(pParse, yygotominor.yy172); + sqlite3ExprSetHeight(yygotominor.yy172); }else{ sqlite3SrcListDelete(pSrc); } if( yymsp[-2].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0); - sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0); + sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy172->span,yymsp[0].minor.yy410.z?&yymsp[0].minor.yy410:&yymsp[-1].minor.yy410); } break; - case 222: /* expr ::= EXISTS LP select RP */ + case 222: { Expr *p = yygotominor.yy172 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0); if( p ){ p->pSelect = yymsp[-1].minor.yy219; sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); - sqlite3ExprSetHeight(pParse, yygotominor.yy172); + sqlite3ExprSetHeight(yygotominor.yy172); }else{ sqlite3SelectDelete(yymsp[-1].minor.yy219); } } break; - case 223: /* expr ::= CASE case_operand case_exprlist case_else END */ + case 223: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pList = yymsp[-2].minor.yy174; - sqlite3ExprSetHeight(pParse, yygotominor.yy172); + sqlite3ExprSetHeight(yygotominor.yy172); }else{ sqlite3ExprListDelete(yymsp[-2].minor.yy174); } sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0); } break; - case 224: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ + case 224: { yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, yymsp[-2].minor.yy172, 0); yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0); } break; - case 225: /* case_exprlist ::= WHEN expr THEN expr */ + case 225: { yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0); yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0); } break; - case 234: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */ + case 234: { - sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, - sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46, + sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy410, &yymsp[-5].minor.yy410, + sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy410,0), yymsp[-1].minor.yy174, yymsp[-9].minor.yy46, &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy46); } break; - case 235: /* uniqueflag ::= UNIQUE */ - case 283: /* raisetype ::= ABORT */ + case 235: + case 282: {yygotominor.yy46 = OE_Abort;} break; - case 236: /* uniqueflag ::= */ + case 236: {yygotominor.yy46 = OE_None;} break; - case 239: /* idxlist ::= idxlist COMMA idxitem collate sortorder */ + case 239: { Expr *p = 0; - if( yymsp[-1].minor.yy0.n>0 ){ + if( yymsp[-1].minor.yy410.n>0 ){ p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0); - sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0); + sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410); } - yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy0); - sqlite3ExprListCheckLength(pParse, yygotominor.yy174, "index"); + yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174, p, &yymsp[-2].minor.yy410); + sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index"); if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46; } break; - case 240: /* idxlist ::= idxitem collate sortorder */ + case 240: { Expr *p = 0; - if( yymsp[-1].minor.yy0.n>0 ){ + if( yymsp[-1].minor.yy410.n>0 ){ p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0); - sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0); + sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410); } - yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0); - sqlite3ExprListCheckLength(pParse, yygotominor.yy174, "index"); + yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy410); + sqlite3ExprListCheckLength(pParse, yygotominor.yy174, SQLITE_MAX_COLUMN, "index"); if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46; } break; - case 242: /* collate ::= */ -{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;} + case 242: +{yygotominor.yy410.z = 0; yygotominor.yy410.n = 0;} break; - case 244: /* cmd ::= DROP INDEX ifexists fullname */ + case 244: {sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);} break; - case 245: /* cmd ::= VACUUM */ - case 246: /* cmd ::= VACUUM nm */ + case 245: + case 246: {sqlite3Vacuum(pParse);} break; - case 247: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ - case 248: /* cmd ::= PRAGMA nm dbnm EQ ON */ - case 249: /* cmd ::= PRAGMA nm dbnm EQ DELETE */ -{sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);} + case 247: +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,0);} break; - case 250: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ + case 248: +{sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy0,0);} + break; + case 249: { - sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1); + sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,1); } break; - case 251: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ -{sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);} + case 250: +{sqlite3Pragma(pParse,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-1].minor.yy410,0);} break; - case 252: /* cmd ::= PRAGMA nm dbnm */ -{sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);} + case 251: +{sqlite3Pragma(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,0,0);} break; - case 260: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */ + case 259: { Token all; - all.z = yymsp[-3].minor.yy0.z; - all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n; + all.z = yymsp[-3].minor.yy410.z; + all.n = (yymsp[0].minor.yy0.z - yymsp[-3].minor.yy410.z) + yymsp[0].minor.yy0.n; sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy243, &all); } break; - case 261: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ + case 260: { - sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy46, yymsp[-4].minor.yy370.a, yymsp[-4].minor.yy370.b, yymsp[-2].minor.yy373, yymsp[0].minor.yy172, yymsp[-10].minor.yy46, yymsp[-8].minor.yy46); - yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); + sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy410, &yymsp[-6].minor.yy410, yymsp[-5].minor.yy46, yymsp[-4].minor.yy370.a, yymsp[-4].minor.yy370.b, yymsp[-2].minor.yy373, yymsp[0].minor.yy172, yymsp[-10].minor.yy46, yymsp[-8].minor.yy46); + yygotominor.yy410 = (yymsp[-6].minor.yy410.n==0?yymsp[-7].minor.yy410:yymsp[-6].minor.yy410); } break; - case 262: /* trigger_time ::= BEFORE */ - case 265: /* trigger_time ::= */ + case 261: + case 264: { yygotominor.yy46 = TK_BEFORE; } break; - case 263: /* trigger_time ::= AFTER */ + case 262: { yygotominor.yy46 = TK_AFTER; } break; - case 264: /* trigger_time ::= INSTEAD OF */ + case 263: { yygotominor.yy46 = TK_INSTEAD;} break; - case 266: /* trigger_event ::= DELETE|INSERT */ - case 267: /* trigger_event ::= UPDATE */ + case 265: + case 266: {yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;} break; - case 268: /* trigger_event ::= UPDATE OF inscollist */ + case 267: {yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;} break; - case 271: /* when_clause ::= */ - case 288: /* key_opt ::= */ + case 270: { yygotominor.yy172 = 0; } break; - case 272: /* when_clause ::= WHEN expr */ - case 289: /* key_opt ::= KEY expr */ + case 271: { yygotominor.yy172 = yymsp[0].minor.yy172; } break; - case 273: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ + case 272: { if( yymsp[-2].minor.yy243 ){ yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243; @@ -78391,25 +70725,25 @@ static void yy_reduce( yygotominor.yy243 = yymsp[-2].minor.yy243; } break; - case 274: /* trigger_cmd_list ::= */ + case 273: { yygotominor.yy243 = 0; } break; - case 275: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */ -{ yygotominor.yy243 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); } + case 274: +{ yygotominor.yy243 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy410, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); } break; - case 276: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */ -{yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);} + case 275: +{yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy410, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);} break; - case 277: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */ -{yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);} + case 276: +{yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy410, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);} break; - case 278: /* trigger_cmd ::= DELETE FROM nm where_opt */ -{yygotominor.yy243 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy172);} + case 277: +{yygotominor.yy243 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy410, yymsp[0].minor.yy172);} break; - case 279: /* trigger_cmd ::= select */ + case 278: {yygotominor.yy243 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy219); } break; - case 280: /* expr ::= RAISE LP IGNORE RP */ + case 279: { yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); if( yygotominor.yy172 ){ @@ -78418,81 +70752,87 @@ static void yy_reduce( } } break; - case 281: /* expr ::= RAISE LP raisetype COMMA nm RP */ + case 280: { - yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); + yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy410); if( yygotominor.yy172 ) { yygotominor.yy172->iColumn = yymsp[-3].minor.yy46; sqlite3ExprSpan(yygotominor.yy172, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0); } } break; - case 282: /* raisetype ::= ROLLBACK */ + case 281: {yygotominor.yy46 = OE_Rollback;} break; - case 284: /* raisetype ::= FAIL */ + case 283: {yygotominor.yy46 = OE_Fail;} break; - case 285: /* cmd ::= DROP TRIGGER ifexists fullname */ + case 284: { sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46); } break; - case 286: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ + case 285: { - sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy172); + sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy386); } break; - case 287: /* cmd ::= DETACH database_kw_opt expr */ + case 286: { sqlite3Detach(pParse, yymsp[0].minor.yy172); } break; - case 292: /* cmd ::= REINDEX */ + case 287: +{ yygotominor.yy386 = 0; } + break; + case 288: +{ yygotominor.yy386 = yymsp[0].minor.yy172; } + break; + case 291: {sqlite3Reindex(pParse, 0, 0);} break; - case 293: /* cmd ::= REINDEX nm dbnm */ -{sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} + case 292: +{sqlite3Reindex(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);} break; - case 294: /* cmd ::= ANALYZE */ + case 293: {sqlite3Analyze(pParse, 0, 0);} break; - case 295: /* cmd ::= ANALYZE nm dbnm */ -{sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);} + case 294: +{sqlite3Analyze(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);} break; - case 296: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ + case 295: { - sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy0); + sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy410); } break; - case 297: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */ + case 296: { - sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0); + sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy410); } break; - case 298: /* add_column_fullname ::= fullname */ + case 297: { sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373); } break; - case 301: /* cmd ::= create_vtab */ + case 300: {sqlite3VtabFinishParse(pParse,0);} break; - case 302: /* cmd ::= create_vtab LP vtabarglist RP */ + case 301: {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} break; - case 303: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */ + case 302: { - sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0); + sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, &yymsp[0].minor.yy410); } break; - case 306: /* vtabarg ::= */ + case 305: {sqlite3VtabArgInit(pParse);} break; - case 308: /* vtabargtoken ::= ANY */ - case 309: /* vtabargtoken ::= lp anylist RP */ - case 310: /* lp ::= LP */ - case 312: /* anylist ::= anylist ANY */ + case 307: + case 308: + case 309: + case 311: {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} break; }; @@ -78517,8 +70857,7 @@ static void yy_reduce( { yy_shift(yypParser,yyact,yygoto,&yygotominor); } - }else{ - assert( yyact == YYNSTATE + YYNRULE + 1 ); + }else if( yyact == YYNSTATE + YYNRULE + 1 ){ yy_accept(yypParser); } } @@ -78552,9 +70891,14 @@ static void yy_syntax_error( sqlite3ParserARG_FETCH; #define TOKEN (yyminor.yy0) - assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); - pParse->parseError = 1; + if( !pParse->parseError ){ + if( TOKEN.z[0] ){ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); + }else{ + sqlite3ErrorMsg(pParse, "incomplete SQL statement"); + } + pParse->parseError = 1; + } sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } @@ -78604,9 +70948,7 @@ SQLITE_PRIVATE void sqlite3Parser( YYMINORTYPE yyminorunion; int yyact; /* The parser action. */ int yyendofinput; /* True if we are at the end of input */ -#ifdef YYERRORSYMBOL int yyerrorhit = 0; /* True if yymajor has invoked an error */ -#endif yyParser *yypParser; /* The parser */ /* (re)initialize the parser, if necessary */ @@ -78614,8 +70956,7 @@ SQLITE_PRIVATE void sqlite3Parser( if( yypParser->yyidx<0 ){ #if YYSTACKDEPTH<=0 if( yypParser->yystksz <=0 ){ - /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/ - yyminorunion = yyzerominor; + memset(&yyminorunion, 0, sizeof(yyminorunion)); yyStackOverflow(yypParser, &yyminorunion); return; } @@ -78638,17 +70979,17 @@ SQLITE_PRIVATE void sqlite3Parser( do{ yyact = yy_find_shift_action(yypParser,yymajor); if( yyactyyerrcnt--; - yymajor = YYNOCODE; + if( yyendofinput && yypParser->yyidx>=0 ){ + yymajor = 0; + }else{ + yymajor = YYNOCODE; + } }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); - }else{ - assert( yyact == YY_ERROR_ACTION ); -#ifdef YYERRORSYMBOL + }else if( yyact == YY_ERROR_ACTION ){ int yymx; -#endif #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); @@ -78729,6 +71070,9 @@ SQLITE_PRIVATE void sqlite3Parser( } yymajor = YYNOCODE; #endif + }else{ + yy_accept(yypParser); + yymajor = YYNOCODE; } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; @@ -78753,7 +71097,7 @@ SQLITE_PRIVATE void sqlite3Parser( ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. ** -** $Id: tokenize.c,v 1.146 2008/07/08 19:34:07 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ /* @@ -78806,7 +71150,7 @@ const unsigned char ebcdicToAscii[] = { ** ** The code in this file has been automatically generated by ** -** $Header: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.31 2007/07/30 18:26:20 rse Exp $ +** $Header: /cvsroot/mozilla/db/sqlite3/src/sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ ** ** The code in this file implements a function that determines whether ** or not a given identifier is really an SQL keyword. The same thing @@ -78829,8 +71173,8 @@ static int keywordCode(const char *z, int n){ "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM" "VIEWINITIALLY"; static const unsigned char aHash[127] = { - 63, 92, 109, 61, 0, 38, 0, 0, 69, 0, 64, 0, 0, - 102, 4, 65, 7, 0, 108, 72, 103, 99, 0, 22, 0, 0, + 63, 92, 109, 61, 0, 39, 0, 0, 69, 0, 64, 0, 0, + 101, 4, 65, 7, 0, 108, 72, 103, 99, 0, 22, 0, 0, 113, 0, 111, 106, 0, 18, 80, 0, 1, 0, 0, 56, 57, 0, 55, 11, 0, 33, 77, 89, 0, 110, 88, 0, 0, 45, 0, 90, 54, 0, 20, 0, 114, 34, 19, 0, 10, 97, 28, @@ -78844,22 +71188,22 @@ static int keywordCode(const char *z, int n){ 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, - 17, 0, 0, 0, 36, 39, 0, 0, 25, 0, 0, 31, 0, + 17, 0, 0, 0, 36, 38, 0, 0, 25, 0, 0, 31, 0, 0, 0, 43, 52, 0, 0, 0, 53, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 0, 0, 0, 26, 0, 8, 46, - 2, 0, 0, 0, 0, 0, 0, 0, 3, 58, 66, 0, 13, - 0, 91, 85, 0, 94, 0, 74, 0, 0, 62, 0, 35, 101, + 3, 0, 0, 0, 0, 0, 0, 0, 2, 58, 66, 0, 13, + 0, 91, 85, 0, 94, 0, 74, 0, 0, 0, 62, 35, 102, 0, 0, 105, 23, 30, 60, 70, 0, 0, 59, 0, 0, }; static const unsigned char aLen[116] = { - 6, 7, 3, 6, 6, 7, 7, 3, 4, 6, 4, 5, 3, + 6, 3, 7, 6, 6, 7, 7, 3, 4, 6, 4, 5, 3, 10, 9, 5, 4, 4, 3, 8, 2, 6, 11, 2, 7, 5, - 5, 4, 6, 7, 10, 6, 5, 6, 6, 5, 6, 4, 9, + 5, 4, 6, 7, 10, 6, 5, 6, 6, 5, 6, 9, 4, 2, 5, 5, 7, 5, 9, 6, 7, 7, 3, 4, 4, 7, 3, 10, 4, 7, 6, 12, 6, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8, - 2, 4, 4, 4, 4, 4, 2, 2, 4, 6, 2, 3, 6, + 2, 4, 4, 4, 4, 4, 2, 2, 4, 2, 6, 3, 6, 5, 8, 5, 5, 8, 3, 5, 5, 6, 4, 9, 3, }; static const unsigned short int aOffset[116] = { @@ -78874,7 +71218,7 @@ static int keywordCode(const char *z, int n){ 464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521, }; static const unsigned char aCode[116] = { - TK_BEFORE, TK_FOREIGN, TK_FOR, TK_IGNORE, TK_LIKE_KW, + TK_BEFORE, TK_FOR, TK_FOREIGN, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD, TK_ADD, TK_DESC, TK_ESCAPE, TK_EACH, TK_CHECK, TK_KEY, TK_CONSTRAINT, TK_INTERSECT, TK_TABLE, TK_JOIN_KW, TK_THEN, TK_END, TK_DATABASE, @@ -78894,7 +71238,7 @@ static int keywordCode(const char *z, int n){ TK_JOIN_KW, TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW, TK_BY, TK_IF, TK_INTO, - TK_OFFSET, TK_OF, TK_SET, TK_ISNULL, TK_ORDER, + TK_OF, TK_OFFSET, TK_SET, TK_ISNULL, TK_ORDER, TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL, @@ -78971,7 +71315,7 @@ SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = { ** Return the length of the token that begins at z[0]. ** Store the token type in *tokenType before returning. */ -SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ +static int getToken(const unsigned char *z, int *tokenType){ int i, c; switch( *z ){ case ' ': case '\t': case '\n': case '\f': case '\r': { @@ -79143,7 +71487,7 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ } case '[': { for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} - *tokenType = c==']' ? TK_ID : TK_ILLEGAL; + *tokenType = TK_ID; return i; } case '?': { @@ -79195,14 +71539,19 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ } #ifndef SQLITE_OMIT_BLOB_LITERAL case 'x': case 'X': { - if( z[1]=='\'' ){ + if( (c=z[1])=='\'' || c=='"' ){ + int delim = c; *tokenType = TK_BLOB; - for(i=2; (c=z[i])!=0 && c!='\''; i++){ + for(i=2; (c=z[i])!=0; i++){ + if( c==delim ){ + if( i%2 ) *tokenType = TK_ILLEGAL; + break; + } if( !isxdigit(c) ){ *tokenType = TK_ILLEGAL; + return i; } } - if( i%2 || !c ) *tokenType = TK_ILLEGAL; if( c ) i++; return i; } @@ -79221,13 +71570,16 @@ SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ *tokenType = TK_ILLEGAL; return 1; } +SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){ + return getToken(z, tokenType); +} /* ** Run the parser on the given SQL string. The parser structure is ** passed in. An SQLITE_ status code is returned. If an error occurs -** then an and attempt is made to write an error message into -** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that -** error message. +** and pzErrMsg!=NULL then an error message might be written into +** memory obtained from sqlite3_malloc() and *pzErrMsg made to point to that +** error message. Or maybe not. */ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){ int nErr = 0; @@ -79236,16 +71588,13 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr int tokenType; int lastTokenParsed = -1; sqlite3 *db = pParse->db; - int mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH]; if( db->activeVdbeCnt==0 ){ db->u1.isInterrupted = 0; } pParse->rc = SQLITE_OK; - pParse->zTail = pParse->zSql = zSql; i = 0; - assert( pzErrMsg!=0 ); - pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc); + pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3_malloc); if( pEngine==0 ){ db->mallocFailed = 1; return SQLITE_NOMEM; @@ -79257,13 +71606,14 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr assert( pParse->nVarExpr==0 ); assert( pParse->nVarExprAlloc==0 ); assert( pParse->apVarExpr==0 ); + pParse->zTail = pParse->zSql = zSql; while( !db->mallocFailed && zSql[i]!=0 ){ assert( i>=0 ); pParse->sLastToken.z = (u8*)&zSql[i]; assert( pParse->sLastToken.dyn==0 ); - pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType); + pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType); i += pParse->sLastToken.n; - if( i>mxSqlLen ){ + if( SQLITE_MAX_SQL_LENGTH>0 && i>SQLITE_MAX_SQL_LENGTH ){ pParse->rc = SQLITE_TOOBIG; break; } @@ -79272,15 +71622,17 @@ SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzEr case TK_COMMENT: { if( db->u1.isInterrupted ){ pParse->rc = SQLITE_INTERRUPT; - sqlite3SetString(pzErrMsg, db, "interrupt"); + sqlite3SetString(pzErrMsg, "interrupt", (char*)0); goto abort_parse; } break; } case TK_ILLEGAL: { - sqlite3_free(*pzErrMsg); - *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"", - &pParse->sLastToken); + if( pzErrMsg ){ + sqlite3_free(*pzErrMsg); + *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"", + &pParse->sLastToken); + } nErr++; goto abort_parse; } @@ -79311,16 +71663,16 @@ abort_parse: pParse->rc = SQLITE_NOMEM; } if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){ - sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc)); + sqlite3SetString(&pParse->zErrMsg, sqlite3ErrStr(pParse->rc), (char*)0); } if( pParse->zErrMsg ){ - if( *pzErrMsg==0 ){ + if( pzErrMsg && *pzErrMsg==0 ){ *pzErrMsg = pParse->zErrMsg; }else{ sqlite3_free(pParse->zErrMsg); } pParse->zErrMsg = 0; - nErr++; + if( !nErr ) nErr++; } if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ sqlite3VdbeDelete(pParse->pVdbe); @@ -79333,9 +71685,6 @@ abort_parse: pParse->nTableLock = 0; } #endif -#ifndef SQLITE_OMIT_VIRTUALTABLE - sqlite3_free(pParse->apVtabLock); -#endif if( !IN_DECLARE_VTAB ){ /* If the pParse->declareVtab flag is set, do not delete any table @@ -79373,7 +71722,7 @@ abort_parse: ** separating it out, the code will be automatically omitted from ** static links that do not use it. ** -** $Id: complete.c,v 1.7 2008/06/13 18:24:27 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ #ifndef SQLITE_OMIT_COMPLETE @@ -79614,17 +71963,11 @@ SQLITE_API int sqlite3_complete16(const void *zSql){ char const *zSql8; int rc = SQLITE_NOMEM; -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ) return rc; -#endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); - }else{ - rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); return sqlite3ApiExit(0, rc); @@ -79650,74 +71993,9 @@ SQLITE_API int sqlite3_complete16(const void *zSql){ ** other files are for internal use by SQLite and should not be ** accessed by users of the library. ** -** $Id: main.c,v 1.479 2008/07/16 14:02:33 drh Exp $ +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ -#ifdef SQLITE_ENABLE_FTS3 -/************** Include fts3.h in the middle of main.c ***********************/ -/************** Begin file fts3.h ********************************************/ -/* -** 2006 Oct 10 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This header file is used by programs that want to link against the -** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. -*/ - -#if 0 -extern "C" { -#endif /* __cplusplus */ - -SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db); - -#if 0 -} /* extern "C" */ -#endif /* __cplusplus */ - -/************** End of fts3.h ************************************************/ -/************** Continuing where we left off in main.c ***********************/ -#endif -#ifdef SQLITE_ENABLE_RTREE -/************** Include rtree.h in the middle of main.c **********************/ -/************** Begin file rtree.h *******************************************/ -/* -** 2008 May 26 -** -** The author disclaims copyright to this source code. In place of -** a legal notice, here is a blessing: -** -** May you do good and not evil. -** May you find forgiveness for yourself and forgive others. -** May you share freely, never taking more than you give. -** -****************************************************************************** -** -** This header file is used by programs that want to link against the -** RTREE library. All it does is declare the sqlite3RtreeInit() interface. -*/ - -#if 0 -extern "C" { -#endif /* __cplusplus */ - -SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db); - -#if 0 -} /* extern "C" */ -#endif /* __cplusplus */ - -/************** End of rtree.h ***********************************************/ -/************** Continuing where we left off in main.c ***********************/ -#endif - /* ** The version of the library */ @@ -79726,15 +72004,13 @@ SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; } SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; } SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; } -#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE) /* ** If the following function pointer is not NULL and if ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing ** I/O active are written using this function. These messages ** are intended for debugging activity only. */ -SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0; -#endif +SQLITE_API void (*sqlite3_io_trace)(const char*, ...) = 0; /* ** If the following global variable points to a string which is the @@ -79745,243 +72021,13 @@ SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0; */ SQLITE_API char *sqlite3_temp_directory = 0; -/* -** Initialize SQLite. -** -** This routine must be called to initialize the memory allocation, -** VFS, and mutex subsystesms prior to doing any serious work with -** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT -** this routine will be called automatically by key routines such as -** sqlite3_open(). -** -** This routine is a no-op except on its very first call for the process, -** or for the first call after a call to sqlite3_shutdown. -*/ -SQLITE_API int sqlite3_initialize(void){ - static int inProgress = 0; - int rc; - - /* If SQLite is already initialized, this call is a no-op. */ - if( sqlite3Config.isInit ) return SQLITE_OK; - - /* Make sure the mutex system is initialized. */ - rc = sqlite3MutexInit(); - - if( rc==SQLITE_OK ){ - - /* Initialize the malloc() system and the recursive pInitMutex mutex. - ** This operation is protected by the STATIC_MASTER mutex. - */ - sqlite3_mutex *pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); - sqlite3_mutex_enter(pMaster); - if( !sqlite3Config.isMallocInit ){ - rc = sqlite3MallocInit(); - } - if( rc==SQLITE_OK ){ - sqlite3Config.isMallocInit = 1; - if( !sqlite3Config.pInitMutex ){ - sqlite3Config.pInitMutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); - if( sqlite3Config.bCoreMutex && !sqlite3Config.pInitMutex ){ - rc = SQLITE_NOMEM; - } - } - } - sqlite3_mutex_leave(pMaster); - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Enter the recursive pInitMutex mutex. After doing so, if the - ** sqlite3Config.isInit flag is true, then some other thread has - ** finished doing the initialization. If the inProgress flag is - ** true, then this function is being called recursively from within - ** the sqlite3_os_init() call below. In either case, exit early. - */ - sqlite3_mutex_enter(sqlite3Config.pInitMutex); - if( sqlite3Config.isInit || inProgress ){ - sqlite3_mutex_leave(sqlite3Config.pInitMutex); - return SQLITE_OK; - } - sqlite3StatusReset(); - inProgress = 1; - rc = sqlite3_os_init(); - inProgress = 0; - sqlite3Config.isInit = (rc==SQLITE_OK ? 1 : 0); - sqlite3_mutex_leave(sqlite3Config.pInitMutex); - } - return rc; -} - -/* -** Undo the effects of sqlite3_initialize(). Must not be called while -** there are outstanding database connections or memory allocations or -** while any part of SQLite is otherwise in use in any thread. This -** routine is not threadsafe. Not by a long shot. -*/ -SQLITE_API int sqlite3_shutdown(void){ - sqlite3_mutex_free(sqlite3Config.pInitMutex); - sqlite3Config.pInitMutex = 0; - sqlite3Config.isMallocInit = 0; - if( sqlite3Config.isInit ){ - sqlite3_os_end(); - } - if( sqlite3Config.m.xShutdown ){ - sqlite3MallocEnd(); - } - if( sqlite3Config.mutex.xMutexEnd ){ - sqlite3MutexEnd(); - } - sqlite3Config.isInit = 0; - return SQLITE_OK; -} - -/* -** This API allows applications to modify the global configuration of -** the SQLite library at run-time. -** -** This routine should only be called when there are no outstanding -** database connections or memory allocations. This routine is not -** threadsafe. Failure to heed these warnings can lead to unpredictable -** behavior. -*/ -SQLITE_API int sqlite3_config(int op, ...){ - va_list ap; - int rc = SQLITE_OK; - - /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while - ** the SQLite library is in use. */ - if( sqlite3Config.isInit ) return SQLITE_MISUSE; - - va_start(ap, op); - switch( op ){ - case SQLITE_CONFIG_SINGLETHREAD: { - /* Disable all mutexing */ - sqlite3Config.bCoreMutex = 0; - sqlite3Config.bFullMutex = 0; - break; - } - case SQLITE_CONFIG_MULTITHREAD: { - /* Disable mutexing of database connections */ - /* Enable mutexing of core data structures */ - sqlite3Config.bCoreMutex = 1; - sqlite3Config.bFullMutex = 0; - break; - } - case SQLITE_CONFIG_SERIALIZED: { - /* Enable all mutexing */ - sqlite3Config.bCoreMutex = 1; - sqlite3Config.bFullMutex = 1; - break; - } - case SQLITE_CONFIG_MALLOC: { - /* Specify an alternative malloc implementation */ - sqlite3Config.m = *va_arg(ap, sqlite3_mem_methods*); - break; - } - case SQLITE_CONFIG_GETMALLOC: { - /* Retrieve the current malloc() implementation */ - if( sqlite3Config.m.xMalloc==0 ) sqlite3MemSetDefault(); - *va_arg(ap, sqlite3_mem_methods*) = sqlite3Config.m; - break; - } - case SQLITE_CONFIG_MUTEX: { - /* Specify an alternative mutex implementation */ - sqlite3Config.mutex = *va_arg(ap, sqlite3_mutex_methods*); - break; - } - case SQLITE_CONFIG_GETMUTEX: { - /* Retrieve the current mutex implementation */ - *va_arg(ap, sqlite3_mutex_methods*) = sqlite3Config.mutex; - break; - } - case SQLITE_CONFIG_MEMSTATUS: { - /* Enable or disable the malloc status collection */ - sqlite3Config.bMemstat = va_arg(ap, int); - break; - } - case SQLITE_CONFIG_SCRATCH: { - /* Designate a buffer for scratch memory space */ - sqlite3Config.pScratch = va_arg(ap, void*); - sqlite3Config.szScratch = va_arg(ap, int); - sqlite3Config.nScratch = va_arg(ap, int); - break; - } - case SQLITE_CONFIG_PAGECACHE: { - /* Designate a buffer for scratch memory space */ - sqlite3Config.pPage = va_arg(ap, void*); - sqlite3Config.szPage = va_arg(ap, int); - sqlite3Config.nPage = va_arg(ap, int); - break; - } - -#if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5) - case SQLITE_CONFIG_HEAP: { - /* Designate a buffer for heap memory space */ - sqlite3Config.pHeap = va_arg(ap, void*); - sqlite3Config.nHeap = va_arg(ap, int); - sqlite3Config.mnReq = va_arg(ap, int); - - if( sqlite3Config.pHeap==0 ){ - /* If the heap pointer is NULL, then restore the malloc implementation - ** back to NULL pointers too. This will cause the malloc to go - ** back to its default implementation when sqlite3_initialize() is - ** run. - */ - memset(&sqlite3Config.m, 0, sizeof(sqlite3Config.m)); - }else{ - /* The heap pointer is not NULL, then install one of the - ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor - ** ENABLE_MEMSYS5 is defined, return an error. - ** the default case and return an error. - */ -#ifdef SQLITE_ENABLE_MEMSYS3 - sqlite3Config.m = *sqlite3MemGetMemsys3(); -#endif -#ifdef SQLITE_ENABLE_MEMSYS5 - sqlite3Config.m = *sqlite3MemGetMemsys5(); -#endif - } - break; - } -#endif - - default: { - rc = SQLITE_ERROR; - break; - } - } - va_end(ap); - return rc; -} - -/* -** Routine needed to support the testcase() macro. -*/ -#ifdef SQLITE_COVERAGE_TEST -SQLITE_PRIVATE void sqlite3Coverage(int x){ - static int dummy = 0; - dummy += x; -} -#endif - - -/* -** Return true if the buffer z[0..n-1] contains all spaces. -*/ -static int allSpaces(const char *z, int n){ - while( n>0 && z[n-1]==' ' ){ n--; } - return n==0; -} /* ** This is the default collating function named "BINARY" which is always ** available. -** -** If the padFlag argument is not NULL then space padding at the end -** of strings is ignored. This implements the RTRIM collation. */ static int binCollFunc( - void *padFlag, + void *NotUsed, int nKey1, const void *pKey1, int nKey2, const void *pKey2 ){ @@ -79989,14 +72035,7 @@ static int binCollFunc( n = nKey1mutex); @@ -80084,7 +72123,21 @@ SQLITE_API int sqlite3_close(sqlite3 *db){ sqlite3_mutex_leave(db->mutex); return SQLITE_BUSY; } - assert( sqlite3SafetyCheckSickOrOk(db) ); + assert( !sqlite3SafetyCheck(db) ); + + /* FIX ME: db->magic may be set to SQLITE_MAGIC_CLOSED if the database + ** cannot be opened for some reason. So this routine needs to run in + ** that case. But maybe there should be an extra magic value for the + ** "failed to open" state. + ** + ** TODO: Coverage tests do not test the case where this condition is + ** true. It's hard to see how to cause it without messing with threads. + */ + if( db->magic!=SQLITE_MAGIC_CLOSED && sqlite3SafetyOn(db) ){ + /* printf("DID NOT CLOSE\n"); fflush(stdout); */ + sqlite3_mutex_leave(db->mutex); + return SQLITE_ERROR; + } for(j=0; jnDb; j++){ struct Db *pDb = &db->aDb[j]; @@ -80146,7 +72199,6 @@ SQLITE_API int sqlite3_close(sqlite3 *db){ */ sqlite3_free(db->aDb[1].pSchema); sqlite3_mutex_leave(db->mutex); - db->magic = SQLITE_MAGIC_CLOSED; sqlite3_mutex_free(db->mutex); sqlite3_free(db); return SQLITE_OK; @@ -80159,7 +72211,7 @@ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){ int i; int inTrans = 0; assert( sqlite3_mutex_held(db->mutex) ); - sqlite3BeginBenignMalloc(); + sqlite3MallocEnterBenignBlock(1); /* Enter benign region */ for(i=0; inDb; i++){ if( db->aDb[i].pBt ){ if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){ @@ -80170,7 +72222,7 @@ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){ } } sqlite3VtabRollback(db); - sqlite3EndBenignMalloc(); + sqlite3MallocLeaveBenignBlock(); /* Leave benign region */ if( db->flags&SQLITE_InternChanges ){ sqlite3ExpirePreparedStatements(db); @@ -80211,7 +72263,7 @@ SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){ case SQLITE_CONSTRAINT: z = "constraint failed"; break; case SQLITE_MISMATCH: z = "datatype mismatch"; break; case SQLITE_MISUSE: z = "library routine called out of sequence";break; - case SQLITE_NOLFS: z = "large file support is disabled"; break; + case SQLITE_NOLFS: z = "kernel lacks large file support"; break; case SQLITE_AUTH: z = "authorization denied"; break; case SQLITE_FORMAT: z = "auxiliary database format error"; break; case SQLITE_RANGE: z = "bind or column index out of range"; break; @@ -80231,7 +72283,7 @@ static int sqliteDefaultBusyCallback( void *ptr, /* Database connection */ int count /* Number of times table has been busy */ ){ -#if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP) +#if OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP) static const u8 delays[] = { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 }; static const u8 totals[] = @@ -80275,7 +72327,7 @@ static int sqliteDefaultBusyCallback( */ SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){ int rc; - if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0; + if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0; rc = p->xFunc(p->pArg, p->nBusy); if( rc==0 ){ p->nBusy = -1; @@ -80294,6 +72346,9 @@ SQLITE_API int sqlite3_busy_handler( int (*xBusy)(void*,int), void *pArg ){ + if( sqlite3SafetyCheck(db) ){ + return SQLITE_MISUSE; + } sqlite3_mutex_enter(db->mutex); db->busyHandler.xFunc = xBusy; db->busyHandler.pArg = pArg; @@ -80314,17 +72369,19 @@ SQLITE_API void sqlite3_progress_handler( int (*xProgress)(void*), void *pArg ){ - sqlite3_mutex_enter(db->mutex); - if( nOps>0 ){ - db->xProgress = xProgress; - db->nProgressOps = nOps; - db->pProgressArg = pArg; - }else{ - db->xProgress = 0; - db->nProgressOps = 0; - db->pProgressArg = 0; + if( !sqlite3SafetyCheck(db) ){ + sqlite3_mutex_enter(db->mutex); + if( nOps>0 ){ + db->xProgress = xProgress; + db->nProgressOps = nOps; + db->pProgressArg = pArg; + }else{ + db->xProgress = 0; + db->nProgressOps = 0; + db->pProgressArg = 0; + } + sqlite3_mutex_leave(db->mutex); } - sqlite3_mutex_leave(db->mutex); } #endif @@ -80334,6 +72391,9 @@ SQLITE_API void sqlite3_progress_handler( ** specified number of milliseconds before returning 0. */ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ + if( sqlite3SafetyCheck(db) ){ + return SQLITE_MISUSE; + } if( ms>0 ){ db->busyTimeout = ms; sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db); @@ -80347,7 +72407,9 @@ SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){ ** Cause any pending operation to stop at its earliest opportunity. */ SQLITE_API void sqlite3_interrupt(sqlite3 *db){ - db->u1.isInterrupted = 1; + if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){ + db->u1.isInterrupted = 1; + } } @@ -80371,12 +72433,15 @@ SQLITE_PRIVATE int sqlite3CreateFunc( int nName; assert( sqlite3_mutex_held(db->mutex) ); + if( sqlite3SafetyCheck(db) ){ + return SQLITE_MISUSE; + } if( zFunctionName==0 || (xFunc && (xFinal || xStep)) || (!xFunc && (xFinal && !xStep)) || (!xFunc && (!xFinal && xStep)) || - (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) || - (255<(nName = sqlite3Strlen(db, zFunctionName))) ){ + (nArg<-1 || nArg>127) || + (255<(nName = strlen(zFunctionName))) ){ sqlite3Error(db, SQLITE_ERROR, "bad parameters"); return SQLITE_ERROR; } @@ -80454,6 +72519,7 @@ SQLITE_API int sqlite3_create_function( ){ int rc; sqlite3_mutex_enter(db->mutex); + assert( !db->mallocFailed ); rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db->mutex); @@ -80502,7 +72568,7 @@ SQLITE_API int sqlite3_overload_function( const char *zName, int nArg ){ - int nName = sqlite3Strlen(db, zName); + int nName = strlen(zName); int rc; sqlite3_mutex_enter(db->mutex); if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){ @@ -80622,19 +72688,19 @@ SQLITE_API void *sqlite3_rollback_hook( ** ** A virtual database can be either a disk file (that is automatically ** deleted when the file is closed) or it an be held entirely in memory, -** depending on the values of the SQLITE_TEMP_STORE compile-time macro and the +** depending on the values of the TEMP_STORE compile-time macro and the ** db->temp_store variable, according to the following chart: ** -** SQLITE_TEMP_STORE db->temp_store Location of temporary database -** ----------------- -------------- ------------------------------ -** 0 any file -** 1 1 file -** 1 2 memory -** 1 0 file -** 2 1 file -** 2 2 memory -** 2 0 memory -** 3 any memory +** TEMP_STORE db->temp_store Location of temporary database +** ---------- -------------- ------------------------------ +** 0 any file +** 1 1 file +** 1 2 memory +** 1 0 file +** 2 1 file +** 2 2 memory +** 2 0 memory +** 3 any memory */ SQLITE_PRIVATE int sqlite3BtreeFactory( const sqlite3 *db, /* Main database when opening aux otherwise 0 */ @@ -80656,17 +72722,17 @@ SQLITE_PRIVATE int sqlite3BtreeFactory( btFlags |= BTREE_NO_READLOCK; } if( zFilename==0 ){ -#if SQLITE_TEMP_STORE==0 +#if TEMP_STORE==0 /* Do nothing */ #endif #ifndef SQLITE_OMIT_MEMORYDB -#if SQLITE_TEMP_STORE==1 +#if TEMP_STORE==1 if( db->temp_store==2 ) zFilename = ":memory:"; #endif -#if SQLITE_TEMP_STORE==2 +#if TEMP_STORE==2 if( db->temp_store!=1 ) zFilename = ":memory:"; #endif -#if SQLITE_TEMP_STORE==3 +#if TEMP_STORE==3 zFilename = ":memory:"; #endif #endif /* SQLITE_OMIT_MEMORYDB */ @@ -80676,13 +72742,7 @@ SQLITE_PRIVATE int sqlite3BtreeFactory( vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; } rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags); - - /* If the B-Tree was successfully opened, set the pager-cache size to the - ** default value. Except, if the call to BtreeOpen() returned a handle - ** open on an existing shared pager-cache, do not change the pager-cache - ** size. - */ - if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){ + if( rc==SQLITE_OK ){ sqlite3BtreeSetCacheSize(*ppBtree, nCache); } return rc; @@ -80697,13 +72757,12 @@ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ if( !db ){ return sqlite3ErrStr(SQLITE_NOMEM); } - if( !sqlite3SafetyCheckSickOrOk(db) ){ + if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){ return sqlite3ErrStr(SQLITE_MISUSE); } sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); z = (char*)sqlite3_value_text(db->pErr); - assert( !db->mallocFailed ); if( z==0 ){ z = sqlite3ErrStr(db->errCode); } @@ -80740,7 +72799,7 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ if( !db ){ return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]); } - if( !sqlite3SafetyCheckSickOrOk(db) ){ + if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){ return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]); } sqlite3_mutex_enter(db->mutex); @@ -80751,12 +72810,7 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ SQLITE_UTF8, SQLITE_STATIC); z = sqlite3_value_text16(db->pErr); } - /* A malloc() may have failed within the call to sqlite3_value_text16() - ** above. If this is the case, then the db->mallocFailed flag needs to - ** be cleared before returning. Do this directly, instead of via - ** sqlite3ApiExit(), to avoid setting the database handle error message. - */ - db->mallocFailed = 0; + sqlite3ApiExit(0, 0); sqlite3_mutex_leave(db->mutex); return z; } @@ -80767,12 +72821,12 @@ SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){ ** passed to this function, we assume a malloc() failed during sqlite3_open(). */ SQLITE_API int sqlite3_errcode(sqlite3 *db){ - if( db && !sqlite3SafetyCheckSickOrOk(db) ){ - return SQLITE_MISUSE; - } if( !db || db->mallocFailed ){ return SQLITE_NOMEM; } + if( sqlite3SafetyCheck(db) ){ + return SQLITE_MISUSE; + } return db->errCode & db->errMask; } @@ -80790,8 +72844,10 @@ static int createCollation( ){ CollSeq *pColl; int enc2; - int nName; + if( sqlite3SafetyCheck(db) ){ + return SQLITE_MISUSE; + } assert( sqlite3_mutex_held(db->mutex) ); /* If SQLITE_UTF16 is specified as the encoding type, transform this @@ -80802,16 +72858,17 @@ static int createCollation( if( enc2==SQLITE_UTF16 ){ enc2 = SQLITE_UTF16NATIVE; } + if( (enc2&~3)!=0 ){ - return SQLITE_MISUSE; + sqlite3Error(db, SQLITE_ERROR, "unknown encoding"); + return SQLITE_ERROR; } /* Check if this call is removing or replacing an existing collation ** sequence. If so, and there are active VMs, return busy. If there ** are no active VMs, invalidate any pre-compiled statements. */ - nName = sqlite3Strlen(db, zName); - pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 0); + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 0); if( pColl && pColl->xCmp ){ if( db->activeVdbeCnt ){ sqlite3Error(db, SQLITE_BUSY, @@ -80827,7 +72884,7 @@ static int createCollation( ** to be called. */ if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){ - CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName); + CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, strlen(zName)); int j; for(j=0; j<3; j++){ CollSeq *p = &aColl[j]; @@ -80841,7 +72898,7 @@ static int createCollation( } } - pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, nName, 1); + pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, strlen(zName), 1); if( pColl ){ pColl->xCmp = xCompare; pColl->pUser = pCtx; @@ -80853,81 +72910,6 @@ static int createCollation( } -/* -** This array defines hard upper bounds on limit values. The -** initializer must be kept in sync with the SQLITE_LIMIT_* -** #defines in sqlite3.h. -*/ -static const int aHardLimit[] = { - SQLITE_MAX_LENGTH, - SQLITE_MAX_SQL_LENGTH, - SQLITE_MAX_COLUMN, - SQLITE_MAX_EXPR_DEPTH, - SQLITE_MAX_COMPOUND_SELECT, - SQLITE_MAX_VDBE_OP, - SQLITE_MAX_FUNCTION_ARG, - SQLITE_MAX_ATTACHED, - SQLITE_MAX_LIKE_PATTERN_LENGTH, - SQLITE_MAX_VARIABLE_NUMBER, -}; - -/* -** Make sure the hard limits are set to reasonable values -*/ -#if SQLITE_MAX_LENGTH<100 -# error SQLITE_MAX_LENGTH must be at least 100 -#endif -#if SQLITE_MAX_SQL_LENGTH<100 -# error SQLITE_MAX_SQL_LENGTH must be at least 100 -#endif -#if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH -# error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH -#endif -#if SQLITE_MAX_COMPOUND_SELECT<2 -# error SQLITE_MAX_COMPOUND_SELECT must be at least 2 -#endif -#if SQLITE_MAX_VDBE_OP<40 -# error SQLITE_MAX_VDBE_OP must be at least 40 -#endif -#if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127 -# error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127 -#endif -#if SQLITE_MAX_ATTACH<0 || SQLITE_MAX_ATTACH>30 -# error SQLITE_MAX_ATTACH must be between 0 and 30 -#endif -#if SQLITE_MAX_LIKE_PATTERN_LENGTH<1 -# error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1 -#endif -#if SQLITE_MAX_VARIABLE_NUMBER<1 -# error SQLITE_MAX_VARIABLE_NUMBER must be at least 1 -#endif - - -/* -** Change the value of a limit. Report the old value. -** If an invalid limit index is supplied, report -1. -** Make no changes but still report the old value if the -** new limit is negative. -** -** A new lower limit does not shrink existing constructs. -** It merely prevents new constructs that exceed the limit -** from forming. -*/ -SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){ - int oldLimit; - if( limitId<0 || limitId>=SQLITE_N_LIMIT ){ - return -1; - } - oldLimit = db->aLimit[limitId]; - if( newLimit>=0 ){ - if( newLimit>aHardLimit[limitId] ){ - newLimit = aHardLimit[limitId]; - } - db->aLimit[limitId] = newLimit; - } - return oldLimit; -} - /* ** This routine does the work of opening a database on behalf of ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename" @@ -80942,39 +72924,15 @@ static int openDatabase( sqlite3 *db; int rc; CollSeq *pColl; - int isThreadsafe = 1; - -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ) return rc; -#endif - - if( flags&SQLITE_OPEN_NOMUTEX ){ - isThreadsafe = 0; - } - - /* Remove harmful bits from the flags parameter */ - flags &= ~( SQLITE_OPEN_DELETEONCLOSE | - SQLITE_OPEN_MAIN_DB | - SQLITE_OPEN_TEMP_DB | - SQLITE_OPEN_TRANSIENT_DB | - SQLITE_OPEN_MAIN_JOURNAL | - SQLITE_OPEN_TEMP_JOURNAL | - SQLITE_OPEN_SUBJOURNAL | - SQLITE_OPEN_MASTER_JOURNAL | - SQLITE_OPEN_NOMUTEX - ); /* Allocate the sqlite data structure */ db = sqlite3MallocZero( sizeof(sqlite3) ); if( db==0 ) goto opendb_out; - if( sqlite3Config.bFullMutex && isThreadsafe ){ - db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE); - if( db->mutex==0 ){ - sqlite3_free(db); - db = 0; - goto opendb_out; - } + db->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE); + if( db->mutex==0 ){ + sqlite3_free(db); + db = 0; + goto opendb_out; } sqlite3_mutex_enter(db->mutex); db->errMask = 0xff; @@ -80982,11 +72940,8 @@ static int openDatabase( db->nDb = 2; db->magic = SQLITE_MAGIC_BUSY; db->aDb = db->aDbStatic; - assert( sizeof(db->aLimit)==sizeof(aHardLimit) ); - memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit)); db->autoCommit = 1; db->nextAutovac = -1; - db->nextPagesize = 0; db->flags |= SQLITE_ShortColNames #if SQLITE_DEFAULT_FILE_FORMAT<4 | SQLITE_LegacyFileFmt @@ -81004,8 +72959,8 @@ static int openDatabase( db->pVfs = sqlite3_vfs_find(zVfs); if( !db->pVfs ){ rc = SQLITE_ERROR; - db->magic = SQLITE_MAGIC_SICK; - sqlite3Error(db, rc, "no such vfs: %s", zVfs); + db->magic = SQLITE_MAGIC_CLOSED; + sqlite3Error(db, rc, "no such vfs: %s", (zVfs?zVfs:"(null)")); goto opendb_out; } @@ -81013,16 +72968,15 @@ static int openDatabase( ** and UTF-16, so add a version for each to avoid any unnecessary ** conversions. The only error that can occur here is a malloc() failure. */ - createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0); - createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0); - createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0); - createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0); - if( db->mallocFailed ){ - db->magic = SQLITE_MAGIC_SICK; + if( createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0) || + createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0) || + createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0) || + (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0 + ){ + assert( db->mallocFailed ); + db->magic = SQLITE_MAGIC_CLOSED; goto opendb_out; } - db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0); - assert( db->pDfltColl!=0 ); /* Also add a UTF-8 case-insensitive collation sequence. */ createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); @@ -81041,7 +72995,7 @@ static int openDatabase( &db->aDb[0].pBt); if( rc!=SQLITE_OK ){ sqlite3Error(db, rc, 0); - db->magic = SQLITE_MAGIC_SICK; + db->magic = SQLITE_MAGIC_CLOSED; goto opendb_out; } db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); @@ -81094,6 +73048,7 @@ static int openDatabase( #ifdef SQLITE_ENABLE_FTS3 if( !db->mallocFailed && rc==SQLITE_OK ){ + extern int sqlite3Fts3Init(sqlite3*); rc = sqlite3Fts3Init(db); } #endif @@ -81104,13 +73059,6 @@ static int openDatabase( rc = sqlite3IcuInit(db); } #endif - -#ifdef SQLITE_ENABLE_RTREE - if( !db->mallocFailed && rc==SQLITE_OK){ - rc = sqlite3RtreeInit(db); - } -#endif - sqlite3Error(db, rc, 0); /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking @@ -81124,8 +73072,7 @@ static int openDatabase( #endif opendb_out: - if( db ){ - assert( db->mutex!=0 || isThreadsafe==0 || sqlite3Config.bFullMutex==0 ); + if( db && db->mutex ){ sqlite3_mutex_leave(db->mutex); } if( SQLITE_NOMEM==(rc = sqlite3_errcode(db)) ){ @@ -81165,27 +73112,24 @@ SQLITE_API int sqlite3_open16( ){ char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */ sqlite3_value *pVal; - int rc; + int rc = SQLITE_NOMEM; assert( zFilename ); assert( ppDb ); *ppDb = 0; -#ifndef SQLITE_OMIT_AUTOINIT - rc = sqlite3_initialize(); - if( rc ) return rc; -#endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC); zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zFilename8 ){ rc = openDatabase(zFilename8, ppDb, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0); - assert( *ppDb || rc==SQLITE_NOMEM ); - if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){ - ENC(*ppDb) = SQLITE_UTF16NATIVE; + if( rc==SQLITE_OK && *ppDb ){ + rc = sqlite3_exec(*ppDb, "PRAGMA encoding = 'UTF-16'", 0, 0, 0); + if( rc!=SQLITE_OK ){ + sqlite3_close(*ppDb); + *ppDb = 0; + } } - }else{ - rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); @@ -81238,13 +73182,13 @@ SQLITE_API int sqlite3_create_collation_v2( */ SQLITE_API int sqlite3_create_collation16( sqlite3* db, - const void *zName, + const char *zName, int enc, void* pCtx, int(*xCompare)(void*,int,const void*,int,const void*) ){ int rc = SQLITE_OK; - char *zName8; + char *zName8; sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); zName8 = sqlite3Utf16to8(db, zName, -1); @@ -81267,6 +73211,9 @@ SQLITE_API int sqlite3_collation_needed( void *pCollNeededArg, void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*) ){ + if( sqlite3SafetyCheck(db) ){ + return SQLITE_MISUSE; + } sqlite3_mutex_enter(db->mutex); db->xCollNeeded = xCollNeeded; db->xCollNeeded16 = 0; @@ -81285,6 +73232,9 @@ SQLITE_API int sqlite3_collation_needed16( void *pCollNeededArg, void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*) ){ + if( sqlite3SafetyCheck(db) ){ + return SQLITE_MISUSE; + } sqlite3_mutex_enter(db->mutex); db->xCollNeeded = 0; db->xCollNeeded16 = xCollNeeded16; @@ -81351,7 +73301,7 @@ SQLITE_API int sqlite3_table_column_metadata( char const **pzCollSeq, /* OUTPUT: Collation sequence name */ int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ - int *pAutoinc /* OUTPUT: True if column is auto-increment */ + int *pAutoinc /* OUTPUT: True if colums is auto-increment */ ){ int rc; char *zErrMsg = 0; @@ -81366,11 +73316,11 @@ SQLITE_API int sqlite3_table_column_metadata( int autoinc = 0; /* Ensure the database schema has been loaded */ + if( sqlite3SafetyOn(db) ){ + return SQLITE_MISUSE; + } sqlite3_mutex_enter(db->mutex); - (void)sqlite3SafetyOn(db); - sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, &zErrMsg); - sqlite3BtreeLeaveAll(db); if( SQLITE_OK!=rc ){ goto error_out; } @@ -81414,9 +73364,9 @@ SQLITE_API int sqlite3_table_column_metadata( if( pCol ){ zDataType = pCol->zType; zCollSeq = pCol->zColl; - notnull = pCol->notNull!=0; - primarykey = pCol->isPrimKey!=0; - autoinc = pTab->iPKey==iCol && pTab->autoInc; + notnull = (pCol->notNull?1:0); + primarykey = (pCol->isPrimKey?1:0); + autoinc = ((pTab->iPKey==iCol && pTab->autoInc)?1:0); }else{ zDataType = "INTEGER"; primarykey = 1; @@ -81426,7 +73376,9 @@ SQLITE_API int sqlite3_table_column_metadata( } error_out: - (void)sqlite3SafetyOff(db); + if( sqlite3SafetyOff(db) ){ + rc = SQLITE_MISUSE; + } /* Whether the function call succeeded or failed, set the output parameters ** to whatever their local counterparts contain. If an error did occur, @@ -81439,9 +73391,8 @@ error_out: if( pAutoinc ) *pAutoinc = autoinc; if( SQLITE_OK==rc && !pTab ){ - sqlite3_free(zErrMsg); - zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName, - zColumnName); + sqlite3SetString(&zErrMsg, "no such table column: ", zTableName, ".", + zColumnName, 0); rc = SQLITE_ERROR; } sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg); @@ -81459,7 +73410,6 @@ SQLITE_API int sqlite3_sleep(int ms){ sqlite3_vfs *pVfs; int rc; pVfs = sqlite3_vfs_find(0); - if( pVfs==0 ) return 0; /* This function works in milliseconds, but the underlying OsSleep() ** API uses microseconds. Hence the 1000's. @@ -81496,14 +73446,13 @@ SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, vo Btree *pBtree = db->aDb[iDb].pBt; if( pBtree ){ Pager *pPager; - sqlite3_file *fd; sqlite3BtreeEnter(pBtree); pPager = sqlite3BtreePager(pBtree); - assert( pPager!=0 ); - fd = sqlite3PagerFile(pPager); - assert( fd!=0 ); - if( fd->pMethods ){ - rc = sqlite3OsFileControl(fd, op, pArg); + if( pPager ){ + sqlite3_file *fd = sqlite3PagerFile(pPager); + if( fd ){ + rc = sqlite3OsFileControl(fd, op, pArg); + } } sqlite3BtreeLeave(pBtree); } @@ -81512,81 +73461,17 @@ SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, vo return rc; } -/* -** Interface to the testing logic. -*/ -SQLITE_API int sqlite3_test_control(int op, ...){ - int rc = 0; -#ifndef SQLITE_OMIT_BUILTIN_TEST - va_list ap; - va_start(ap, op); - switch( op ){ - - /* - ** Save the current state of the PRNG. - */ - case SQLITE_TESTCTRL_PRNG_SAVE: { - sqlite3PrngSaveState(); - break; - } - - /* - ** Restore the state of the PRNG to the last state saved using - ** PRNG_SAVE. If PRNG_SAVE has never before been called, then - ** this verb acts like PRNG_RESET. - */ - case SQLITE_TESTCTRL_PRNG_RESTORE: { - sqlite3PrngRestoreState(); - break; - } - - /* - ** Reset the PRNG back to its uninitialized state. The next call - ** to sqlite3_randomness() will reseed the PRNG using a single call - ** to the xRandomness method of the default VFS. - */ - case SQLITE_TESTCTRL_PRNG_RESET: { - sqlite3PrngResetState(); - break; - } - - /* - ** sqlite3_test_control(BITVEC_TEST, size, program) - ** - ** Run a test against a Bitvec object of size. The program argument - ** is an array of integers that defines the test. Return -1 on a - ** memory allocation error, 0 on success, or non-zero for an error. - ** See the sqlite3BitvecBuiltinTest() for additional information. - */ - case SQLITE_TESTCTRL_BITVEC_TEST: { - int sz = va_arg(ap, int); - int *aProg = va_arg(ap, int*); - rc = sqlite3BitvecBuiltinTest(sz, aProg); - break; - } - - /* - ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd) - ** - ** Register hooks to call to indicate which malloc() failures - ** are benign. - */ - case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: { - typedef void (*void_function)(void); - void_function xBenignBegin; - void_function xBenignEnd; - xBenignBegin = va_arg(ap, void_function); - xBenignEnd = va_arg(ap, void_function); - sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd); - break; - } - } - va_end(ap); -#endif /* SQLITE_OMIT_BUILTIN_TEST */ - return rc; -} - /************** End of main.c ************************************************/ +/****************************************************************************** +** This file is an amalgamation of separate C source files from the SQLite +** Full Text Search extension 2 (fts3). By combining all the individual C +** code files into this single large file, the entire code can be compiled +** as a one translation unit. This allows many compilers to do optimizations +** that would not be possible if the files were compiled separately. It also +** makes the code easier to import into other projects. +** +** This amalgamation was generated on 2008-01-26 07:51:19 UTC. +*/ /************** Begin file fts3.c ********************************************/ /* ** 2006 Oct 10 @@ -81868,7 +73753,3887 @@ SQLITE_API int sqlite3_test_control(int op, ...){ # define SQLITE_CORE 1 #endif +#include +#include +#include +#include +#include +/************** Include fts3.h in the middle of fts3.c ***********************/ +/************** Begin file fts3.h ********************************************/ +/* +** 2006 Oct 10 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +****************************************************************************** +** +** This header file is used by programs that want to link against the +** FTS3 library. All it does is declare the sqlite3Fts3Init() interface. +*/ +/************** Include sqlite3.h in the middle of fts3.h ********************/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ +#include /* Needed for the definition of va_list */ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection {F12010} +** +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. +** +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} +** +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. +** +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. +** +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. +** +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK +** +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. +** +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} +** +** See also: [SQLITE_IOERR_READ | extended result codes] +** +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 + +/* +** CAPI3REF: Device Characteristics {F10240} +** +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} +** +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} +** +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} +** +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the +** these integer values as the second argument. +** +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means +** to use Mac OS-X style fullsync instead of fsync(). +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + + +/* +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object {F11120} +** +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** +** The integer values to xLock() and xUnlock() are one of +**
        +**
      • [SQLITE_LOCK_NONE], +**
      • [SQLITE_LOCK_SHARED], +**
      • [SQLITE_LOCK_RESERVED], +**
      • [SQLITE_LOCK_PENDING], or +**
      • [SQLITE_LOCK_EXCLUSIVE]. +**
      +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 + +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +**
      +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +** +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in fts3.h ***********************/ + +#if 0 +extern "C" { +#endif /* __cplusplus */ + +int sqlite3Fts3Init(sqlite3 *db); + +#if 0 +} /* extern "C" */ +#endif /* __cplusplus */ + +/************** End of fts3.h ************************************************/ +/************** Continuing where we left off in fts3.c ***********************/ /************** Include fts3_hash.h in the middle of fts3.c ******************/ /************** Begin file fts3_hash.h ***************************************/ /* @@ -81944,10 +77709,10 @@ struct fts3HashElem { /* ** Access routines. To delete, insert a NULL pointer. */ -SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey); -SQLITE_PRIVATE void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData); -SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey); -SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*); +void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey); +void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData); +void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey); +void sqlite3Fts3HashClear(fts3Hash*); /* ** Shorthand for the functions above @@ -82012,6 +77777,3850 @@ SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash*); ** If tokenizers are to be allowed to call sqlite3_*() functions, then ** we will need a way to register the API consistently. */ +/************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection {F12010} +** +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. +** +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} +** +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. +** +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. +** +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. +** +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK +** +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. +** +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} +** +** See also: [SQLITE_IOERR_READ | extended result codes] +** +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 + +/* +** CAPI3REF: Device Characteristics {F10240} +** +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} +** +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} +** +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} +** +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the +** these integer values as the second argument. +** +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means +** to use Mac OS-X style fullsync instead of fsync(). +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + + +/* +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object {F11120} +** +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** +** The integer values to xLock() and xUnlock() are one of +**
        +**
      • [SQLITE_LOCK_NONE], +**
      • [SQLITE_LOCK_SHARED], +**
      • [SQLITE_LOCK_RESERVED], +**
      • [SQLITE_LOCK_PENDING], or +**
      • [SQLITE_LOCK_EXCLUSIVE]. +**
      +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 + +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +** +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +**
      +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in fts3_tokenizer.h *************/ /* ** Structures used by the tokenizer interface. When a new tokenizer @@ -82134,6 +81743,7 @@ struct sqlite3_tokenizer_cursor { /************** End of fts3_tokenizer.h **************************************/ /************** Continuing where we left off in fts3.c ***********************/ #ifndef SQLITE_CORE + #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #endif @@ -83750,22 +83360,17 @@ typedef enum fulltext_statement { CONTENT_SELECT_STMT, CONTENT_UPDATE_STMT, CONTENT_DELETE_STMT, - CONTENT_EXISTS_STMT, BLOCK_INSERT_STMT, BLOCK_SELECT_STMT, BLOCK_DELETE_STMT, - BLOCK_DELETE_ALL_STMT, SEGDIR_MAX_INDEX_STMT, SEGDIR_SET_STMT, - SEGDIR_SELECT_LEVEL_STMT, + SEGDIR_SELECT_STMT, SEGDIR_SPAN_STMT, SEGDIR_DELETE_STMT, - SEGDIR_SELECT_SEGMENT_STMT, SEGDIR_SELECT_ALL_STMT, - SEGDIR_DELETE_ALL_STMT, - SEGDIR_COUNT_STMT, MAX_STMT /* Always at end! */ } fulltext_statement; @@ -83780,35 +83385,23 @@ static const char *const fulltext_zStatement[MAX_STMT] = { /* CONTENT_SELECT */ NULL, /* generated in contentSelectStatement() */ /* CONTENT_UPDATE */ NULL, /* generated in contentUpdateStatement() */ /* CONTENT_DELETE */ "delete from %_content where docid = ?", - /* CONTENT_EXISTS */ "select docid from %_content limit 1", /* BLOCK_INSERT */ "insert into %_segments (blockid, block) values (null, ?)", /* BLOCK_SELECT */ "select block from %_segments where blockid = ?", /* BLOCK_DELETE */ "delete from %_segments where blockid between ? and ?", - /* BLOCK_DELETE_ALL */ "delete from %_segments", /* SEGDIR_MAX_INDEX */ "select max(idx) from %_segdir where level = ?", /* SEGDIR_SET */ "insert into %_segdir values (?, ?, ?, ?, ?, ?)", - /* SEGDIR_SELECT_LEVEL */ + /* SEGDIR_SELECT */ "select start_block, leaves_end_block, root from %_segdir " " where level = ? order by idx", /* SEGDIR_SPAN */ "select min(start_block), max(end_block) from %_segdir " " where level = ? and start_block <> 0", /* SEGDIR_DELETE */ "delete from %_segdir where level = ?", - - /* NOTE(shess): The first three results of the following two - ** statements must match. - */ - /* SEGDIR_SELECT_SEGMENT */ - "select start_block, leaves_end_block, root from %_segdir " - " where level = ? and idx = ?", /* SEGDIR_SELECT_ALL */ - "select start_block, leaves_end_block, root from %_segdir " - " order by level desc, idx asc", - /* SEGDIR_DELETE_ALL */ "delete from %_segdir", - /* SEGDIR_COUNT */ "select count(*), ifnull(max(level),0) from %_segdir", + "select root, leaves_end_block from %_segdir order by level desc, idx", }; /* @@ -83973,18 +83566,15 @@ static int sql_single_step(sqlite3_stmt *s){ } /* Like sql_get_statement(), but for special replicated LEAF_SELECT -** statements. idx -1 is a special case for an uncached version of -** the statement (used in the optimize implementation). +** statements. */ /* TODO(shess) Write version for generic statements and then share ** that between the cached-statement functions. */ static int sql_get_leaf_statement(fulltext_vtab *v, int idx, sqlite3_stmt **ppStmt){ - assert( idx>=-1 && idxdb, v->zDb, v->zName, ppStmt, LEAF_SELECT); - }else if( v->pLeafSelectStmts[idx]==NULL ){ + assert( idx>=0 && idxpLeafSelectStmts[idx]==NULL ){ int rc = sql_prepare(v->db, v->zDb, v->zName, &v->pLeafSelectStmts[idx], LEAF_SELECT); if( rc!=SQLITE_OK ) return rc; @@ -84105,25 +83695,6 @@ static int content_delete(fulltext_vtab *v, sqlite_int64 iDocid){ return sql_single_step(s); } -/* Returns SQLITE_ROW if any rows exist in %_content, SQLITE_DONE if -** no rows exist, and any error in case of failure. -*/ -static int content_exists(fulltext_vtab *v){ - sqlite3_stmt *s; - int rc = sql_get_statement(v, CONTENT_EXISTS_STMT, &s); - if( rc!=SQLITE_OK ) return rc; - - rc = sqlite3_step(s); - if( rc!=SQLITE_ROW ) return rc; - - /* We expect only one row. We must execute another sqlite3_step() - * to complete the iteration; otherwise the table will remain locked. */ - rc = sqlite3_step(s); - if( rc==SQLITE_DONE ) return SQLITE_ROW; - if( rc==SQLITE_ROW ) return SQLITE_ERROR; - return rc; -} - /* insert into %_segments values ([pData]) ** returns assigned blockid in *piBlockid */ @@ -84298,54 +83869,6 @@ static int segdir_delete(fulltext_vtab *v, int iLevel){ return sql_single_step(s); } -/* Delete entire fts index, SQLITE_OK on success, relevant error on -** failure. -*/ -static int segdir_delete_all(fulltext_vtab *v){ - sqlite3_stmt *s; - int rc = sql_get_statement(v, SEGDIR_DELETE_ALL_STMT, &s); - if( rc!=SQLITE_OK ) return rc; - - rc = sql_single_step(s); - if( rc!=SQLITE_OK ) return rc; - - rc = sql_get_statement(v, BLOCK_DELETE_ALL_STMT, &s); - if( rc!=SQLITE_OK ) return rc; - - return sql_single_step(s); -} - -/* Returns SQLITE_OK with *pnSegments set to the number of entries in -** %_segdir and *piMaxLevel set to the highest level which has a -** segment. Otherwise returns the SQLite error which caused failure. -*/ -static int segdir_count(fulltext_vtab *v, int *pnSegments, int *piMaxLevel){ - sqlite3_stmt *s; - int rc = sql_get_statement(v, SEGDIR_COUNT_STMT, &s); - if( rc!=SQLITE_OK ) return rc; - - rc = sqlite3_step(s); - /* TODO(shess): This case should not be possible? Should stronger - ** measures be taken if it happens? - */ - if( rc==SQLITE_DONE ){ - *pnSegments = 0; - *piMaxLevel = 0; - return SQLITE_OK; - } - if( rc!=SQLITE_ROW ) return rc; - - *pnSegments = sqlite3_column_int(s, 0); - *piMaxLevel = sqlite3_column_int(s, 1); - - /* We expect only one row. We must execute another sqlite3_step() - * to complete the iteration; otherwise the table will remain locked. */ - rc = sqlite3_step(s); - if( rc==SQLITE_DONE ) return SQLITE_OK; - if( rc==SQLITE_ROW ) return SQLITE_ERROR; - return rc; -} - /* TODO(shess) clearPendingTerms() is far down the file because ** writeZeroSegment() is far down the file because LeafWriter is far ** down the file. Consider refactoring the code to move the non-vtab @@ -85304,8 +84827,8 @@ static void snippetOffsetText(Snippet *p){ ** it in this case */ zBuf[0] = ' '; - sqlite3_snprintf(sizeof(zBuf)-1, &zBuf[cnt>0], "%d %d %d %d", - pMatch->iCol, pMatch->iTerm, pMatch->iStart, pMatch->nByte); + sprintf(&zBuf[cnt>0], "%d %d %d %d", pMatch->iCol, + pMatch->iTerm, pMatch->iStart, pMatch->nByte); append(&sb, zBuf); cnt++; } @@ -87221,12 +86744,6 @@ static int leavesReaderReset(LeavesReader *pReader){ } static void leavesReaderDestroy(LeavesReader *pReader){ - /* If idx is -1, that means we're using a non-cached statement - ** handle in the optimize() case, so we need to release it. - */ - if( pReader->pStmt!=NULL && pReader->idx==-1 ){ - sqlite3_finalize(pReader->pStmt); - } leafReaderDestroy(&pReader->leafReader); dataBufferDestroy(&pReader->rootData); SCRAMBLE(pReader); @@ -87347,7 +86864,7 @@ static void leavesReaderReorder(LeavesReader *pLr, int nLr){ static int leavesReadersInit(fulltext_vtab *v, int iLevel, LeavesReader *pReaders, int *piReaders){ sqlite3_stmt *s; - int i, rc = sql_get_statement(v, SEGDIR_SELECT_LEVEL_STMT, &s); + int i, rc = sql_get_statement(v, SEGDIR_SELECT_STMT, &s); if( rc!=SQLITE_OK ) return rc; rc = sqlite3_bind_int(s, 1, iLevel); @@ -87885,8 +87402,8 @@ static int termSelect(fulltext_vtab *v, int iColumn, ** elements for given docids overwrite older elements. */ while( (rc = sqlite3_step(s))==SQLITE_ROW ){ - const char *pData = sqlite3_column_blob(s, 2); - const int nData = sqlite3_column_bytes(s, 2); + const char *pData = sqlite3_column_blob(s, 0); + const int nData = sqlite3_column_bytes(s, 0); const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1); rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, isPrefix, &doclist); @@ -88040,23 +87557,6 @@ static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg, if( nArg<2 ){ rc = index_delete(v, sqlite3_value_int64(ppArg[0])); - if( rc==SQLITE_OK ){ - /* If we just deleted the last row in the table, clear out the - ** index data. - */ - rc = content_exists(v); - if( rc==SQLITE_ROW ){ - rc = SQLITE_OK; - }else if( rc==SQLITE_DONE ){ - /* Clear the pending terms so we don't flush a useless level-0 - ** segment when the transaction closes. - */ - rc = clearPendingTerms(v); - if( rc==SQLITE_OK ){ - rc = segdir_delete_all(v); - } - } - } } else if( sqlite3_value_type(ppArg[0]) != SQLITE_NULL ){ /* An update: * ppArg[0] = old rowid @@ -88193,665 +87693,6 @@ static void snippetOffsetsFunc( } } -/* OptLeavesReader is nearly identical to LeavesReader, except that -** where LeavesReader is geared towards the merging of complete -** segment levels (with exactly MERGE_COUNT segments), OptLeavesReader -** is geared towards implementation of the optimize() function, and -** can merge all segments simultaneously. This version may be -** somewhat less efficient than LeavesReader because it merges into an -** accumulator rather than doing an N-way merge, but since segment -** size grows exponentially (so segment count logrithmically) this is -** probably not an immediate problem. -*/ -/* TODO(shess): Prove that assertion, or extend the merge code to -** merge tree fashion (like the prefix-searching code does). -*/ -/* TODO(shess): OptLeavesReader and LeavesReader could probably be -** merged with little or no loss of performance for LeavesReader. The -** merged code would need to handle >MERGE_COUNT segments, and would -** also need to be able to optionally optimize away deletes. -*/ -typedef struct OptLeavesReader { - /* Segment number, to order readers by age. */ - int segment; - LeavesReader reader; -} OptLeavesReader; - -static int optLeavesReaderAtEnd(OptLeavesReader *pReader){ - return leavesReaderAtEnd(&pReader->reader); -} -static int optLeavesReaderTermBytes(OptLeavesReader *pReader){ - return leavesReaderTermBytes(&pReader->reader); -} -static const char *optLeavesReaderData(OptLeavesReader *pReader){ - return leavesReaderData(&pReader->reader); -} -static int optLeavesReaderDataBytes(OptLeavesReader *pReader){ - return leavesReaderDataBytes(&pReader->reader); -} -static const char *optLeavesReaderTerm(OptLeavesReader *pReader){ - return leavesReaderTerm(&pReader->reader); -} -static int optLeavesReaderStep(fulltext_vtab *v, OptLeavesReader *pReader){ - return leavesReaderStep(v, &pReader->reader); -} -static int optLeavesReaderTermCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){ - return leavesReaderTermCmp(&lr1->reader, &lr2->reader); -} -/* Order by term ascending, segment ascending (oldest to newest), with -** exhausted readers to the end. -*/ -static int optLeavesReaderCmp(OptLeavesReader *lr1, OptLeavesReader *lr2){ - int c = optLeavesReaderTermCmp(lr1, lr2); - if( c!=0 ) return c; - return lr1->segment-lr2->segment; -} -/* Bubble pLr[0] to appropriate place in pLr[1..nLr-1]. Assumes that -** pLr[1..nLr-1] is already sorted. -*/ -static void optLeavesReaderReorder(OptLeavesReader *pLr, int nLr){ - while( nLr>1 && optLeavesReaderCmp(pLr, pLr+1)>0 ){ - OptLeavesReader tmp = pLr[0]; - pLr[0] = pLr[1]; - pLr[1] = tmp; - nLr--; - pLr++; - } -} - -/* optimize() helper function. Put the readers in order and iterate -** through them, merging doclists for matching terms into pWriter. -** Returns SQLITE_OK on success, or the SQLite error code which -** prevented success. -*/ -static int optimizeInternal(fulltext_vtab *v, - OptLeavesReader *readers, int nReaders, - LeafWriter *pWriter){ - int i, rc = SQLITE_OK; - DataBuffer doclist, merged, tmp; - - /* Order the readers. */ - i = nReaders; - while( i-- > 0 ){ - optLeavesReaderReorder(&readers[i], nReaders-i); - } - - dataBufferInit(&doclist, LEAF_MAX); - dataBufferInit(&merged, LEAF_MAX); - - /* Exhausted readers bubble to the end, so when the first reader is - ** at eof, all are at eof. - */ - while( !optLeavesReaderAtEnd(&readers[0]) ){ - - /* Figure out how many readers share the next term. */ - for(i=1; i 0 ){ - dlrDestroy(&dlReaders[nReaders]); - } - - /* Accumulated doclist to reader 0 for next pass. */ - dlrInit(&dlReaders[0], DL_DEFAULT, doclist.pData, doclist.nData); - } - - /* Destroy reader that was left in the pipeline. */ - dlrDestroy(&dlReaders[0]); - - /* Trim deletions from the doclist. */ - dataBufferReset(&merged); - docListTrim(DL_DEFAULT, doclist.pData, doclist.nData, - -1, DL_DEFAULT, &merged); - } - - /* Only pass doclists with hits (skip if all hits deleted). */ - if( merged.nData>0 ){ - rc = leafWriterStep(v, pWriter, - optLeavesReaderTerm(&readers[0]), - optLeavesReaderTermBytes(&readers[0]), - merged.pData, merged.nData); - if( rc!=SQLITE_OK ) goto err; - } - - /* Step merged readers to next term and reorder. */ - while( i-- > 0 ){ - rc = optLeavesReaderStep(v, &readers[i]); - if( rc!=SQLITE_OK ) goto err; - - optLeavesReaderReorder(&readers[i], nReaders-i); - } - } - - err: - dataBufferDestroy(&doclist); - dataBufferDestroy(&merged); - return rc; -} - -/* Implement optimize() function for FTS3. optimize(t) merges all -** segments in the fts index into a single segment. 't' is the magic -** table-named column. -*/ -static void optimizeFunc(sqlite3_context *pContext, - int argc, sqlite3_value **argv){ - fulltext_cursor *pCursor; - if( argc>1 ){ - sqlite3_result_error(pContext, "excess arguments to optimize()",-1); - }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || - sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ - sqlite3_result_error(pContext, "illegal first argument to optimize",-1); - }else{ - fulltext_vtab *v; - int i, rc, iMaxLevel; - OptLeavesReader *readers; - int nReaders; - LeafWriter writer; - sqlite3_stmt *s; - - memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); - v = cursor_vtab(pCursor); - - /* Flush any buffered updates before optimizing. */ - rc = flushPendingTerms(v); - if( rc!=SQLITE_OK ) goto err; - - rc = segdir_count(v, &nReaders, &iMaxLevel); - if( rc!=SQLITE_OK ) goto err; - if( nReaders==0 || nReaders==1 ){ - sqlite3_result_text(pContext, "Index already optimal", -1, - SQLITE_STATIC); - return; - } - - rc = sql_get_statement(v, SEGDIR_SELECT_ALL_STMT, &s); - if( rc!=SQLITE_OK ) goto err; - - readers = sqlite3_malloc(nReaders*sizeof(readers[0])); - if( readers==NULL ) goto err; - - /* Note that there will already be a segment at this position - ** until we call segdir_delete() on iMaxLevel. - */ - leafWriterInit(iMaxLevel, 0, &writer); - - i = 0; - while( (rc = sqlite3_step(s))==SQLITE_ROW ){ - sqlite_int64 iStart = sqlite3_column_int64(s, 0); - sqlite_int64 iEnd = sqlite3_column_int64(s, 1); - const char *pRootData = sqlite3_column_blob(s, 2); - int nRootData = sqlite3_column_bytes(s, 2); - - assert( i 0 ){ - leavesReaderDestroy(&readers[i].reader); - } - sqlite3_free(readers); - - /* If we've successfully gotten to here, delete the old segments - ** and flush the interior structure of the new segment. - */ - if( rc==SQLITE_OK ){ - for( i=0; i<=iMaxLevel; i++ ){ - rc = segdir_delete(v, i); - if( rc!=SQLITE_OK ) break; - } - - if( rc==SQLITE_OK ) rc = leafWriterFinalize(v, &writer); - } - - leafWriterDestroy(&writer); - - if( rc!=SQLITE_OK ) goto err; - - sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC); - return; - - /* TODO(shess): Error-handling needs to be improved along the - ** lines of the dump_ functions. - */ - err: - { - char buf[512]; - sqlite3_snprintf(sizeof(buf), buf, "Error in optimize: %s", - sqlite3_errmsg(sqlite3_context_db_handle(pContext))); - sqlite3_result_error(pContext, buf, -1); - } - } -} - -#ifdef SQLITE_TEST -/* Generate an error of the form ": ". If msg is NULL, -** pull the error from the context's db handle. -*/ -static void generateError(sqlite3_context *pContext, - const char *prefix, const char *msg){ - char buf[512]; - if( msg==NULL ) msg = sqlite3_errmsg(sqlite3_context_db_handle(pContext)); - sqlite3_snprintf(sizeof(buf), buf, "%s: %s", prefix, msg); - sqlite3_result_error(pContext, buf, -1); -} - -/* Helper function to collect the set of terms in the segment into -** pTerms. The segment is defined by the leaf nodes between -** iStartBlockid and iEndBlockid, inclusive, or by the contents of -** pRootData if iStartBlockid is 0 (in which case the entire segment -** fit in a leaf). -*/ -static int collectSegmentTerms(fulltext_vtab *v, sqlite3_stmt *s, - fts3Hash *pTerms){ - const sqlite_int64 iStartBlockid = sqlite3_column_int64(s, 0); - const sqlite_int64 iEndBlockid = sqlite3_column_int64(s, 1); - const char *pRootData = sqlite3_column_blob(s, 2); - const int nRootData = sqlite3_column_bytes(s, 2); - LeavesReader reader; - int rc = leavesReaderInit(v, 0, iStartBlockid, iEndBlockid, - pRootData, nRootData, &reader); - if( rc!=SQLITE_OK ) return rc; - - while( rc==SQLITE_OK && !leavesReaderAtEnd(&reader) ){ - const char *pTerm = leavesReaderTerm(&reader); - const int nTerm = leavesReaderTermBytes(&reader); - void *oldValue = sqlite3Fts3HashFind(pTerms, pTerm, nTerm); - void *newValue = (void *)((char *)oldValue+1); - - /* From the comment before sqlite3Fts3HashInsert in fts3_hash.c, - ** the data value passed is returned in case of malloc failure. - */ - if( newValue==sqlite3Fts3HashInsert(pTerms, pTerm, nTerm, newValue) ){ - rc = SQLITE_NOMEM; - }else{ - rc = leavesReaderStep(v, &reader); - } - } - - leavesReaderDestroy(&reader); - return rc; -} - -/* Helper function to build the result string for dump_terms(). */ -static int generateTermsResult(sqlite3_context *pContext, fts3Hash *pTerms){ - int iTerm, nTerms, nResultBytes, iByte; - char *result; - TermData *pData; - fts3HashElem *e; - - /* Iterate pTerms to generate an array of terms in pData for - ** sorting. - */ - nTerms = fts3HashCount(pTerms); - assert( nTerms>0 ); - pData = sqlite3_malloc(nTerms*sizeof(TermData)); - if( pData==NULL ) return SQLITE_NOMEM; - - nResultBytes = 0; - for(iTerm = 0, e = fts3HashFirst(pTerms); e; iTerm++, e = fts3HashNext(e)){ - nResultBytes += fts3HashKeysize(e)+1; /* Term plus trailing space */ - assert( iTerm0 ); /* nTerms>0, nResultsBytes must be, too. */ - result = sqlite3_malloc(nResultBytes); - if( result==NULL ){ - sqlite3_free(pData); - return SQLITE_NOMEM; - } - - if( nTerms>1 ) qsort(pData, nTerms, sizeof(*pData), termDataCmp); - - /* Read the terms in order to build the result. */ - iByte = 0; - for(iTerm=0; iTerm0 ){ - rc = generateTermsResult(pContext, &terms); - if( rc==SQLITE_NOMEM ){ - generateError(pContext, "dump_terms", "out of memory"); - }else{ - assert( rc==SQLITE_OK ); - } - }else if( argc==3 ){ - /* The specific segment asked for could not be found. */ - generateError(pContext, "dump_terms", "segment not found"); - }else{ - /* No segments found. */ - /* TODO(shess): It should be impossible to reach this. This - ** case can only happen for an empty table, in which case - ** SQLite has no rows to call this function on. - */ - sqlite3_result_null(pContext); - } - } - sqlite3Fts3HashClear(&terms); - } -} - -/* Expand the DL_DEFAULT doclist in pData into a text result in -** pContext. -*/ -static void createDoclistResult(sqlite3_context *pContext, - const char *pData, int nData){ - DataBuffer dump; - DLReader dlReader; - - assert( pData!=NULL && nData>0 ); - - dataBufferInit(&dump, 0); - dlrInit(&dlReader, DL_DEFAULT, pData, nData); - for( ; !dlrAtEnd(&dlReader); dlrStep(&dlReader) ){ - char buf[256]; - PLReader plReader; - - plrInit(&plReader, &dlReader); - if( DL_DEFAULT==DL_DOCIDS || plrAtEnd(&plReader) ){ - sqlite3_snprintf(sizeof(buf), buf, "[%lld] ", dlrDocid(&dlReader)); - dataBufferAppend(&dump, buf, strlen(buf)); - }else{ - int iColumn = plrColumn(&plReader); - - sqlite3_snprintf(sizeof(buf), buf, "[%lld %d[", - dlrDocid(&dlReader), iColumn); - dataBufferAppend(&dump, buf, strlen(buf)); - - for( ; !plrAtEnd(&plReader); plrStep(&plReader) ){ - if( plrColumn(&plReader)!=iColumn ){ - iColumn = plrColumn(&plReader); - sqlite3_snprintf(sizeof(buf), buf, "] %d[", iColumn); - assert( dump.nData>0 ); - dump.nData--; /* Overwrite trailing space. */ - assert( dump.pData[dump.nData]==' '); - dataBufferAppend(&dump, buf, strlen(buf)); - } - if( DL_DEFAULT==DL_POSITIONS_OFFSETS ){ - sqlite3_snprintf(sizeof(buf), buf, "%d,%d,%d ", - plrPosition(&plReader), - plrStartOffset(&plReader), plrEndOffset(&plReader)); - }else if( DL_DEFAULT==DL_POSITIONS ){ - sqlite3_snprintf(sizeof(buf), buf, "%d ", plrPosition(&plReader)); - }else{ - assert( NULL=="Unhandled DL_DEFAULT value"); - } - dataBufferAppend(&dump, buf, strlen(buf)); - } - plrDestroy(&plReader); - - assert( dump.nData>0 ); - dump.nData--; /* Overwrite trailing space. */ - assert( dump.pData[dump.nData]==' '); - dataBufferAppend(&dump, "]] ", 3); - } - } - dlrDestroy(&dlReader); - - assert( dump.nData>0 ); - dump.nData--; /* Overwrite trailing space. */ - assert( dump.pData[dump.nData]==' '); - dump.pData[dump.nData] = '\0'; - assert( dump.nData>0 ); - - /* Passes ownership of dump's buffer to pContext. */ - sqlite3_result_text(pContext, dump.pData, dump.nData, sqlite3_free); - dump.pData = NULL; - dump.nData = dump.nCapacity = 0; -} - -/* Implements dump_doclist() for use in inspecting the fts3 index from -** tests. TEXT result containing a string representation of the -** doclist for the indicated term. dump_doclist(t, term, level, idx) -** dumps the doclist for term from the segment specified by level, idx -** (in %_segdir), while dump_doclist(t, term) dumps the logical -** doclist for the term across all segments. The per-segment doclist -** can contain deletions, while the full-index doclist will not -** (deletions are omitted). -** -** Result formats differ with the setting of DL_DEFAULTS. Examples: -** -** DL_DOCIDS: [1] [3] [7] -** DL_POSITIONS: [1 0[0 4] 1[17]] [3 1[5]] -** DL_POSITIONS_OFFSETS: [1 0[0,0,3 4,23,26] 1[17,102,105]] [3 1[5,20,23]] -** -** In each case the number after the outer '[' is the docid. In the -** latter two cases, the number before the inner '[' is the column -** associated with the values within. For DL_POSITIONS the numbers -** within are the positions, for DL_POSITIONS_OFFSETS they are the -** position, the start offset, and the end offset. -*/ -static void dumpDoclistFunc( - sqlite3_context *pContext, - int argc, sqlite3_value **argv -){ - fulltext_cursor *pCursor; - if( argc!=2 && argc!=4 ){ - generateError(pContext, "dump_doclist", "incorrect arguments"); - }else if( sqlite3_value_type(argv[0])!=SQLITE_BLOB || - sqlite3_value_bytes(argv[0])!=sizeof(pCursor) ){ - generateError(pContext, "dump_doclist", "illegal first argument"); - }else if( sqlite3_value_text(argv[1])==NULL || - sqlite3_value_text(argv[1])[0]=='\0' ){ - generateError(pContext, "dump_doclist", "empty second argument"); - }else{ - const char *pTerm = (const char *)sqlite3_value_text(argv[1]); - const int nTerm = strlen(pTerm); - fulltext_vtab *v; - int rc; - DataBuffer doclist; - - memcpy(&pCursor, sqlite3_value_blob(argv[0]), sizeof(pCursor)); - v = cursor_vtab(pCursor); - - dataBufferInit(&doclist, 0); - - /* termSelect() yields the same logical doclist that queries are - ** run against. - */ - if( argc==2 ){ - rc = termSelect(v, v->nColumn, pTerm, nTerm, 0, DL_DEFAULT, &doclist); - }else{ - sqlite3_stmt *s = NULL; - - /* Get our specific segment's information. */ - rc = sql_get_statement(v, SEGDIR_SELECT_SEGMENT_STMT, &s); - if( rc==SQLITE_OK ){ - rc = sqlite3_bind_int(s, 1, sqlite3_value_int(argv[2])); - if( rc==SQLITE_OK ){ - rc = sqlite3_bind_int(s, 2, sqlite3_value_int(argv[3])); - } - } - - if( rc==SQLITE_OK ){ - rc = sqlite3_step(s); - - if( rc==SQLITE_DONE ){ - dataBufferDestroy(&doclist); - generateError(pContext, "dump_doclist", "segment not found"); - return; - } - - /* Found a segment, load it into doclist. */ - if( rc==SQLITE_ROW ){ - const sqlite_int64 iLeavesEnd = sqlite3_column_int64(s, 1); - const char *pData = sqlite3_column_blob(s, 2); - const int nData = sqlite3_column_bytes(s, 2); - - /* loadSegment() is used by termSelect() to load each - ** segment's data. - */ - rc = loadSegment(v, pData, nData, iLeavesEnd, pTerm, nTerm, 0, - &doclist); - if( rc==SQLITE_OK ){ - rc = sqlite3_step(s); - - /* Should not have more than one matching segment. */ - if( rc!=SQLITE_DONE ){ - sqlite3_reset(s); - dataBufferDestroy(&doclist); - generateError(pContext, "dump_doclist", "invalid segdir"); - return; - } - rc = SQLITE_OK; - } - } - } - - sqlite3_reset(s); - } - - if( rc==SQLITE_OK ){ - if( doclist.nData>0 ){ - createDoclistResult(pContext, doclist.pData, doclist.nData); - }else{ - /* TODO(shess): This can happen if the term is not present, or - ** if all instances of the term have been deleted and this is - ** an all-index dump. It may be interesting to distinguish - ** these cases. - */ - sqlite3_result_text(pContext, "", 0, SQLITE_STATIC); - } - }else if( rc==SQLITE_NOMEM ){ - /* Handle out-of-memory cases specially because if they are - ** generated in fts3 code they may not be reflected in the db - ** handle. - */ - /* TODO(shess): Handle this more comprehensively. - ** sqlite3ErrStr() has what I need, but is internal. - */ - generateError(pContext, "dump_doclist", "out of memory"); - }else{ - generateError(pContext, "dump_doclist", NULL); - } - - dataBufferDestroy(&doclist); - } -} -#endif - /* ** This routine implements the xFindFunction method for the FTS3 ** virtual table. @@ -88869,23 +87710,6 @@ static int fulltextFindFunction( }else if( strcmp(zName,"offsets")==0 ){ *pxFunc = snippetOffsetsFunc; return 1; - }else if( strcmp(zName,"optimize")==0 ){ - *pxFunc = optimizeFunc; - return 1; -#ifdef SQLITE_TEST - /* NOTE(shess): These functions are present only for testing - ** purposes. No particular effort is made to optimize their - ** execution or how they build their results. - */ - }else if( strcmp(zName,"dump_terms")==0 ){ - /* fprintf(stderr, "Found dump_terms\n"); */ - *pxFunc = dumpTermsFunc; - return 1; - }else if( strcmp(zName,"dump_doclist")==0 ){ - /* fprintf(stderr, "Found dump_doclist\n"); */ - *pxFunc = dumpDoclistFunc; - return 1; -#endif } return 0; } @@ -88954,11 +87778,11 @@ static void hashDestroy(void *p){ ** Function ...PorterTokenizerModule() sets *pModule to point to the ** porter tokenizer/stemmer implementation. */ -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); -SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); -SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); -SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *); +int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *); /* ** Initialise the fts3 extension. If this extension is built as part @@ -88966,7 +87790,7 @@ SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *) ** SQLite. If fts3 is built as a dynamically loadable extension, this ** function is called by the sqlite3_extension_init() entry point. */ -SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ +int sqlite3Fts3Init(sqlite3 *db){ int rc = SQLITE_OK; fts3Hash *pHash = 0; const sqlite3_tokenizer_module *pSimple = 0; @@ -89005,11 +87829,6 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer")) && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1)) && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", -1)) -#ifdef SQLITE_TEST - && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_terms", -1)) - && SQLITE_OK==(rc = sqlite3_overload_function(db, "dump_doclist", -1)) -#endif ){ return sqlite3_create_module_v2( db, "fts3", &fts3Module, (void *)pHash, hashDestroy @@ -89026,7 +87845,7 @@ SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ } #if !SQLITE_CORE -SQLITE_API int sqlite3_extension_init( +int sqlite3_extension_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi @@ -89068,6 +87887,3965 @@ SQLITE_API int sqlite3_extension_init( #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) +/************** Include sqlite3.h in the middle of fts3_hash.c ***************/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection {F12010} +** +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. +** +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} +** +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. +** +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. +** +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. +** +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK +** +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. +** +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} +** +** See also: [SQLITE_IOERR_READ | extended result codes] +** +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 + +/* +** CAPI3REF: Device Characteristics {F10240} +** +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} +** +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} +** +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} +** +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the +** these integer values as the second argument. +** +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means +** to use Mac OS-X style fullsync instead of fsync(). +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + + +/* +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object {F11120} +** +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** +** The integer values to xLock() and xUnlock() are one of +**
        +**
      • [SQLITE_LOCK_NONE], +**
      • [SQLITE_LOCK_SHARED], +**
      • [SQLITE_LOCK_RESERVED], +**
      • [SQLITE_LOCK_PENDING], or +**
      • [SQLITE_LOCK_EXCLUSIVE]. +**
      +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 + +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +** +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +**
      +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in fts3_hash.c ******************/ +/************** Include fts3_hash.h in the middle of fts3_hash.c *************/ +/************** Begin file fts3_hash.h ***************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implemenation +** used in SQLite. We've modified it slightly to serve as a standalone +** hash table implementation for the full-text indexing module. +** +*/ +#ifndef _FTS3_HASH_H_ +#define _FTS3_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct fts3Hash fts3Hash; +typedef struct fts3HashElem fts3HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, many of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +*/ +struct fts3Hash { + char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ + char copyKey; /* True if copy of key made on insert */ + int count; /* Number of entries in this table */ + fts3HashElem *first; /* The first element of the array */ + int htsize; /* Number of buckets in the hash table */ + struct _fts3ht { /* the hash table */ + int count; /* Number of entries with this hash */ + fts3HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct fts3HashElem { + fts3HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + void *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** There are 2 different modes of operation for a hash table: +** +** FTS3_HASH_STRING pKey points to a string that is nKey bytes long +** (including the null-terminator, if any). Case +** is respected in comparisons. +** +** FTS3_HASH_BINARY pKey points to binary data nKey bytes long. +** memcmp() is used to compare keys. +** +** A copy of the key is made if the copyKey parameter to fts3HashInit is 1. +*/ +#define FTS3_HASH_STRING 1 +#define FTS3_HASH_BINARY 2 + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey); +void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData); +void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey); +void sqlite3Fts3HashClear(fts3Hash*); + +/* +** Shorthand for the functions above +*/ +#define fts3HashInit sqlite3Fts3HashInit +#define fts3HashInsert sqlite3Fts3HashInsert +#define fts3HashFind sqlite3Fts3HashFind +#define fts3HashClear sqlite3Fts3HashClear + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** fts3Hash h; +** fts3HashElem *p; +** ... +** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){ +** SomeStructure *pData = fts3HashData(p); +** // do something with pData +** } +*/ +#define fts3HashFirst(H) ((H)->first) +#define fts3HashNext(E) ((E)->next) +#define fts3HashData(E) ((E)->data) +#define fts3HashKey(E) ((E)->pKey) +#define fts3HashKeysize(E) ((E)->nKey) + +/* +** Number of entries in a hash table +*/ +#define fts3HashCount(H) ((H)->count) + +#endif /* _FTS3_HASH_H_ */ + +/************** End of fts3_hash.h *******************************************/ +/************** Continuing where we left off in fts3_hash.c ******************/ /* ** Malloc and Free functions @@ -89093,7 +91871,7 @@ static void fts3HashFree(void *p){ ** true if the hash table should make its own private copy of keys and ** false if it should just use the supplied pointer. */ -SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){ +void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){ assert( pNew!=0 ); assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); pNew->keyClass = keyClass; @@ -89108,7 +91886,7 @@ SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKe ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ -SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){ +void sqlite3Fts3HashClear(fts3Hash *pH){ fts3HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); @@ -89317,7 +92095,7 @@ static void fts3RemoveElementByHash( ** that matches pKey,nKey. Return the data for this element if it is ** found, or NULL if there is no match. */ -SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){ +void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){ int h; /* A hash on key */ fts3HashElem *elem; /* The element that matches key */ int (*xHash)(const void*,int); /* The hash function */ @@ -89346,7 +92124,7 @@ SQLITE_PRIVATE void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, i ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ -SQLITE_PRIVATE void *sqlite3Fts3HashInsert( +void *sqlite3Fts3HashInsert( fts3Hash *pH, /* The hash table to insert into */ const void *pKey, /* The key */ int nKey, /* Number of bytes in the key */ @@ -89440,6 +92218,3999 @@ SQLITE_PRIVATE void *sqlite3Fts3HashInsert( +/************** Include fts3_tokenizer.h in the middle of fts3_porter.c ******/ +/************** Begin file fts3_tokenizer.h **********************************/ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS3_TOKENIZER_H_ +#define _FTS3_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +/************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection {F12010} +** +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. +** +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} +** +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. +** +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. +** +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. +** +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK +** +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. +** +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} +** +** See also: [SQLITE_IOERR_READ | extended result codes] +** +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 + +/* +** CAPI3REF: Device Characteristics {F10240} +** +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} +** +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} +** +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} +** +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the +** these integer values as the second argument. +** +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means +** to use Mac OS-X style fullsync instead of fsync(). +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + + +/* +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object {F11120} +** +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** +** The integer values to xLock() and xUnlock() are one of +**
        +**
      • [SQLITE_LOCK_NONE], +**
      • [SQLITE_LOCK_SHARED], +**
      • [SQLITE_LOCK_RESERVED], +**
      • [SQLITE_LOCK_PENDING], or +**
      • [SQLITE_LOCK_EXCLUSIVE]. +**
      +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 + +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +** +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +**
      +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in fts3_tokenizer.h *************/ + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts3 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts3 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts3 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialised by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts3 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts3 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +#endif /* _FTS3_TOKENIZER_H_ */ + +/************** End of fts3_tokenizer.h **************************************/ +/************** Continuing where we left off in fts3_porter.c ****************/ /* ** Class derived from sqlite3_tokenizer @@ -90041,7 +96812,7 @@ static const sqlite3_tokenizer_module porterTokenizerModule = { ** Allocate a new porter tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ -SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( +void sqlite3Fts3PorterTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &porterTokenizerModule; @@ -90078,11 +96849,8315 @@ SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -#ifndef SQLITE_CORE - SQLITE_EXTENSION_INIT1 +/************** Include sqlite3ext.h in the middle of fts3_tokenizer.c *******/ +/************** Begin file sqlite3ext.h **************************************/ +/* +** 2006 June 7 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the SQLite interface for use by +** shared libraries that want to be imported as extensions into +** an SQLite instance. Shared libraries that intend to be loaded +** as extensions by SQLite should #include this file instead of +** sqlite3.h. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3EXT_H_ +#define _SQLITE3EXT_H_ +/************** Include sqlite3.h in the middle of sqlite3ext.h **************/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { #endif +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection {F12010} +** +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. +** +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} +** +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. +** +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. +** +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. +** +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK +** +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. +** +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} +** +** See also: [SQLITE_IOERR_READ | extended result codes] +** +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 + +/* +** CAPI3REF: Device Characteristics {F10240} +** +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} +** +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} +** +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} +** +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the +** these integer values as the second argument. +** +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means +** to use Mac OS-X style fullsync instead of fsync(). +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + + +/* +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object {F11120} +** +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** +** The integer values to xLock() and xUnlock() are one of +**
        +**
      • [SQLITE_LOCK_NONE], +**
      • [SQLITE_LOCK_SHARED], +**
      • [SQLITE_LOCK_RESERVED], +**
      • [SQLITE_LOCK_PENDING], or +**
      • [SQLITE_LOCK_EXCLUSIVE]. +**
      +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 + +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +** +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +**
      +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in sqlite3ext.h *****************/ + +typedef struct sqlite3_api_routines sqlite3_api_routines; + +/* +** The following structure hold pointers to all of the SQLite API +** routines. +** +** WARNING: In order to maintain backwards compatibility, add new +** interfaces to the end of this structure only. If you insert new +** interfaces in the middle of this structure, then older different +** versions of SQLite will not be able to load each others shared +** libraries! +*/ +struct sqlite3_api_routines { + void * (*aggregate_context)(sqlite3_context*,int nBytes); + int (*aggregate_count)(sqlite3_context*); + int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*)); + int (*bind_double)(sqlite3_stmt*,int,double); + int (*bind_int)(sqlite3_stmt*,int,int); + int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64); + int (*bind_null)(sqlite3_stmt*,int); + int (*bind_parameter_count)(sqlite3_stmt*); + int (*bind_parameter_index)(sqlite3_stmt*,const char*zName); + const char * (*bind_parameter_name)(sqlite3_stmt*,int); + int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*)); + int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*)); + int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*); + int (*busy_handler)(sqlite3*,int(*)(void*,int),void*); + int (*busy_timeout)(sqlite3*,int ms); + int (*changes)(sqlite3*); + int (*close)(sqlite3*); + int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*)); + int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*)); + const void * (*column_blob)(sqlite3_stmt*,int iCol); + int (*column_bytes)(sqlite3_stmt*,int iCol); + int (*column_bytes16)(sqlite3_stmt*,int iCol); + int (*column_count)(sqlite3_stmt*pStmt); + const char * (*column_database_name)(sqlite3_stmt*,int); + const void * (*column_database_name16)(sqlite3_stmt*,int); + const char * (*column_decltype)(sqlite3_stmt*,int i); + const void * (*column_decltype16)(sqlite3_stmt*,int); + double (*column_double)(sqlite3_stmt*,int iCol); + int (*column_int)(sqlite3_stmt*,int iCol); + sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol); + const char * (*column_name)(sqlite3_stmt*,int); + const void * (*column_name16)(sqlite3_stmt*,int); + const char * (*column_origin_name)(sqlite3_stmt*,int); + const void * (*column_origin_name16)(sqlite3_stmt*,int); + const char * (*column_table_name)(sqlite3_stmt*,int); + const void * (*column_table_name16)(sqlite3_stmt*,int); + const unsigned char * (*column_text)(sqlite3_stmt*,int iCol); + const void * (*column_text16)(sqlite3_stmt*,int iCol); + int (*column_type)(sqlite3_stmt*,int iCol); + sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol); + void * (*commit_hook)(sqlite3*,int(*)(void*),void*); + int (*complete)(const char*sql); + int (*complete16)(const void*sql); + int (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*)); + int (*create_collation16)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*)); + int (*create_function)(sqlite3*,const char*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); + int (*create_function16)(sqlite3*,const void*,int,int,void*,void (*xFunc)(sqlite3_context*,int,sqlite3_value**),void (*xStep)(sqlite3_context*,int,sqlite3_value**),void (*xFinal)(sqlite3_context*)); + int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*); + int (*data_count)(sqlite3_stmt*pStmt); + sqlite3 * (*db_handle)(sqlite3_stmt*); + int (*declare_vtab)(sqlite3*,const char*); + int (*enable_shared_cache)(int); + int (*errcode)(sqlite3*db); + const char * (*errmsg)(sqlite3*); + const void * (*errmsg16)(sqlite3*); + int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**); + int (*expired)(sqlite3_stmt*); + int (*finalize)(sqlite3_stmt*pStmt); + void (*free)(void*); + void (*free_table)(char**result); + int (*get_autocommit)(sqlite3*); + void * (*get_auxdata)(sqlite3_context*,int); + int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**); + int (*global_recover)(void); + void (*interruptx)(sqlite3*); + sqlite_int64 (*last_insert_rowid)(sqlite3*); + const char * (*libversion)(void); + int (*libversion_number)(void); + void *(*malloc)(int); + char * (*mprintf)(const char*,...); + int (*open)(const char*,sqlite3**); + int (*open16)(const void*,sqlite3**); + int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*); + void (*progress_handler)(sqlite3*,int,int(*)(void*),void*); + void *(*realloc)(void*,int); + int (*reset)(sqlite3_stmt*pStmt); + void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_double)(sqlite3_context*,double); + void (*result_error)(sqlite3_context*,const char*,int); + void (*result_error16)(sqlite3_context*,const void*,int); + void (*result_int)(sqlite3_context*,int); + void (*result_int64)(sqlite3_context*,sqlite_int64); + void (*result_null)(sqlite3_context*); + void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*)); + void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*)); + void (*result_value)(sqlite3_context*,sqlite3_value*); + void * (*rollback_hook)(sqlite3*,void(*)(void*),void*); + int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*); + void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*)); + char * (*snprintf)(int,char*,const char*,...); + int (*step)(sqlite3_stmt*); + int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*); + void (*thread_cleanup)(void); + int (*total_changes)(sqlite3*); + void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*); + int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*); + void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*); + void * (*user_data)(sqlite3_context*); + const void * (*value_blob)(sqlite3_value*); + int (*value_bytes)(sqlite3_value*); + int (*value_bytes16)(sqlite3_value*); + double (*value_double)(sqlite3_value*); + int (*value_int)(sqlite3_value*); + sqlite_int64 (*value_int64)(sqlite3_value*); + int (*value_numeric_type)(sqlite3_value*); + const unsigned char * (*value_text)(sqlite3_value*); + const void * (*value_text16)(sqlite3_value*); + const void * (*value_text16be)(sqlite3_value*); + const void * (*value_text16le)(sqlite3_value*); + int (*value_type)(sqlite3_value*); + char *(*vmprintf)(const char*,va_list); + /* Added ??? */ + int (*overload_function)(sqlite3*, const char *zFuncName, int nArg); + /* Added by 3.3.13 */ + int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**); + int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**); + int (*clear_bindings)(sqlite3_stmt*); + /* Added by 3.4.1 */ + int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *)); + /* Added by 3.5.0 */ + int (*bind_zeroblob)(sqlite3_stmt*,int,int); + int (*blob_bytes)(sqlite3_blob*); + int (*blob_close)(sqlite3_blob*); + int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**); + int (*blob_read)(sqlite3_blob*,void*,int,int); + int (*blob_write)(sqlite3_blob*,const void*,int,int); + int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*)); + int (*file_control)(sqlite3*,const char*,int,void*); + sqlite3_int64 (*memory_highwater)(int); + sqlite3_int64 (*memory_used)(void); + sqlite3_mutex *(*mutex_alloc)(int); + void (*mutex_enter)(sqlite3_mutex*); + void (*mutex_free)(sqlite3_mutex*); + void (*mutex_leave)(sqlite3_mutex*); + int (*mutex_try)(sqlite3_mutex*); + int (*open_v2)(const char*,sqlite3**,int,const char*); + int (*release_memory)(int); + void (*result_error_nomem)(sqlite3_context*); + void (*result_error_toobig)(sqlite3_context*); + int (*sleep)(int); + void (*soft_heap_limit)(int); + sqlite3_vfs *(*vfs_find)(const char*); + int (*vfs_register)(sqlite3_vfs*,int); + int (*vfs_unregister)(sqlite3_vfs*); +}; + +/* +** The following macros redefine the API routines so that they are +** redirected throught the global sqlite3_api structure. +** +** This header file is also used by the loadext.c source file +** (part of the main SQLite library - not an extension) so that +** it can get access to the sqlite3_api_routines structure +** definition. But the main library does not want to redefine +** the API. So the redefinition macros are only valid if the +** SQLITE_CORE macros is undefined. +*/ +#ifndef SQLITE_CORE +#define sqlite3_aggregate_context sqlite3_api->aggregate_context +#define sqlite3_aggregate_count sqlite3_api->aggregate_count +#define sqlite3_bind_blob sqlite3_api->bind_blob +#define sqlite3_bind_double sqlite3_api->bind_double +#define sqlite3_bind_int sqlite3_api->bind_int +#define sqlite3_bind_int64 sqlite3_api->bind_int64 +#define sqlite3_bind_null sqlite3_api->bind_null +#define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count +#define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index +#define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name +#define sqlite3_bind_text sqlite3_api->bind_text +#define sqlite3_bind_text16 sqlite3_api->bind_text16 +#define sqlite3_bind_value sqlite3_api->bind_value +#define sqlite3_busy_handler sqlite3_api->busy_handler +#define sqlite3_busy_timeout sqlite3_api->busy_timeout +#define sqlite3_changes sqlite3_api->changes +#define sqlite3_close sqlite3_api->close +#define sqlite3_collation_needed sqlite3_api->collation_needed +#define sqlite3_collation_needed16 sqlite3_api->collation_needed16 +#define sqlite3_column_blob sqlite3_api->column_blob +#define sqlite3_column_bytes sqlite3_api->column_bytes +#define sqlite3_column_bytes16 sqlite3_api->column_bytes16 +#define sqlite3_column_count sqlite3_api->column_count +#define sqlite3_column_database_name sqlite3_api->column_database_name +#define sqlite3_column_database_name16 sqlite3_api->column_database_name16 +#define sqlite3_column_decltype sqlite3_api->column_decltype +#define sqlite3_column_decltype16 sqlite3_api->column_decltype16 +#define sqlite3_column_double sqlite3_api->column_double +#define sqlite3_column_int sqlite3_api->column_int +#define sqlite3_column_int64 sqlite3_api->column_int64 +#define sqlite3_column_name sqlite3_api->column_name +#define sqlite3_column_name16 sqlite3_api->column_name16 +#define sqlite3_column_origin_name sqlite3_api->column_origin_name +#define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16 +#define sqlite3_column_table_name sqlite3_api->column_table_name +#define sqlite3_column_table_name16 sqlite3_api->column_table_name16 +#define sqlite3_column_text sqlite3_api->column_text +#define sqlite3_column_text16 sqlite3_api->column_text16 +#define sqlite3_column_type sqlite3_api->column_type +#define sqlite3_column_value sqlite3_api->column_value +#define sqlite3_commit_hook sqlite3_api->commit_hook +#define sqlite3_complete sqlite3_api->complete +#define sqlite3_complete16 sqlite3_api->complete16 +#define sqlite3_create_collation sqlite3_api->create_collation +#define sqlite3_create_collation16 sqlite3_api->create_collation16 +#define sqlite3_create_function sqlite3_api->create_function +#define sqlite3_create_function16 sqlite3_api->create_function16 +#define sqlite3_create_module sqlite3_api->create_module +#define sqlite3_create_module_v2 sqlite3_api->create_module_v2 +#define sqlite3_data_count sqlite3_api->data_count +#define sqlite3_db_handle sqlite3_api->db_handle +#define sqlite3_declare_vtab sqlite3_api->declare_vtab +#define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache +#define sqlite3_errcode sqlite3_api->errcode +#define sqlite3_errmsg sqlite3_api->errmsg +#define sqlite3_errmsg16 sqlite3_api->errmsg16 +#define sqlite3_exec sqlite3_api->exec +#define sqlite3_expired sqlite3_api->expired +#define sqlite3_finalize sqlite3_api->finalize +#define sqlite3_free sqlite3_api->free +#define sqlite3_free_table sqlite3_api->free_table +#define sqlite3_get_autocommit sqlite3_api->get_autocommit +#define sqlite3_get_auxdata sqlite3_api->get_auxdata +#define sqlite3_get_table sqlite3_api->get_table +#define sqlite3_global_recover sqlite3_api->global_recover +#define sqlite3_interrupt sqlite3_api->interruptx +#define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid +#define sqlite3_libversion sqlite3_api->libversion +#define sqlite3_libversion_number sqlite3_api->libversion_number +#define sqlite3_malloc sqlite3_api->malloc +#define sqlite3_mprintf sqlite3_api->mprintf +#define sqlite3_open sqlite3_api->open +#define sqlite3_open16 sqlite3_api->open16 +#define sqlite3_prepare sqlite3_api->prepare +#define sqlite3_prepare16 sqlite3_api->prepare16 +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_profile sqlite3_api->profile +#define sqlite3_progress_handler sqlite3_api->progress_handler +#define sqlite3_realloc sqlite3_api->realloc +#define sqlite3_reset sqlite3_api->reset +#define sqlite3_result_blob sqlite3_api->result_blob +#define sqlite3_result_double sqlite3_api->result_double +#define sqlite3_result_error sqlite3_api->result_error +#define sqlite3_result_error16 sqlite3_api->result_error16 +#define sqlite3_result_int sqlite3_api->result_int +#define sqlite3_result_int64 sqlite3_api->result_int64 +#define sqlite3_result_null sqlite3_api->result_null +#define sqlite3_result_text sqlite3_api->result_text +#define sqlite3_result_text16 sqlite3_api->result_text16 +#define sqlite3_result_text16be sqlite3_api->result_text16be +#define sqlite3_result_text16le sqlite3_api->result_text16le +#define sqlite3_result_value sqlite3_api->result_value +#define sqlite3_rollback_hook sqlite3_api->rollback_hook +#define sqlite3_set_authorizer sqlite3_api->set_authorizer +#define sqlite3_set_auxdata sqlite3_api->set_auxdata +#define sqlite3_snprintf sqlite3_api->snprintf +#define sqlite3_step sqlite3_api->step +#define sqlite3_table_column_metadata sqlite3_api->table_column_metadata +#define sqlite3_thread_cleanup sqlite3_api->thread_cleanup +#define sqlite3_total_changes sqlite3_api->total_changes +#define sqlite3_trace sqlite3_api->trace +#define sqlite3_transfer_bindings sqlite3_api->transfer_bindings +#define sqlite3_update_hook sqlite3_api->update_hook +#define sqlite3_user_data sqlite3_api->user_data +#define sqlite3_value_blob sqlite3_api->value_blob +#define sqlite3_value_bytes sqlite3_api->value_bytes +#define sqlite3_value_bytes16 sqlite3_api->value_bytes16 +#define sqlite3_value_double sqlite3_api->value_double +#define sqlite3_value_int sqlite3_api->value_int +#define sqlite3_value_int64 sqlite3_api->value_int64 +#define sqlite3_value_numeric_type sqlite3_api->value_numeric_type +#define sqlite3_value_text sqlite3_api->value_text +#define sqlite3_value_text16 sqlite3_api->value_text16 +#define sqlite3_value_text16be sqlite3_api->value_text16be +#define sqlite3_value_text16le sqlite3_api->value_text16le +#define sqlite3_value_type sqlite3_api->value_type +#define sqlite3_vmprintf sqlite3_api->vmprintf +#define sqlite3_overload_function sqlite3_api->overload_function +#define sqlite3_prepare_v2 sqlite3_api->prepare_v2 +#define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2 +#define sqlite3_clear_bindings sqlite3_api->clear_bindings +#define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob +#define sqlite3_blob_bytes sqlite3_api->blob_bytes +#define sqlite3_blob_close sqlite3_api->blob_close +#define sqlite3_blob_open sqlite3_api->blob_open +#define sqlite3_blob_read sqlite3_api->blob_read +#define sqlite3_blob_write sqlite3_api->blob_write +#define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2 +#define sqlite3_file_control sqlite3_api->file_control +#define sqlite3_memory_highwater sqlite3_api->memory_highwater +#define sqlite3_memory_used sqlite3_api->memory_used +#define sqlite3_mutex_alloc sqlite3_api->mutex_alloc +#define sqlite3_mutex_enter sqlite3_api->mutex_enter +#define sqlite3_mutex_free sqlite3_api->mutex_free +#define sqlite3_mutex_leave sqlite3_api->mutex_leave +#define sqlite3_mutex_try sqlite3_api->mutex_try +#define sqlite3_open_v2 sqlite3_api->open_v2 +#define sqlite3_release_memory sqlite3_api->release_memory +#define sqlite3_result_error_nomem sqlite3_api->result_error_nomem +#define sqlite3_result_error_toobig sqlite3_api->result_error_toobig +#define sqlite3_sleep sqlite3_api->sleep +#define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit +#define sqlite3_vfs_find sqlite3_api->vfs_find +#define sqlite3_vfs_register sqlite3_api->vfs_register +#define sqlite3_vfs_unregister sqlite3_api->vfs_unregister +#endif /* SQLITE_CORE */ + +#define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api; +#define SQLITE_EXTENSION_INIT2(v) sqlite3_api = v; + +#endif /* _SQLITE3EXT_H_ */ + +/************** End of sqlite3ext.h ******************************************/ +/************** Continuing where we left off in fts3_tokenizer.c *************/ +SQLITE_EXTENSION_INIT1 + +/************** Include fts3_hash.h in the middle of fts3_tokenizer.c ********/ +/************** Begin file fts3_hash.h ***************************************/ +/* +** 2001 September 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This is the header file for the generic hash-table implemenation +** used in SQLite. We've modified it slightly to serve as a standalone +** hash table implementation for the full-text indexing module. +** +*/ +#ifndef _FTS3_HASH_H_ +#define _FTS3_HASH_H_ + +/* Forward declarations of structures. */ +typedef struct fts3Hash fts3Hash; +typedef struct fts3HashElem fts3HashElem; + +/* A complete hash table is an instance of the following structure. +** The internals of this structure are intended to be opaque -- client +** code should not attempt to access or modify the fields of this structure +** directly. Change this structure only by using the routines below. +** However, many of the "procedures" and "functions" for modifying and +** accessing this structure are really macros, so we can't really make +** this structure opaque. +*/ +struct fts3Hash { + char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */ + char copyKey; /* True if copy of key made on insert */ + int count; /* Number of entries in this table */ + fts3HashElem *first; /* The first element of the array */ + int htsize; /* Number of buckets in the hash table */ + struct _fts3ht { /* the hash table */ + int count; /* Number of entries with this hash */ + fts3HashElem *chain; /* Pointer to first entry with this hash */ + } *ht; +}; + +/* Each element in the hash table is an instance of the following +** structure. All elements are stored on a single doubly-linked list. +** +** Again, this structure is intended to be opaque, but it can't really +** be opaque because it is used by macros. +*/ +struct fts3HashElem { + fts3HashElem *next, *prev; /* Next and previous elements in the table */ + void *data; /* Data associated with this element */ + void *pKey; int nKey; /* Key associated with this element */ +}; + +/* +** There are 2 different modes of operation for a hash table: +** +** FTS3_HASH_STRING pKey points to a string that is nKey bytes long +** (including the null-terminator, if any). Case +** is respected in comparisons. +** +** FTS3_HASH_BINARY pKey points to binary data nKey bytes long. +** memcmp() is used to compare keys. +** +** A copy of the key is made if the copyKey parameter to fts3HashInit is 1. +*/ +#define FTS3_HASH_STRING 1 +#define FTS3_HASH_BINARY 2 + +/* +** Access routines. To delete, insert a NULL pointer. +*/ +void sqlite3Fts3HashInit(fts3Hash*, int keytype, int copyKey); +void *sqlite3Fts3HashInsert(fts3Hash*, const void *pKey, int nKey, void *pData); +void *sqlite3Fts3HashFind(const fts3Hash*, const void *pKey, int nKey); +void sqlite3Fts3HashClear(fts3Hash*); + +/* +** Shorthand for the functions above +*/ +#define fts3HashInit sqlite3Fts3HashInit +#define fts3HashInsert sqlite3Fts3HashInsert +#define fts3HashFind sqlite3Fts3HashFind +#define fts3HashClear sqlite3Fts3HashClear + +/* +** Macros for looping over all elements of a hash table. The idiom is +** like this: +** +** fts3Hash h; +** fts3HashElem *p; +** ... +** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){ +** SomeStructure *pData = fts3HashData(p); +** // do something with pData +** } +*/ +#define fts3HashFirst(H) ((H)->first) +#define fts3HashNext(E) ((E)->next) +#define fts3HashData(E) ((E)->data) +#define fts3HashKey(E) ((E)->pKey) +#define fts3HashKeysize(E) ((E)->nKey) + +/* +** Number of entries in a hash table +*/ +#define fts3HashCount(H) ((H)->count) + +#endif /* _FTS3_HASH_H_ */ + +/************** End of fts3_hash.h *******************************************/ +/************** Continuing where we left off in fts3_tokenizer.c *************/ +/************** Include fts3_tokenizer.h in the middle of fts3_tokenizer.c ***/ +/************** Begin file fts3_tokenizer.h **********************************/ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS3_TOKENIZER_H_ +#define _FTS3_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +/************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection {F12010} +** +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. +** +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} +** +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. +** +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. +** +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. +** +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK +** +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. +** +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} +** +** See also: [SQLITE_IOERR_READ | extended result codes] +** +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 + +/* +** CAPI3REF: Device Characteristics {F10240} +** +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} +** +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} +** +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} +** +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the +** these integer values as the second argument. +** +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means +** to use Mac OS-X style fullsync instead of fsync(). +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + + +/* +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object {F11120} +** +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** +** The integer values to xLock() and xUnlock() are one of +**
        +**
      • [SQLITE_LOCK_NONE], +**
      • [SQLITE_LOCK_SHARED], +**
      • [SQLITE_LOCK_RESERVED], +**
      • [SQLITE_LOCK_PENDING], or +**
      • [SQLITE_LOCK_EXCLUSIVE]. +**
      +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 + +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +** +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +**
      +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in fts3_tokenizer.h *************/ + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts3 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts3 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts3 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialised by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts3 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts3 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +#endif /* _FTS3_TOKENIZER_H_ */ + +/************** End of fts3_tokenizer.h **************************************/ +/************** Continuing where we left off in fts3_tokenizer.c *************/ + /* ** Implementation of the SQL scalar function for accessing the underlying ** hash table. This function may be called as follows: @@ -90148,6 +105223,7 @@ static void scalarFunc( #ifdef SQLITE_TEST +#include /* ** Implementation of a special SQL scalar function for testing tokenizers @@ -90311,7 +105387,7 @@ int queryTokenizer( return sqlite3_finalize(pStmt); } -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); /* ** Implementation of the scalar function fts3_tokenizer_internal_test(). @@ -90380,7 +105456,7 @@ static void intTestFunc( ** The third argument to this function, zName, is used as the name ** of both the scalar and, if created, the virtual table. */ -SQLITE_PRIVATE int sqlite3Fts3InitHashTable( +int sqlite3Fts3InitHashTable( sqlite3 *db, fts3Hash *pHash, const char *zName @@ -90447,6 +105523,3999 @@ SQLITE_PRIVATE int sqlite3Fts3InitHashTable( +/************** Include fts3_tokenizer.h in the middle of fts3_tokenizer1.c **/ +/************** Begin file fts3_tokenizer.h **********************************/ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS3_TOKENIZER_H_ +#define _FTS3_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +/************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/ +/************** Begin file sqlite3.h *****************************************/ +/* +** 2001 September 15 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. +** +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ + +/* +** Make sure we can call this stuff from C++. +*/ +#if 0 +extern "C" { +#endif + + +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; +#else + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 +#endif + +/* +** CAPI3REF: Closing A Database Connection {F12010} +** +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. +** +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} +** +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. +** +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. +** +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. +** +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} +*/ +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ +); + +/* +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK +** +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. +** +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} +** +** See also: [SQLITE_IOERR_READ | extended result codes] +** +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} +** +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} +** +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. +*/ +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 + +/* +** CAPI3REF: Device Characteristics {F10240} +** +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} +** +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} +** +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} +** +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the +** these integer values as the second argument. +** +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means +** to use Mac OS-X style fullsync instead of fsync(). +*/ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 + + +/* +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. +*/ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ +}; + +/* +** CAPI3REF: OS Interface File Virtual Methods Object {F11120} +** +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. +** +** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or +** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** +** The integer values to xLock() and xUnlock() are one of +**
        +**
      • [SQLITE_LOCK_NONE], +**
      • [SQLITE_LOCK_SHARED], +**
      • [SQLITE_LOCK_RESERVED], +**
      • [SQLITE_LOCK_PENDING], or +**
      • [SQLITE_LOCK_EXCLUSIVE]. +**
      +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; + +/* +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. +*/ +#define SQLITE_FCNTL_LOCKSTATE 1 + +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; + +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; + +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. +*/ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +** +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +**
      +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in fts3_tokenizer.h *************/ + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts3 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts3 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts3 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialised by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts3 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts3 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +#endif /* _FTS3_TOKENIZER_H_ */ + +/************** End of fts3_tokenizer.h **************************************/ +/************** Continuing where we left off in fts3_tokenizer1.c ************/ typedef struct simple_tokenizer { sqlite3_tokenizer base; @@ -90636,7 +109705,7 @@ static const sqlite3_tokenizer_module simpleTokenizerModule = { ** Allocate a new simple tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ -SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( +void sqlite3Fts3SimpleTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &simpleTokenizerModule; @@ -90645,7 +109714,56 @@ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenizer1.c *************************************/ -/************** Begin file rtree.c *******************************************/ +/************** Begin file fts3_icu.c ****************************************/ +/* +** 2007 June 22 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file implements a tokenizer for fts3 based on the ICU library. +** +** $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ +*/ + +#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) +#ifdef SQLITE_ENABLE_ICU + +/************** Include fts3_tokenizer.h in the middle of fts3_icu.c *********/ +/************** Begin file fts3_tokenizer.h **********************************/ +/* +** 2006 July 10 +** +** The author disclaims copyright to this source code. +** +************************************************************************* +** Defines the interface to tokenizers used by fulltext-search. There +** are three basic components: +** +** sqlite3_tokenizer_module is a singleton defining the tokenizer +** interface functions. This is essentially the class structure for +** tokenizers. +** +** sqlite3_tokenizer is used to define a particular tokenizer, perhaps +** including customization information defined at creation time. +** +** sqlite3_tokenizer_cursor is generated by a tokenizer to generate +** tokens from a particular input. +*/ +#ifndef _FTS3_TOKENIZER_H_ +#define _FTS3_TOKENIZER_H_ + +/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time. +** If tokenizers are to be allowed to call sqlite3_*() functions, then +** we will need a way to register the API consistently. +*/ +/************** Include sqlite3.h in the middle of fts3_tokenizer.h **********/ +/************** Begin file sqlite3.h *****************************************/ /* ** 2001 September 15 ** @@ -90657,2818 +109775,4193 @@ SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( ** May you share freely, never taking more than you give. ** ************************************************************************* -** This file contains code for implementations of the r-tree and r*-tree -** algorithms packaged as an SQLite virtual table module. +** This header file defines the interface that the SQLite library +** presents to client programs. If a C-function, structure, datatype, +** or constant definition does not appear in this file, then it is +** not a published API of SQLite, is subject to change without +** notice, and should not be referenced by programs that use SQLite. ** -** $Id: rtree.c,v 1.7 2008/07/16 14:43:35 drh Exp $ +** Some of the definitions that are in this file are marked as +** "experimental". Experimental interfaces are normally new +** features recently added to SQLite. We do not anticipate changes +** to experimental interfaces but reserve to make minor changes if +** experience from use "in the wild" suggest such changes are prudent. +** +** The official C-language API documentation for SQLite is derived +** from comments in this file. This file is the authoritative source +** on how SQLite interfaces are suppose to operate. +** +** The name of this file under configuration management is "sqlite.h.in". +** The makefile makes some minor changes to this file (such as inserting +** the version number) and changes its name to "sqlite3.h" as +** part of the build process. +** +** @(#) $Id: sqlite3.c,v 1.15 2008/03/20 19:17:10 gavin%gavinsharp.com Exp $ */ - -#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE) +#ifndef _SQLITE3_H_ +#define _SQLITE3_H_ /* -** This file contains an implementation of a couple of different variants -** of the r-tree algorithm. See the README file for further details. The -** same data-structure is used for all, but the algorithms for insert and -** delete operations vary. The variants used are selected at compile time -** by defining the following symbols: +** Make sure we can call this stuff from C++. */ - -/* Either, both or none of the following may be set to activate -** r*tree variant algorithms. -*/ -#define VARIANT_RSTARTREE_CHOOSESUBTREE 0 -#define VARIANT_RSTARTREE_REINSERT 1 - -/* -** Exactly one of the following must be set to 1. -*/ -#define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0 -#define VARIANT_GUTTMAN_LINEAR_SPLIT 0 -#define VARIANT_RSTARTREE_SPLIT 1 - -#define VARIANT_GUTTMAN_SPLIT \ - (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT) - -#if VARIANT_GUTTMAN_QUADRATIC_SPLIT - #define PickNext QuadraticPickNext - #define PickSeeds QuadraticPickSeeds - #define AssignCells splitNodeGuttman -#endif -#if VARIANT_GUTTMAN_LINEAR_SPLIT - #define PickNext LinearPickNext - #define PickSeeds LinearPickSeeds - #define AssignCells splitNodeGuttman -#endif -#if VARIANT_RSTARTREE_SPLIT - #define AssignCells splitNodeStartree +#if 0 +extern "C" { #endif -#ifndef SQLITE_CORE - #include "sqlite3ext.h" - SQLITE_EXTENSION_INIT1 +/* +** Add the ability to override 'extern' +*/ +#ifndef SQLITE_EXTERN +# define SQLITE_EXTERN extern +#endif + +/* +** Make sure these symbols where not defined by some previous header +** file. +*/ +#ifdef SQLITE_VERSION +# undef SQLITE_VERSION +#endif +#ifdef SQLITE_VERSION_NUMBER +# undef SQLITE_VERSION_NUMBER +#endif + +/* +** CAPI3REF: Compile-Time Library Version Numbers {F10010} +** +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". +** +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when +** there are major feature enhancements that are forwards compatible +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). +** +** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. +*/ +#define SQLITE_VERSION "3.5.4" +#define SQLITE_VERSION_NUMBER 3005004 + +/* +** CAPI3REF: Run-Time Library Version Numbers {F10020} +** +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value +** [SQLITE_VERSION_NUMBER]. +** +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not +** constants within the DLL. +*/ +SQLITE_EXTERN const char sqlite3_version[]; +const char *sqlite3_libversion(void); +int sqlite3_libversion_number(void); + +/* +** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} +** +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. +** +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 +** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. +*/ +typedef struct sqlite3 sqlite3; + + +/* +** CAPI3REF: 64-Bit Integer Types {F10200} +** +** Because there is no cross-platform way to specify such types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} +** +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. +*/ +#ifdef SQLITE_INT64_TYPE + typedef SQLITE_INT64_TYPE sqlite_int64; + typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; +#elif defined(_MSC_VER) || defined(__BORLANDC__) + typedef __int64 sqlite_int64; + typedef unsigned __int64 sqlite_uint64; #else - #include "sqlite3.h" + typedef long long int sqlite_int64; + typedef unsigned long long int sqlite_uint64; +#endif +typedef sqlite_int64 sqlite3_int64; +typedef sqlite_uint64 sqlite3_uint64; + +/* +** If compiling for a processor that lacks floating point support, +** substitute integer for floating-point +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# define double sqlite3_int64 #endif - -#ifndef SQLITE_AMALGAMATION -typedef sqlite3_int64 i64; -typedef unsigned char u8; -typedef unsigned int u32; -#endif - -typedef struct Rtree Rtree; -typedef struct RtreeCursor RtreeCursor; -typedef struct RtreeNode RtreeNode; -typedef struct RtreeCell RtreeCell; -typedef struct RtreeConstraint RtreeConstraint; -typedef union RtreeCoord RtreeCoord; - -/* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */ -#define RTREE_MAX_DIMENSIONS 5 - -/* Size of hash table Rtree.aHash. This hash table is not expected to -** ever contain very many entries, so a fixed number of buckets is -** used. -*/ -#define HASHSIZE 128 - -/* -** An rtree virtual-table object. -*/ -struct Rtree { - sqlite3_vtab base; - sqlite3 *db; /* Host database connection */ - int iNodeSize; /* Size in bytes of each node in the node table */ - int nDim; /* Number of dimensions */ - int nBytesPerCell; /* Bytes consumed per cell */ - int iDepth; /* Current depth of the r-tree structure */ - char *zDb; /* Name of database containing r-tree table */ - char *zName; /* Name of r-tree table */ - RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ - int nBusy; /* Current number of users of this structure */ - - /* List of nodes removed during a CondenseTree operation. List is - ** linked together via the pointer normally used for hash chains - - ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree - ** headed by the node (leaf nodes have RtreeNode.iNode==0). - */ - RtreeNode *pDeleted; - int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */ - - /* Statements to read/write/delete a record from xxx_node */ - sqlite3_stmt *pReadNode; - sqlite3_stmt *pWriteNode; - sqlite3_stmt *pDeleteNode; - - /* Statements to read/write/delete a record from xxx_rowid */ - sqlite3_stmt *pReadRowid; - sqlite3_stmt *pWriteRowid; - sqlite3_stmt *pDeleteRowid; - - /* Statements to read/write/delete a record from xxx_parent */ - sqlite3_stmt *pReadParent; - sqlite3_stmt *pWriteParent; - sqlite3_stmt *pDeleteParent; - - int eCoordType; -}; - -/* Possible values for eCoordType: */ -#define RTREE_COORD_REAL32 0 -#define RTREE_COORD_INT32 1 - /* -** The minimum number of cells allowed for a node is a third of the -** maximum. In Gutman's notation: +** CAPI3REF: Closing A Database Connection {F12010} ** -** m = M/3 +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. ** -** If an R*-tree "Reinsert" operation is required, the same number of -** cells are removed from the overfull node and reinserted into the tree. -*/ -#define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3) -#define RTREE_REINSERT(p) RTREE_MINCELLS(p) -#define RTREE_MAXCELLS 51 - -/* -** An rtree cursor object. -*/ -struct RtreeCursor { - sqlite3_vtab_cursor base; - RtreeNode *pNode; /* Node cursor is currently pointing at */ - int iCell; /* Index of current cell in pNode */ - int iStrategy; /* Copy of idxNum search parameter */ - int nConstraint; /* Number of entries in aConstraint */ - RtreeConstraint *aConstraint; /* Search constraints. */ -}; - -union RtreeCoord { - float f; - int i; -}; - -/* -** The argument is an RtreeCoord. Return the value stored within the RtreeCoord -** formatted as a double. This macro assumes that local variable pRtree points -** to the Rtree structure associated with the RtreeCoord. -*/ -#define DCOORD(coord) ( \ - (pRtree->eCoordType==RTREE_COORD_REAL32) ? \ - ((double)coord.f) : \ - ((double)coord.i) \ -) - -/* -** A search constraint. -*/ -struct RtreeConstraint { - int iCoord; /* Index of constrained coordinate */ - int op; /* Constraining operation */ - double rValue; /* Constraint value. */ -}; - -/* Possible values for RtreeConstraint.op */ -#define RTREE_EQ 0x41 -#define RTREE_LE 0x42 -#define RTREE_LT 0x43 -#define RTREE_GE 0x44 -#define RTREE_GT 0x45 - -/* -** An rtree structure node. +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} ** -** Data format (RtreeNode.zData): +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. +*/ +int sqlite3_close(sqlite3 *); + +/* +** The type for a callback function. +** This is legacy and deprecated. It is included for historical +** compatibility and is not documented. +*/ +typedef int (*sqlite3_callback)(void*,int,char**, char**); + +/* +** CAPI3REF: One-Step Query Execution Interface {F12100} ** -** 1. If the node is the root node (node 1), then the first 2 bytes -** of the node contain the tree depth as a big-endian integer. -** For non-root nodes, the first 2 bytes are left unused. +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. ** -** 2. The next 2 bytes contain the number of entries currently -** stored in the node. +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. ** -** 3. The remainder of the node contains the node entries. Each entry -** consists of a single 8-byte integer followed by an even number -** of 4-byte coordinates. For leaf nodes the integer is the rowid -** of a record. For internal nodes it is the node number of a -** child page. -*/ -struct RtreeNode { - RtreeNode *pParent; /* Parent node */ - i64 iNode; - int nRef; - int isDirty; - u8 *zData; - RtreeNode *pNext; /* Next node in this hash chain */ -}; -#define NCELL(pNode) readInt16(&(pNode)->zData[2]) - -/* -** Structure to store a deserialized rtree record. -*/ -struct RtreeCell { - i64 iRowid; - RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; -}; - -#define MAX(x,y) ((x) < (y) ? (y) : (x)) -#define MIN(x,y) ((x) > (y) ? (y) : (x)) - -/* -** Functions to deserialize a 16 bit integer, 32 bit real number and -** 64 bit integer. The deserialized value is returned. -*/ -static int readInt16(u8 *p){ - return (p[0]<<8) + p[1]; -} -static void readCoord(u8 *p, RtreeCoord *pCoord){ - u32 i = ( - (((u32)p[0]) << 24) + - (((u32)p[1]) << 16) + - (((u32)p[2]) << 8) + - (((u32)p[3]) << 0) - ); - *(u32 *)pCoord = i; -} -static i64 readInt64(u8 *p){ - return ( - (((i64)p[0]) << 56) + - (((i64)p[1]) << 48) + - (((i64)p[2]) << 40) + - (((i64)p[3]) << 32) + - (((i64)p[4]) << 24) + - (((i64)p[5]) << 16) + - (((i64)p[6]) << 8) + - (((i64)p[7]) << 0) - ); -} - -/* -** Functions to serialize a 16 bit integer, 32 bit real number and -** 64 bit integer. The value returned is the number of bytes written -** to the argument buffer (always 2, 4 and 8 respectively). -*/ -static int writeInt16(u8 *p, int i){ - p[0] = (i>> 8)&0xFF; - p[1] = (i>> 0)&0xFF; - return 2; -} -static int writeCoord(u8 *p, RtreeCoord *pCoord){ - u32 i; - assert( sizeof(RtreeCoord)==4 ); - assert( sizeof(u32)==4 ); - i = *(u32 *)pCoord; - p[0] = (i>>24)&0xFF; - p[1] = (i>>16)&0xFF; - p[2] = (i>> 8)&0xFF; - p[3] = (i>> 0)&0xFF; - return 4; -} -static int writeInt64(u8 *p, i64 i){ - p[0] = (i>>56)&0xFF; - p[1] = (i>>48)&0xFF; - p[2] = (i>>40)&0xFF; - p[3] = (i>>32)&0xFF; - p[4] = (i>>24)&0xFF; - p[5] = (i>>16)&0xFF; - p[6] = (i>> 8)&0xFF; - p[7] = (i>> 0)&0xFF; - return 8; -} - -/* -** Increment the reference count of node p. -*/ -static void nodeReference(RtreeNode *p){ - if( p ){ - p->nRef++; - } -} - -/* -** Clear the content of node p (set all bytes to 0x00). -*/ -static void nodeZero(Rtree *pRtree, RtreeNode *p){ - if( p ){ - memset(&p->zData[2], 0, pRtree->iNodeSize-2); - p->isDirty = 1; - } -} - -/* -** Given a node number iNode, return the corresponding key to use -** in the Rtree.aHash table. -*/ -static int nodeHash(i64 iNode){ - return ( - (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ - (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0) - ) % HASHSIZE; -} - -/* -** Search the node hash table for node iNode. If found, return a pointer -** to it. Otherwise, return 0. -*/ -static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){ - RtreeNode *p; - assert( iNode!=0 ); - for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext); - return p; -} - -/* -** Add node pNode to the node hash table. -*/ -static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){ - if( pNode ){ - int iHash; - assert( pNode->pNext==0 ); - iHash = nodeHash(pNode->iNode); - pNode->pNext = pRtree->aHash[iHash]; - pRtree->aHash[iHash] = pNode; - } -} - -/* -** Remove node pNode from the node hash table. -*/ -static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){ - RtreeNode **pp; - if( pNode->iNode!=0 ){ - pp = &pRtree->aHash[nodeHash(pNode->iNode)]; - for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); } - *pp = pNode->pNext; - pNode->pNext = 0; - } -} - -/* -** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0), -** indicating that node has not yet been assigned a node number. It is -** assigned a node number when nodeWrite() is called to write the -** node contents out to the database. -*/ -static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){ - RtreeNode *pNode; - pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); - if( pNode ){ - memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0)); - pNode->zData = (u8 *)&pNode[1]; - pNode->nRef = 1; - pNode->pParent = pParent; - pNode->isDirty = 1; - nodeReference(pParent); - } - return pNode; -} - -/* -** Obtain a reference to an r-tree node. -*/ -static int -nodeAcquire( - Rtree *pRtree, /* R-tree structure */ - i64 iNode, /* Node number to load */ - RtreeNode *pParent, /* Either the parent node or NULL */ - RtreeNode **ppNode /* OUT: Acquired node */ -){ - int rc; - RtreeNode *pNode; - - /* Check if the requested node is already in the hash table. If so, - ** increase its reference count and return it. - */ - if( (pNode = nodeHashLookup(pRtree, iNode)) ){ - assert( !pParent || !pNode->pParent || pNode->pParent==pParent ); - if( pParent ){ - pNode->pParent = pParent; - } - pNode->nRef++; - *ppNode = pNode; - return SQLITE_OK; - } - - pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize); - if( !pNode ){ - *ppNode = 0; - return SQLITE_NOMEM; - } - pNode->pParent = pParent; - pNode->zData = (u8 *)&pNode[1]; - pNode->nRef = 1; - pNode->iNode = iNode; - pNode->isDirty = 0; - pNode->pNext = 0; - - sqlite3_bind_int64(pRtree->pReadNode, 1, iNode); - rc = sqlite3_step(pRtree->pReadNode); - if( rc==SQLITE_ROW ){ - const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0); - memcpy(pNode->zData, zBlob, pRtree->iNodeSize); - nodeReference(pParent); - }else{ - sqlite3_free(pNode); - pNode = 0; - } - - *ppNode = pNode; - rc = sqlite3_reset(pRtree->pReadNode); - - if( rc==SQLITE_OK && iNode==1 ){ - pRtree->iDepth = readInt16(pNode->zData); - } - - assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) ); - nodeHashInsert(pRtree, pNode); - - return rc; -} - -/* -** Overwrite cell iCell of node pNode with the contents of pCell. -*/ -static void nodeOverwriteCell( - Rtree *pRtree, - RtreeNode *pNode, - RtreeCell *pCell, - int iCell -){ - int ii; - u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; - p += writeInt64(p, pCell->iRowid); - for(ii=0; ii<(pRtree->nDim*2); ii++){ - p += writeCoord(p, &pCell->aCoord[ii]); - } - pNode->isDirty = 1; -} - -/* -** Remove cell the cell with index iCell from node pNode. -*/ -static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){ - u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell]; - u8 *pSrc = &pDst[pRtree->nBytesPerCell]; - int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell; - memmove(pDst, pSrc, nByte); - writeInt16(&pNode->zData[2], NCELL(pNode)-1); - pNode->isDirty = 1; -} - -/* -** Insert the contents of cell pCell into node pNode. If the insert -** is successful, return SQLITE_OK. +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. ** -** If there is not enough free space in pNode, return SQLITE_FULL. +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. +** +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. +** +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? +** +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} */ -static int -nodeInsertCell( - Rtree *pRtree, - RtreeNode *pNode, - RtreeCell *pCell -){ - int nCell; /* Current number of cells in pNode */ - int nMaxCell; /* Maximum number of cells for pNode */ - - nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell; - nCell = NCELL(pNode); - - assert(nCell<=nMaxCell); - - if( nCellzData[2], nCell+1); - pNode->isDirty = 1; - } - - return (nCell==nMaxCell); -} - -/* -** If the node is dirty, write it out to the database. -*/ -static int -nodeWrite(Rtree *pRtree, RtreeNode *pNode){ - int rc = SQLITE_OK; - if( pNode->isDirty ){ - sqlite3_stmt *p = pRtree->pWriteNode; - if( pNode->iNode ){ - sqlite3_bind_int64(p, 1, pNode->iNode); - }else{ - sqlite3_bind_null(p, 1); - } - sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC); - sqlite3_step(p); - pNode->isDirty = 0; - rc = sqlite3_reset(p); - if( pNode->iNode==0 && rc==SQLITE_OK ){ - pNode->iNode = sqlite3_last_insert_rowid(pRtree->db); - nodeHashInsert(pRtree, pNode); - } - } - return rc; -} - -/* -** Release a reference to a node. If the node is dirty and the reference -** count drops to zero, the node data is written to the database. -*/ -static int -nodeRelease(Rtree *pRtree, RtreeNode *pNode){ - int rc = SQLITE_OK; - if( pNode ){ - assert( pNode->nRef>0 ); - pNode->nRef--; - if( pNode->nRef==0 ){ - if( pNode->iNode==1 ){ - pRtree->iDepth = -1; - } - if( pNode->pParent ){ - rc = nodeRelease(pRtree, pNode->pParent); - } - if( rc==SQLITE_OK ){ - rc = nodeWrite(pRtree, pNode); - } - nodeHashDelete(pRtree, pNode); - sqlite3_free(pNode); - } - } - return rc; -} - -/* -** Return the 64-bit integer value associated with cell iCell of -** node pNode. If pNode is a leaf node, this is a rowid. If it is -** an internal node, then the 64-bit integer is a child page number. -*/ -static i64 nodeGetRowid( - Rtree *pRtree, - RtreeNode *pNode, - int iCell -){ - assert( iCellzData[4 + pRtree->nBytesPerCell*iCell]); -} - -/* -** Return coordinate iCoord from cell iCell in node pNode. -*/ -static void nodeGetCoord( - Rtree *pRtree, - RtreeNode *pNode, - int iCell, - int iCoord, - RtreeCoord *pCoord /* Space to write result to */ -){ - readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord); -} - -/* -** Deserialize cell iCell of node pNode. Populate the structure pointed -** to by pCell with the results. -*/ -static void nodeGetCell( - Rtree *pRtree, - RtreeNode *pNode, - int iCell, - RtreeCell *pCell -){ - int ii; - pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell); - for(ii=0; iinDim*2; ii++){ - nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]); - } -} - - -/* Forward declaration for the function that does the work of -** the virtual table module xCreate() and xConnect() methods. -*/ -static int rtreeInit( - sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int, int +int sqlite3_exec( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluted */ + int (*callback)(void*,int,char**,char**), /* Callback function */ + void *, /* 1st argument to callback */ + char **errmsg /* Error msg written here */ ); -/* -** Rtree virtual table module xCreate method. -*/ -static int rtreeCreate( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1, (int)pAux); -} - -/* -** Rtree virtual table module xConnect method. -*/ -static int rtreeConnect( - sqlite3 *db, - void *pAux, - int argc, const char *const*argv, - sqlite3_vtab **ppVtab, - char **pzErr -){ - return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0, (int)pAux); -} - /* -** Increment the r-tree reference count. -*/ -static void rtreeReference(Rtree *pRtree){ - pRtree->nBusy++; -} - -/* -** Decrement the r-tree reference count. When the reference count reaches -** zero the structure is deleted. -*/ -static void rtreeRelease(Rtree *pRtree){ - pRtree->nBusy--; - if( pRtree->nBusy==0 ){ - sqlite3_finalize(pRtree->pReadNode); - sqlite3_finalize(pRtree->pWriteNode); - sqlite3_finalize(pRtree->pDeleteNode); - sqlite3_finalize(pRtree->pReadRowid); - sqlite3_finalize(pRtree->pWriteRowid); - sqlite3_finalize(pRtree->pDeleteRowid); - sqlite3_finalize(pRtree->pReadParent); - sqlite3_finalize(pRtree->pWriteParent); - sqlite3_finalize(pRtree->pDeleteParent); - sqlite3_free(pRtree); - } -} - -/* -** Rtree virtual table module xDisconnect method. -*/ -static int rtreeDisconnect(sqlite3_vtab *pVtab){ - rtreeRelease((Rtree *)pVtab); - return SQLITE_OK; -} - -/* -** Rtree virtual table module xDestroy method. -*/ -static int rtreeDestroy(sqlite3_vtab *pVtab){ - Rtree *pRtree = (Rtree *)pVtab; - int rc; - char *zCreate = sqlite3_mprintf( - "DROP TABLE '%q'.'%q_node';" - "DROP TABLE '%q'.'%q_rowid';" - "DROP TABLE '%q'.'%q_parent';", - pRtree->zDb, pRtree->zName, - pRtree->zDb, pRtree->zName, - pRtree->zDb, pRtree->zName - ); - if( !zCreate ){ - rc = SQLITE_NOMEM; - }else{ - rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0); - sqlite3_free(zCreate); - } - if( rc==SQLITE_OK ){ - rtreeRelease(pRtree); - } - - return rc; -} - -/* -** Rtree virtual table module xOpen method. -*/ -static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){ - int rc = SQLITE_NOMEM; - RtreeCursor *pCsr; - - pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor)); - if( pCsr ){ - memset(pCsr, 0, sizeof(RtreeCursor)); - pCsr->base.pVtab = pVTab; - rc = SQLITE_OK; - } - *ppCursor = (sqlite3_vtab_cursor *)pCsr; - - return rc; -} - -/* -** Rtree virtual table module xClose method. -*/ -static int rtreeClose(sqlite3_vtab_cursor *cur){ - Rtree *pRtree = (Rtree *)(cur->pVtab); - int rc; - RtreeCursor *pCsr = (RtreeCursor *)cur; - sqlite3_free(pCsr->aConstraint); - rc = nodeRelease(pRtree, pCsr->pNode); - sqlite3_free(pCsr); - return rc; -} - -/* -** Rtree virtual table module xEof method. +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK ** -** Return non-zero if the cursor does not currently point to a valid -** record (i.e if the scan has finished), or zero otherwise. -*/ -static int rtreeEof(sqlite3_vtab_cursor *cur){ - RtreeCursor *pCsr = (RtreeCursor *)cur; - return (pCsr->pNode==0); -} - -/* -** Cursor pCursor currently points to a cell in a non-leaf page. -** Return true if the sub-tree headed by the cell is filtered -** (excluded) by the constraints in the pCursor->aConstraint[] -** array, or false otherwise. -*/ -static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){ - RtreeCell cell; - int ii; - int bRes = 0; - - nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); - for(ii=0; bRes==0 && iinConstraint; ii++){ - RtreeConstraint *p = &pCursor->aConstraint[ii]; - double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]); - double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]); - - assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE - || p->op==RTREE_GT || p->op==RTREE_EQ - ); - - switch( p->op ){ - case RTREE_LE: case RTREE_LT: bRes = p->rValuerValue>cell_max; break; - case RTREE_EQ: - bRes = (p->rValue>cell_max || p->rValueaConstraint[] array, or false otherwise. +** Many SQLite functions return an integer result code from the set shown +** above in order to indicates success or failure. ** -** This function assumes that the cell is part of a leaf node. -*/ -static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){ - RtreeCell cell; - int ii; - - nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell); - for(ii=0; iinConstraint; ii++){ - RtreeConstraint *p = &pCursor->aConstraint[ii]; - double coord = DCOORD(cell.aCoord[p->iCoord]); - int res; - assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE - || p->op==RTREE_GT || p->op==RTREE_EQ - ); - switch( p->op ){ - case RTREE_LE: res = (coord<=p->rValue); break; - case RTREE_LT: res = (coordrValue); break; - case RTREE_GE: res = (coord>=p->rValue); break; - case RTREE_GT: res = (coord>p->rValue); break; - case RTREE_EQ: res = (coord==p->rValue); break; - } - - if( !res ) return 1; - } - - return 0; -} - -/* -** Cursor pCursor currently points at a node that heads a sub-tree of -** height iHeight (if iHeight==0, then the node is a leaf). Descend -** to point to the left-most cell of the sub-tree that matches the -** configured constraints. -*/ -static int descendToCell( - Rtree *pRtree, - RtreeCursor *pCursor, - int iHeight, - int *pEof /* OUT: Set to true if cannot descend */ -){ - int isEof; - int rc; - int ii; - RtreeNode *pChild; - sqlite3_int64 iRowid; - - RtreeNode *pSavedNode = pCursor->pNode; - int iSavedCell = pCursor->iCell; - - assert( iHeight>=0 ); - - if( iHeight==0 ){ - isEof = testRtreeEntry(pRtree, pCursor); - }else{ - isEof = testRtreeCell(pRtree, pCursor); - } - if( isEof || iHeight==0 ){ - *pEof = isEof; - return SQLITE_OK; - } - - iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell); - rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild); - if( rc!=SQLITE_OK ){ - return rc; - } - - nodeRelease(pRtree, pCursor->pNode); - pCursor->pNode = pChild; - isEof = 1; - for(ii=0; isEof && iiiCell = ii; - rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof); - if( rc!=SQLITE_OK ){ - return rc; - } - } - - if( isEof ){ - assert( pCursor->pNode==pChild ); - nodeReference(pSavedNode); - nodeRelease(pRtree, pChild); - pCursor->pNode = pSavedNode; - pCursor->iCell = iSavedCell; - } - - *pEof = isEof; - return SQLITE_OK; -} - -/* -** One of the cells in node pNode is guaranteed to have a 64-bit -** integer value equal to iRowid. Return the index of this cell. -*/ -static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){ - int ii; - for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){ - assert( ii<(NCELL(pNode)-1) ); - } - return ii; -} - -/* -** Return the index of the cell containing a pointer to node pNode -** in its parent. If pNode is the root node, return -1. -*/ -static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){ - RtreeNode *pParent = pNode->pParent; - if( pParent ){ - return nodeRowidIndex(pRtree, pParent, pNode->iNode); - } - return -1; -} - -/* -** Rtree virtual table module xNext method. -*/ -static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){ - Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab); - RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; - int rc = SQLITE_OK; - - if( pCsr->iStrategy==1 ){ - /* This "scan" is a direct lookup by rowid. There is no next entry. */ - nodeRelease(pRtree, pCsr->pNode); - pCsr->pNode = 0; - } - - else if( pCsr->pNode ){ - /* Move to the next entry that matches the configured constraints. */ - int iHeight = 0; - while( pCsr->pNode ){ - RtreeNode *pNode = pCsr->pNode; - int nCell = NCELL(pNode); - for(pCsr->iCell++; pCsr->iCelliCell++){ - int isEof; - rc = descendToCell(pRtree, pCsr, iHeight, &isEof); - if( rc!=SQLITE_OK || !isEof ){ - return rc; - } - } - pCsr->pNode = pNode->pParent; - pCsr->iCell = nodeParentIndex(pRtree, pNode); - nodeReference(pCsr->pNode); - nodeRelease(pRtree, pNode); - iHeight++; - } - } - - return rc; -} - -/* -** Rtree virtual table module xRowid method. -*/ -static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){ - Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; - RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; - - assert(pCsr->pNode); - *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); - - return SQLITE_OK; -} - -/* -** Rtree virtual table module xColumn method. -*/ -static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){ - Rtree *pRtree = (Rtree *)cur->pVtab; - RtreeCursor *pCsr = (RtreeCursor *)cur; - - if( i==0 ){ - i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell); - sqlite3_result_int64(ctx, iRowid); - }else{ - RtreeCoord c; - nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c); - if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - sqlite3_result_double(ctx, c.f); - }else{ - assert( pRtree->eCoordType==RTREE_COORD_INT32 ); - sqlite3_result_int(ctx, c.i); - } - } - - return SQLITE_OK; -} - -/* -** Use nodeAcquire() to obtain the leaf node containing the record with -** rowid iRowid. If successful, set *ppLeaf to point to the node and -** return SQLITE_OK. If there is no such record in the table, set -** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf -** to zero and return an SQLite error code. -*/ -static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){ - int rc; - *ppLeaf = 0; - sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid); - if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){ - i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0); - rc = nodeAcquire(pRtree, iNode, 0, ppLeaf); - sqlite3_reset(pRtree->pReadRowid); - }else{ - rc = sqlite3_reset(pRtree->pReadRowid); - } - return rc; -} - - -/* -** Rtree virtual table module xFilter method. -*/ -static int rtreeFilter( - sqlite3_vtab_cursor *pVtabCursor, - int idxNum, const char *idxStr, - int argc, sqlite3_value **argv -){ - Rtree *pRtree = (Rtree *)pVtabCursor->pVtab; - RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor; - - RtreeNode *pRoot = 0; - int ii; - int rc = SQLITE_OK; - - rtreeReference(pRtree); - - sqlite3_free(pCsr->aConstraint); - pCsr->aConstraint = 0; - pCsr->iStrategy = idxNum; - - if( idxNum==1 ){ - /* Special case - lookup by rowid. */ - RtreeNode *pLeaf; /* Leaf on which the required cell resides */ - i64 iRowid = sqlite3_value_int64(argv[0]); - rc = findLeafNode(pRtree, iRowid, &pLeaf); - pCsr->pNode = pLeaf; - if( pLeaf && rc==SQLITE_OK ){ - pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid); - } - }else{ - /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array - ** with the configured constraints. - */ - if( argc>0 ){ - pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc); - pCsr->nConstraint = argc; - if( !pCsr->aConstraint ){ - rc = SQLITE_NOMEM; - }else{ - assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 ); - for(ii=0; iiaConstraint[ii]; - p->op = idxStr[ii*2]; - p->iCoord = idxStr[ii*2+1]-'a'; - p->rValue = sqlite3_value_double(argv[ii]); - } - } - } - - if( rc==SQLITE_OK ){ - pCsr->pNode = 0; - rc = nodeAcquire(pRtree, 1, 0, &pRoot); - } - if( rc==SQLITE_OK ){ - int isEof = 1; - int nCell = NCELL(pRoot); - pCsr->pNode = pRoot; - for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCelliCell++){ - assert( pCsr->pNode==pRoot ); - rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof); - if( !isEof ){ - break; - } - } - if( rc==SQLITE_OK && isEof ){ - assert( pCsr->pNode==pRoot ); - nodeRelease(pRtree, pRoot); - pCsr->pNode = 0; - } - assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCellpNode) ); - } - } - - rtreeRelease(pRtree); - return rc; -} - -/* -** Rtree virtual table module xBestIndex method. There are three -** table scan strategies to choose from (in order from most to -** least desirable): +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} ** -** idxNum idxStr Strategy -** ------------------------------------------------ -** 1 Unused Direct lookup by rowid. -** 2 See below R-tree query. -** 3 Unused Full table scan. -** ------------------------------------------------ +** See also: [SQLITE_IOERR_READ | extended result codes] ** -** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy -** 2 is used, idxStr is formatted to contain 2 bytes for each -** constraint used. The first two bytes of idxStr correspond to -** the constraint in sqlite3_index_info.aConstraintUsage[] with -** (argvIndex==1) etc. +*/ +#define SQLITE_OK 0 /* Successful result */ +/* beginning-of-error-codes */ +#define SQLITE_ERROR 1 /* SQL error or missing database */ +#define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ +#define SQLITE_PERM 3 /* Access permission denied */ +#define SQLITE_ABORT 4 /* Callback routine requested an abort */ +#define SQLITE_BUSY 5 /* The database file is locked */ +#define SQLITE_LOCKED 6 /* A table in the database is locked */ +#define SQLITE_NOMEM 7 /* A malloc() failed */ +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */ +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */ +#define SQLITE_NOTFOUND 12 /* NOT USED. Table or record not found */ +#define SQLITE_FULL 13 /* Insertion failed because database is full */ +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ +#define SQLITE_PROTOCOL 15 /* NOT USED. Database lock protocol error */ +#define SQLITE_EMPTY 16 /* Database is empty */ +#define SQLITE_SCHEMA 17 /* The database schema changed */ +#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ +#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ +#define SQLITE_MISMATCH 20 /* Data type mismatch */ +#define SQLITE_MISUSE 21 /* Library used incorrectly */ +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */ +#define SQLITE_AUTH 23 /* Authorization denied */ +#define SQLITE_FORMAT 24 /* Auxiliary database format error */ +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */ +#define SQLITE_NOTADB 26 /* File opened that is not a database file */ +#define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ +#define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ +/* end-of-error-codes */ + +/* +** CAPI3REF: Extended Result Codes {F10220} ** -** The first of each pair of bytes in idxStr identifies the constraint -** operator as follows: +** In its default configuration, SQLite API routines return one of 26 integer +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as +** much information about problems as programmers might like. In an effort to +** address this, newer versions of SQLite (version 3.3.8 and later) include +** support for additional result codes that provide more detailed information +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} ** -** Operator Byte Value -** ---------------------- -** = 0x41 ('A') -** <= 0x42 ('B') -** < 0x43 ('C') -** >= 0x44 ('D') -** > 0x45 ('E') -** ---------------------- +** The SQLITE_OK result code will never be extended. It will always +** be exactly zero. +*/ +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} ** -** The second of each pair of bytes identifies the coordinate column -** to which the constraint applies. The leftmost coordinate column -** is 'a', the second from the left 'b' etc. +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the +** [sqlite3_vfs] object. */ -static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){ - int rc = SQLITE_OK; - int ii, cCol; - - int iIdx = 0; - char zIdxStr[RTREE_MAX_DIMENSIONS*8+1]; - memset(zIdxStr, 0, sizeof(zIdxStr)); - - assert( pIdxInfo->idxStr==0 ); - for(ii=0; iinConstraint; ii++){ - struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii]; - - if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){ - /* We have an equality constraint on the rowid. Use strategy 1. */ - int jj; - for(jj=0; jjaConstraintUsage[jj].argvIndex = 0; - pIdxInfo->aConstraintUsage[jj].omit = 0; - } - pIdxInfo->idxNum = 1; - pIdxInfo->aConstraintUsage[ii].argvIndex = 1; - pIdxInfo->aConstraintUsage[jj].omit = 1; - return SQLITE_OK; - } - - if( p->usable && p->iColumn>0 ){ - u8 op = 0; - switch( p->op ){ - case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break; - case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break; - case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break; - case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break; - case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break; - } - if( op ){ - /* Make sure this particular constraint has not been used before. - ** If it has been used before, ignore it. - ** - ** A <= or < can be used if there is a prior >= or >. - ** A >= or > can be used if there is a prior < or <=. - ** A <= or < is disqualified if there is a prior <=, <, or ==. - ** A >= or > is disqualified if there is a prior >=, >, or ==. - ** A == is disqualifed if there is any prior constraint. - */ - int j, opmsk; - static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 }; - assert( compatible[RTREE_EQ & 7]==0 ); - assert( compatible[RTREE_LT & 7]==1 ); - assert( compatible[RTREE_LE & 7]==1 ); - assert( compatible[RTREE_GT & 7]==2 ); - assert( compatible[RTREE_GE & 7]==2 ); - cCol = p->iColumn - 1 + 'a'; - opmsk = compatible[op & 7]; - for(j=0; jaConstraintUsage[ii].argvIndex = (iIdx/2); - pIdxInfo->aConstraintUsage[ii].omit = 1; - } - } - } - - pIdxInfo->idxNum = 2; - pIdxInfo->needToFreeIdxStr = 1; - if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){ - return SQLITE_NOMEM; - } - return rc; -} +#define SQLITE_OPEN_READONLY 0x00000001 +#define SQLITE_OPEN_READWRITE 0x00000002 +#define SQLITE_OPEN_CREATE 0x00000004 +#define SQLITE_OPEN_DELETEONCLOSE 0x00000008 +#define SQLITE_OPEN_EXCLUSIVE 0x00000010 +#define SQLITE_OPEN_MAIN_DB 0x00000100 +#define SQLITE_OPEN_TEMP_DB 0x00000200 +#define SQLITE_OPEN_TRANSIENT_DB 0x00000400 +#define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 +#define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 +#define SQLITE_OPEN_SUBJOURNAL 0x00002000 +#define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* -** Return the N-dimensional volumn of the cell stored in *p. -*/ -static float cellArea(Rtree *pRtree, RtreeCell *p){ - float area = 1.0; - int ii; - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ - area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); - } - return area; -} - -/* -** Return the margin length of cell p. The margin length is the sum -** of the objects size in each dimension. -*/ -static float cellMargin(Rtree *pRtree, RtreeCell *p){ - float margin = 0.0; - int ii; - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ - margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])); - } - return margin; -} - -/* -** Store the union of cells p1 and p2 in p1. -*/ -static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){ - int ii; - if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ - p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f); - p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f); - } - }else{ - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ - p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i); - p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i); - } - } -} - -/* -** Return the amount cell p would grow by if it were unioned with pCell. -*/ -static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){ - float area; - RtreeCell cell; - memcpy(&cell, p, sizeof(RtreeCell)); - area = cellArea(pRtree, &cell); - cellUnion(pRtree, &cell, pCell); - return (cellArea(pRtree, &cell)-area); -} - -#if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT -static float cellOverlap( - Rtree *pRtree, - RtreeCell *p, - RtreeCell *aCell, - int nCell, - int iExclude -){ - int ii; - float overlap = 0.0; - for(ii=0; iinDim*2); jj+=2){ - double x1; - double x2; - - x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj])); - x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1])); - - if( x2iDepth-iHeight); ii++){ - int iCell; - sqlite3_int64 iBest; - - float fMinGrowth; - float fMinArea; - float fMinOverlap; - - int nCell = NCELL(pNode); - RtreeCell cell; - RtreeNode *pChild; - - RtreeCell *aCell = 0; - -#if VARIANT_RSTARTREE_CHOOSESUBTREE - if( ii==(pRtree->iDepth-1) ){ - int jj; - aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell); - if( !aCell ){ - rc = SQLITE_NOMEM; - nodeRelease(pRtree, pNode); - pNode = 0; - continue; - } - for(jj=0; jjiDepth-1) ){ - overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell); - } -#endif - if( (iCell==0) - || (overlappParent ){ - RtreeCell cell; - RtreeNode *pParent = p->pParent; - int iCell = nodeParentIndex(pRtree, p); - - nodeGetCell(pRtree, pParent, iCell, &cell); - if( cellGrowth(pRtree, &cell, pCell)>0.0 ){ - cellUnion(pRtree, &cell, pCell); - nodeOverwriteCell(pRtree, pParent, &cell, iCell); - } - - p = pParent; - } -} - -/* -** Write mapping (iRowid->iNode) to the _rowid table. -*/ -static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){ - sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid); - sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode); - sqlite3_step(pRtree->pWriteRowid); - return sqlite3_reset(pRtree->pWriteRowid); -} - -/* -** Write mapping (iNode->iPar) to the _parent table. -*/ -static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){ - sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode); - sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar); - sqlite3_step(pRtree->pWriteParent); - return sqlite3_reset(pRtree->pWriteParent); -} - -static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int); - -#if VARIANT_GUTTMAN_LINEAR_SPLIT -/* -** Implementation of the linear variant of the PickNext() function from -** Guttman[84]. -*/ -static RtreeCell *LinearPickNext( - Rtree *pRtree, - RtreeCell *aCell, - int nCell, - RtreeCell *pLeftBox, - RtreeCell *pRightBox, - int *aiUsed -){ - int ii; - for(ii=0; aiUsed[ii]; ii++); - aiUsed[ii] = 1; - return &aCell[ii]; -} - -/* -** Implementation of the linear variant of the PickSeeds() function from -** Guttman[84]. -*/ -static void LinearPickSeeds( - Rtree *pRtree, - RtreeCell *aCell, - int nCell, - int *piLeftSeed, - int *piRightSeed -){ - int i; - int iLeftSeed = 0; - int iRightSeed = 1; - float maxNormalInnerWidth = 0.0; - - /* Pick two "seed" cells from the array of cells. The algorithm used - ** here is the LinearPickSeeds algorithm from Gutman[1984]. The - ** indices of the two seed cells in the array are stored in local - ** variables iLeftSeek and iRightSeed. - */ - for(i=0; inDim; i++){ - float x1 = aCell[0].aCoord[i*2]; - float x2 = aCell[0].aCoord[i*2+1]; - float x3 = x1; - float x4 = x2; - int jj; - - int iCellLeft = 0; - int iCellRight = 0; - - for(jj=1; jjx4 ) x4 = right; - if( left>x3 ){ - x3 = left; - iCellRight = jj; - } - if( rightmaxNormalInnerWidth ){ - iLeftSeed = iCellLeft; - iRightSeed = iCellRight; - } - } - } - - *piLeftSeed = iLeftSeed; - *piRightSeed = iRightSeed; -} -#endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */ - -#if VARIANT_GUTTMAN_QUADRATIC_SPLIT -/* -** Implementation of the quadratic variant of the PickNext() function from -** Guttman[84]. -*/ -static RtreeCell *QuadraticPickNext( - Rtree *pRtree, - RtreeCell *aCell, - int nCell, - RtreeCell *pLeftBox, - RtreeCell *pRightBox, - int *aiUsed -){ - #define FABS(a) ((a)<0.0?-1.0*(a):(a)) - - int iSelect = -1; - float fDiff; - int ii; - for(ii=0; iifDiff ){ - fDiff = diff; - iSelect = ii; - } - } - } - aiUsed[iSelect] = 1; - return &aCell[iSelect]; -} - -/* -** Implementation of the quadratic variant of the PickSeeds() function from -** Guttman[84]. -*/ -static void QuadraticPickSeeds( - Rtree *pRtree, - RtreeCell *aCell, - int nCell, - int *piLeftSeed, - int *piRightSeed -){ - int ii; - int jj; - - int iLeftSeed = 0; - int iRightSeed = 1; - float fWaste = 0.0; - - for(ii=0; iifWaste ){ - iLeftSeed = ii; - iRightSeed = jj; - fWaste = waste; - } - } - } - - *piLeftSeed = iLeftSeed; - *piRightSeed = iRightSeed; -} -#endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */ - -/* -** Arguments aIdx, aDistance and aSpare all point to arrays of size -** nIdx. The aIdx array contains the set of integers from 0 to -** (nIdx-1) in no particular order. This function sorts the values -** in aIdx according to the indexed values in aDistance. For -** example, assuming the inputs: +** CAPI3REF: Device Characteristics {F10240} ** -** aIdx = { 0, 1, 2, 3 } -** aDistance = { 5.0, 2.0, 7.0, 6.0 } +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] +** object returns an integer which is a vector of the these +** bit values expressing I/O characteristics of the mass storage +** device that holds the file that the [sqlite3_io_methods] +** refers to. {END} ** -** this function sets the aIdx array to contain: +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +#define SQLITE_IOCAP_ATOMIC 0x00000001 +#define SQLITE_IOCAP_ATOMIC512 0x00000002 +#define SQLITE_IOCAP_ATOMIC1K 0x00000004 +#define SQLITE_IOCAP_ATOMIC2K 0x00000008 +#define SQLITE_IOCAP_ATOMIC4K 0x00000010 +#define SQLITE_IOCAP_ATOMIC8K 0x00000020 +#define SQLITE_IOCAP_ATOMIC16K 0x00000040 +#define SQLITE_IOCAP_ATOMIC32K 0x00000080 +#define SQLITE_IOCAP_ATOMIC64K 0x00000100 +#define SQLITE_IOCAP_SAFE_APPEND 0x00000200 +#define SQLITE_IOCAP_SEQUENTIAL 0x00000400 + +/* +** CAPI3REF: File Locking Levels {F10250} ** -** aIdx = { 0, 1, 2, 3 } +** {F10251} SQLite uses one of the following integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. {END} +*/ +#define SQLITE_LOCK_NONE 0 +#define SQLITE_LOCK_SHARED 1 +#define SQLITE_LOCK_RESERVED 2 +#define SQLITE_LOCK_PENDING 3 +#define SQLITE_LOCK_EXCLUSIVE 4 + +/* +** CAPI3REF: Synchronization Type Flags {F10260} ** -** The aSpare array is used as temporary working space by the -** sorting algorithm. -*/ -static void SortByDistance( - int *aIdx, - int nIdx, - float *aDistance, - int *aSpare -){ - if( nIdx>1 ){ - int iLeft = 0; - int iRight = 0; - - int nLeft = nIdx/2; - int nRight = nIdx-nLeft; - int *aLeft = aIdx; - int *aRight = &aIdx[nLeft]; - - SortByDistance(aLeft, nLeft, aDistance, aSpare); - SortByDistance(aRight, nRight, aDistance, aSpare); - - memcpy(aSpare, aLeft, sizeof(int)*nLeft); - aLeft = aSpare; - - while( iLeft1 ){ +#define SQLITE_SYNC_NORMAL 0x00002 +#define SQLITE_SYNC_FULL 0x00003 +#define SQLITE_SYNC_DATAONLY 0x00010 - int iLeft = 0; - int iRight = 0; - - int nLeft = nIdx/2; - int nRight = nIdx-nLeft; - int *aLeft = aIdx; - int *aRight = &aIdx[nLeft]; - - SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare); - SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare); - - memcpy(aSpare, aLeft, sizeof(int)*nLeft); - aLeft = aSpare; - while( iLeftnDim+1)*(sizeof(int*)+nCell*sizeof(int)); - - aaSorted = (int **)sqlite3_malloc(nByte); - if( !aaSorted ){ - return SQLITE_NOMEM; - } - - aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell]; - memset(aaSorted, 0, nByte); - for(ii=0; iinDim; ii++){ - int jj; - aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell]; - for(jj=0; jjnDim; ii++){ - float margin = 0.0; - float fBestOverlap; - float fBestArea; - int iBestLeft; - int nLeft; - - for( - nLeft=RTREE_MINCELLS(pRtree); - nLeft<=(nCell-RTREE_MINCELLS(pRtree)); - nLeft++ - ){ - RtreeCell left; - RtreeCell right; - int kk; - float overlap; - float area; - - memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell)); - memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell)); - for(kk=1; kk<(nCell-1); kk++){ - if( kk0; i--){ - RtreeCell *pNext; - pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed); - float diff = - cellGrowth(pRtree, pBboxLeft, pNext) - - cellGrowth(pRtree, pBboxRight, pNext) - ; - if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i) - || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i)) - ){ - nodeInsertCell(pRtree, pRight, pNext); - cellUnion(pRtree, pBboxRight, pNext); - }else{ - nodeInsertCell(pRtree, pLeft, pNext); - cellUnion(pRtree, pBboxLeft, pNext); - } - } - - sqlite3_free(aiUsed); - return SQLITE_OK; -} -#endif - -static int updateMapping( - Rtree *pRtree, - i64 iRowid, - RtreeNode *pNode, - int iHeight -){ - int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64); - xSetMapping = ((iHeight==0)?rowidWrite:parentWrite); - if( iHeight>0 ){ - RtreeNode *pChild = nodeHashLookup(pRtree, iRowid); - if( pChild ){ - nodeRelease(pRtree, pChild->pParent); - nodeReference(pNode); - pChild->pParent = pNode; - } - } - return xSetMapping(pRtree, iRowid, pNode->iNode); -} - -static int SplitNode( - Rtree *pRtree, - RtreeNode *pNode, - RtreeCell *pCell, - int iHeight -){ - int i; - int newCellIsRight = 0; - - int rc = SQLITE_OK; - int nCell = NCELL(pNode); - RtreeCell *aCell; - int *aiUsed; - - RtreeNode *pLeft = 0; - RtreeNode *pRight = 0; - - RtreeCell leftbbox; - RtreeCell rightbbox; - - /* Allocate an array and populate it with a copy of pCell and - ** all cells from node pLeft. Then zero the original node. - */ - aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1)); - if( !aCell ){ - rc = SQLITE_NOMEM; - goto splitnode_out; - } - aiUsed = (int *)&aCell[nCell+1]; - memset(aiUsed, 0, sizeof(int)*(nCell+1)); - for(i=0; iiNode==1 ){ - pRight = nodeNew(pRtree, pNode, 1); - pLeft = nodeNew(pRtree, pNode, 1); - pRtree->iDepth++; - pNode->isDirty = 1; - writeInt16(pNode->zData, pRtree->iDepth); - }else{ - pLeft = pNode; - pRight = nodeNew(pRtree, pLeft->pParent, 1); - nodeReference(pLeft); - } - - if( !pLeft || !pRight ){ - rc = SQLITE_NOMEM; - goto splitnode_out; - } - - memset(pLeft->zData, 0, pRtree->iNodeSize); - memset(pRight->zData, 0, pRtree->iNodeSize); - - rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox); - if( rc!=SQLITE_OK ){ - goto splitnode_out; - } - - /* Ensure both child nodes have node numbers assigned to them. */ - if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))) - || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft))) - ){ - goto splitnode_out; - } - - rightbbox.iRowid = pRight->iNode; - leftbbox.iRowid = pLeft->iNode; - - if( pNode->iNode==1 ){ - rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1); - if( rc!=SQLITE_OK ){ - goto splitnode_out; - } - }else{ - RtreeNode *pParent = pLeft->pParent; - int iCell = nodeParentIndex(pRtree, pLeft); - nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell); - AdjustTree(pRtree, pParent, &leftbbox); - } - if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){ - goto splitnode_out; - } - - for(i=0; iiRowid ){ - newCellIsRight = 1; - } - if( rc!=SQLITE_OK ){ - goto splitnode_out; - } - } - if( pNode->iNode==1 ){ - for(i=0; iiRowid, pLeft, iHeight); - } - - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pRight); - pRight = 0; - } - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pLeft); - pLeft = 0; - } - -splitnode_out: - nodeRelease(pRtree, pRight); - nodeRelease(pRtree, pLeft); - sqlite3_free(aCell); - return rc; -} - -static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){ - int rc = SQLITE_OK; - if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){ - sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode); - if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){ - i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0); - rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent); - }else{ - rc = SQLITE_ERROR; - } - sqlite3_reset(pRtree->pReadParent); - if( rc==SQLITE_OK ){ - rc = fixLeafParent(pRtree, pLeaf->pParent); - } - } - return rc; -} - -static int deleteCell(Rtree *, RtreeNode *, int, int); - -static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){ - int rc; - RtreeNode *pParent; - int iCell; - - assert( pNode->nRef==1 ); - - /* Remove the entry in the parent cell. */ - iCell = nodeParentIndex(pRtree, pNode); - pParent = pNode->pParent; - pNode->pParent = 0; - if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) - || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent)) - ){ - return rc; - } - - /* Remove the xxx_node entry. */ - sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode); - sqlite3_step(pRtree->pDeleteNode); - if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){ - return rc; - } - - /* Remove the xxx_parent entry. */ - sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode); - sqlite3_step(pRtree->pDeleteParent); - if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){ - return rc; - } - - /* Remove the node from the in-memory hash table and link it into - ** the Rtree.pDeleted list. Its contents will be re-inserted later on. - */ - nodeHashDelete(pRtree, pNode); - pNode->iNode = iHeight; - pNode->pNext = pRtree->pDeleted; - pNode->nRef++; - pRtree->pDeleted = pNode; - - return SQLITE_OK; -} - -static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){ - RtreeNode *pParent = pNode->pParent; - if( pParent ){ - int ii; - int nCell = NCELL(pNode); - RtreeCell box; /* Bounding box for pNode */ - nodeGetCell(pRtree, pNode, 0, &box); - for(ii=1; iiiNode; - ii = nodeParentIndex(pRtree, pNode); - nodeOverwriteCell(pRtree, pParent, &box, ii); - fixBoundingBox(pRtree, pParent); - } -} /* -** Delete the cell at index iCell of node pNode. After removing the -** cell, adjust the r-tree data structure if required. +** CAPI3REF: OS Interface Open File Handle {F11110} +** +** An [sqlite3_file] object represents an open file in the OS +** interface layer. Individual OS interface implementations will +** want to subclass this object by appending additional fields +** for their own use. The pMethods entry is a pointer to an +** [sqlite3_io_methods] object that defines methods for performing +** I/O operations on the open file. */ -static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){ - int rc; - - if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){ - return rc; - } - - /* Remove the cell from the node. This call just moves bytes around - ** the in-memory node image, so it cannot fail. - */ - nodeDeleteCell(pRtree, pNode, iCell); - - /* If the node is not the tree root and now has less than the minimum - ** number of cells, remove it from the tree. Otherwise, update the - ** cell in the parent node so that it tightly contains the updated - ** node. - */ - if( pNode->iNode!=1 ){ - RtreeNode *pParent = pNode->pParent; - if( (pParent->iNode!=1 || NCELL(pParent)!=1) - && (NCELL(pNode)nDim; iDim++){ - aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]); - aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]); - } - } - for(iDim=0; iDimnDim; iDim++){ - aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0); - } - - for(ii=0; iinDim; iDim++){ - float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - - DCOORD(aCell[ii].aCoord[iDim*2]); - aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]); - } - } - - SortByDistance(aOrder, nCell, aDistance, aSpare); - nodeZero(pRtree, pNode); - - for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){ - RtreeCell *p = &aCell[aOrder[ii]]; - nodeInsertCell(pRtree, pNode, p); - if( p->iRowid==pCell->iRowid ){ - if( iHeight==0 ){ - rc = rowidWrite(pRtree, p->iRowid, pNode->iNode); - }else{ - rc = parentWrite(pRtree, p->iRowid, pNode->iNode); - } - } - } - if( rc==SQLITE_OK ){ - fixBoundingBox(pRtree, pNode); - } - for(; rc==SQLITE_OK && iiiNode currently contains - ** the height of the sub-tree headed by the cell. - */ - RtreeNode *pInsert; - RtreeCell *p = &aCell[aOrder[ii]]; - rc = ChooseLeaf(pRtree, p, iHeight, &pInsert); - if( rc==SQLITE_OK ){ - int rc2; - rc = rtreeInsertCell(pRtree, pInsert, p, iHeight); - rc2 = nodeRelease(pRtree, pInsert); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - - sqlite3_free(aCell); - return rc; -} - -/* -** Insert cell pCell into node pNode. Node pNode is the head of a -** subtree iHeight high (leaf nodes have iHeight==0). -*/ -static int rtreeInsertCell( - Rtree *pRtree, - RtreeNode *pNode, - RtreeCell *pCell, - int iHeight -){ - int rc = SQLITE_OK; - if( iHeight>0 ){ - RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid); - if( pChild ){ - nodeRelease(pRtree, pChild->pParent); - nodeReference(pNode); - pChild->pParent = pNode; - } - } - if( nodeInsertCell(pRtree, pNode, pCell) ){ -#if VARIANT_RSTARTREE_REINSERT - if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){ - rc = SplitNode(pRtree, pNode, pCell, iHeight); - }else{ - pRtree->iReinsertHeight = iHeight; - rc = Reinsert(pRtree, pNode, pCell, iHeight); - } -#else - rc = SplitNode(pRtree, pNode, pCell, iHeight); -#endif - }else{ - AdjustTree(pRtree, pNode, pCell); - if( iHeight==0 ){ - rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode); - }else{ - rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode); - } - } - return rc; -} - -static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){ - int ii; - int rc = SQLITE_OK; - int nCell = NCELL(pNode); - - for(ii=0; rc==SQLITE_OK && iiiNode currently contains - ** the height of the sub-tree headed by the cell. - */ - rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert); - if( rc==SQLITE_OK ){ - int rc2; - rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode); - rc2 = nodeRelease(pRtree, pInsert); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - return rc; -} - -/* -** Select a currently unused rowid for a new r-tree record. -*/ -static int newRowid(Rtree *pRtree, i64 *piRowid){ - int rc; - sqlite3_bind_null(pRtree->pWriteRowid, 1); - sqlite3_bind_null(pRtree->pWriteRowid, 2); - sqlite3_step(pRtree->pWriteRowid); - rc = sqlite3_reset(pRtree->pWriteRowid); - *piRowid = sqlite3_last_insert_rowid(pRtree->db); - return rc; -} - -#ifndef NDEBUG -static int hashIsEmpty(Rtree *pRtree){ - int ii; - for(ii=0; iiaHash[ii] ); - } - return 1; -} -#endif - -/* -** The xUpdate method for rtree module virtual tables. -*/ -int rtreeUpdate( - sqlite3_vtab *pVtab, - int nData, - sqlite3_value **azData, - sqlite_int64 *pRowid -){ - Rtree *pRtree = (Rtree *)pVtab; - int rc = SQLITE_OK; - - rtreeReference(pRtree); - - assert(nData>=1); - assert(hashIsEmpty(pRtree)); - - /* If azData[0] is not an SQL NULL value, it is the rowid of a - ** record to delete from the r-tree table. The following block does - ** just that. - */ - if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){ - i64 iDelete; /* The rowid to delete */ - RtreeNode *pLeaf; /* Leaf node containing record iDelete */ - int iCell; /* Index of iDelete cell in pLeaf */ - RtreeNode *pRoot; - - /* Obtain a reference to the root node to initialise Rtree.iDepth */ - rc = nodeAcquire(pRtree, 1, 0, &pRoot); - - /* Obtain a reference to the leaf node that contains the entry - ** about to be deleted. - */ - if( rc==SQLITE_OK ){ - iDelete = sqlite3_value_int64(azData[0]); - rc = findLeafNode(pRtree, iDelete, &pLeaf); - } - - /* Delete the cell in question from the leaf node. */ - if( rc==SQLITE_OK ){ - int rc2; - iCell = nodeRowidIndex(pRtree, pLeaf, iDelete); - rc = deleteCell(pRtree, pLeaf, iCell, 0); - rc2 = nodeRelease(pRtree, pLeaf); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - - /* Delete the corresponding entry in the _rowid table. */ - if( rc==SQLITE_OK ){ - sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete); - sqlite3_step(pRtree->pDeleteRowid); - rc = sqlite3_reset(pRtree->pDeleteRowid); - } - - /* Check if the root node now has exactly one child. If so, remove - ** it, schedule the contents of the child for reinsertion and - ** reduce the tree height by one. - ** - ** This is equivalent to copying the contents of the child into - ** the root node (the operation that Gutman's paper says to perform - ** in this scenario). - */ - if( rc==SQLITE_OK && pRtree->iDepth>0 ){ - if( rc==SQLITE_OK && NCELL(pRoot)==1 ){ - RtreeNode *pChild; - i64 iChild = nodeGetRowid(pRtree, pRoot, 0); - rc = nodeAcquire(pRtree, iChild, pRoot, &pChild); - if( rc==SQLITE_OK ){ - rc = removeNode(pRtree, pChild, pRtree->iDepth-1); - } - if( rc==SQLITE_OK ){ - pRtree->iDepth--; - writeInt16(pRoot->zData, pRtree->iDepth); - pRoot->isDirty = 1; - } - } - } - - /* Re-insert the contents of any underfull nodes removed from the tree. */ - for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){ - if( rc==SQLITE_OK ){ - rc = reinsertNodeContent(pRtree, pLeaf); - } - pRtree->pDeleted = pLeaf->pNext; - sqlite3_free(pLeaf); - } - - /* Release the reference to the root node. */ - if( rc==SQLITE_OK ){ - rc = nodeRelease(pRtree, pRoot); - }else{ - nodeRelease(pRtree, pRoot); - } - } - - /* If the azData[] array contains more than one element, elements - ** (azData[2]..azData[argc-1]) contain a new record to insert into - ** the r-tree structure. - */ - if( rc==SQLITE_OK && nData>1 ){ - /* Insert a new record into the r-tree */ - RtreeCell cell; - int ii; - RtreeNode *pLeaf; - - /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */ - assert( nData==(pRtree->nDim*2 + 3) ); - if( pRtree->eCoordType==RTREE_COORD_REAL32 ){ - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ - cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]); - cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]); - if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){ - rc = SQLITE_CONSTRAINT; - goto constraint; - } - } - }else{ - for(ii=0; ii<(pRtree->nDim*2); ii+=2){ - cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]); - cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]); - if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){ - rc = SQLITE_CONSTRAINT; - goto constraint; - } - } - } - - /* Figure out the rowid of the new row. */ - if( sqlite3_value_type(azData[2])==SQLITE_NULL ){ - rc = newRowid(pRtree, &cell.iRowid); - }else{ - cell.iRowid = sqlite3_value_int64(azData[2]); - sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid); - if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){ - sqlite3_reset(pRtree->pReadRowid); - rc = SQLITE_CONSTRAINT; - goto constraint; - } - rc = sqlite3_reset(pRtree->pReadRowid); - } - - if( rc==SQLITE_OK ){ - rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf); - } - if( rc==SQLITE_OK ){ - int rc2; - pRtree->iReinsertHeight = -1; - rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0); - rc2 = nodeRelease(pRtree, pLeaf); - if( rc==SQLITE_OK ){ - rc = rc2; - } - } - } - -constraint: - rtreeRelease(pRtree); - return rc; -} - -/* -** The xRename method for rtree module virtual tables. -*/ -static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){ - Rtree *pRtree = (Rtree *)pVtab; - int rc = SQLITE_NOMEM; - char *zSql = sqlite3_mprintf( - "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";" - "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";" - "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";" - , pRtree->zDb, pRtree->zName, zNewName - , pRtree->zDb, pRtree->zName, zNewName - , pRtree->zDb, pRtree->zName, zNewName - ); - if( zSql ){ - rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0); - sqlite3_free(zSql); - } - return rc; -} - -static sqlite3_module rtreeModule = { - 0, /* iVersion */ - rtreeCreate, /* xCreate - create a table */ - rtreeConnect, /* xConnect - connect to an existing table */ - rtreeBestIndex, /* xBestIndex - Determine search strategy */ - rtreeDisconnect, /* xDisconnect - Disconnect from a table */ - rtreeDestroy, /* xDestroy - Drop a table */ - rtreeOpen, /* xOpen - open a cursor */ - rtreeClose, /* xClose - close a cursor */ - rtreeFilter, /* xFilter - configure scan constraints */ - rtreeNext, /* xNext - advance a cursor */ - rtreeEof, /* xEof */ - rtreeColumn, /* xColumn - read data */ - rtreeRowid, /* xRowid - read data */ - rtreeUpdate, /* xUpdate - write data */ - 0, /* xBegin - begin transaction */ - 0, /* xSync - sync transaction */ - 0, /* xCommit - commit transaction */ - 0, /* xRollback - rollback transaction */ - 0, /* xFindFunction - function overloading */ - rtreeRename /* xRename - rename the table */ +typedef struct sqlite3_file sqlite3_file; +struct sqlite3_file { + const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ }; -static int rtreeSqlInit( - Rtree *pRtree, - sqlite3 *db, - const char *zDb, - const char *zPrefix, - int isCreate -){ - int rc = SQLITE_OK; - - #define N_STATEMENT 9 - static const char *azSql[N_STATEMENT] = { - /* Read and write the xxx_node table */ - "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1", - "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1", - - /* Read and write the xxx_rowid table */ - "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1", - "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1", - - /* Read and write the xxx_parent table */ - "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1", - "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)", - "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1" - }; - sqlite3_stmt **appStmt[N_STATEMENT]; - int i; - - pRtree->db = db; - - if( isCreate ){ - char *zCreate = sqlite3_mprintf( -"CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);" -"CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);" -"CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);" -"INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))", - zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize - ); - if( !zCreate ){ - return SQLITE_NOMEM; - } - rc = sqlite3_exec(db, zCreate, 0, 0, 0); - sqlite3_free(zCreate); - if( rc!=SQLITE_OK ){ - return rc; - } - } - - appStmt[0] = &pRtree->pReadNode; - appStmt[1] = &pRtree->pWriteNode; - appStmt[2] = &pRtree->pDeleteNode; - appStmt[3] = &pRtree->pReadRowid; - appStmt[4] = &pRtree->pWriteRowid; - appStmt[5] = &pRtree->pDeleteRowid; - appStmt[6] = &pRtree->pReadParent; - appStmt[7] = &pRtree->pWriteParent; - appStmt[8] = &pRtree->pDeleteParent; - - for(i=0; i +**
    • [SQLITE_LOCK_NONE], +**
    • [SQLITE_LOCK_SHARED], +**
    • [SQLITE_LOCK_RESERVED], +**
    • [SQLITE_LOCK_PENDING], or +**
    • [SQLITE_LOCK_EXCLUSIVE]. +** +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, +** PENDING, or EXCLUSIVE lock on the file. It returns true +** if such a lock exists and false if not. +** +** The xFileControl() method is a generic interface that allows custom +** VFS implementations to directly control an open file using the +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to +** write return values. Potential uses for xFileControl() might be +** functions to enable blocking locks with timeouts, to change the +** locking strategy (for example to use dot-file locks), to inquire +** about the status of a lock, or to break stale locks. The SQLite +** core reserves opcodes less than 100 for its own use. +** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. +** Applications that define a custom xFileControl method should use opcodes +** greater than 100 to avoid conflicts. +** +** The xSectorSize() method returns the sector size of the +** device that underlies the file. The sector size is the +** minimum write that can be performed without disturbing +** other bytes in the file. The xDeviceCharacteristics() +** method returns a bit vector describing behaviors of the +** underlying device: +** +**
        +**
      • [SQLITE_IOCAP_ATOMIC] +**
      • [SQLITE_IOCAP_ATOMIC512] +**
      • [SQLITE_IOCAP_ATOMIC1K] +**
      • [SQLITE_IOCAP_ATOMIC2K] +**
      • [SQLITE_IOCAP_ATOMIC4K] +**
      • [SQLITE_IOCAP_ATOMIC8K] +**
      • [SQLITE_IOCAP_ATOMIC16K] +**
      • [SQLITE_IOCAP_ATOMIC32K] +**
      • [SQLITE_IOCAP_ATOMIC64K] +**
      • [SQLITE_IOCAP_SAFE_APPEND] +**
      • [SQLITE_IOCAP_SEQUENTIAL] +**
      +** +** The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** mean that writes of blocks that are nnn bytes in size and +** are aligned to an address which is an integer multiple of +** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** that when data is appended to a file, the data is appended +** first then the size of the file is extended, never the other +** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** information is written to disk in the same order as calls +** to xWrite(). +*/ +typedef struct sqlite3_io_methods sqlite3_io_methods; +struct sqlite3_io_methods { + int iVersion; + int (*xClose)(sqlite3_file*); + int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst); + int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst); + int (*xTruncate)(sqlite3_file*, sqlite3_int64 size); + int (*xSync)(sqlite3_file*, int flags); + int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); + int (*xLock)(sqlite3_file*, int); + int (*xUnlock)(sqlite3_file*, int); + int (*xCheckReservedLock)(sqlite3_file*); + int (*xFileControl)(sqlite3_file*, int op, void *pArg); + int (*xSectorSize)(sqlite3_file*); + int (*xDeviceCharacteristics)(sqlite3_file*); + /* Additional methods may be added in future releases */ +}; /* -** This routine queries database handle db for the page-size used by -** database zDb. If successful, the page-size in bytes is written to -** *piPageSize and SQLITE_OK returned. Otherwise, and an SQLite error -** code is returned. +** CAPI3REF: Standard File Control Opcodes {F11310} +** +** These integer constants are opcodes for the xFileControl method +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] +** interface. +** +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of +** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], +** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) +** into an integer that the pArg argument points to. {F11312} This capability +** is used during testing and only needs to be supported when SQLITE_TEST +** is defined. */ -static int getPageSize(sqlite3 *db, const char *zDb, int *piPageSize){ - int rc = SQLITE_NOMEM; - char *zSql; - sqlite3_stmt *pStmt = 0; +#define SQLITE_FCNTL_LOCKSTATE 1 - zSql = sqlite3_mprintf("PRAGMA %Q.page_size", zDb); - if( !zSql ){ - return SQLITE_NOMEM; - } +/* +** CAPI3REF: Mutex Handle {F17110} +** +** The mutex module within SQLite defines [sqlite3_mutex] to be an +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only +** deals with pointers to the [sqlite3_mutex] object. +** +** Mutexes are created using [sqlite3_mutex_alloc()]. +*/ +typedef struct sqlite3_mutex sqlite3_mutex; - rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0); - sqlite3_free(zSql); - if( rc!=SQLITE_OK ){ - return rc; - } +/* +** CAPI3REF: OS Interface Object {F11140} +** +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" +** in the name of the object stands for "virtual file system". +** +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. +** +** The szOsFile field is the size of the subclassed [sqlite3_file] +** structure used by this VFS. mxPathname is the maximum length of +** a pathname in this VFS. +** +** Registered vfs modules are kept on a linked list formed by +** the pNext pointer. The [sqlite3_vfs_register()] +** and [sqlite3_vfs_unregister()] interfaces manage this list +** in a thread-safe way. The [sqlite3_vfs_find()] interface +** searches the list. +** +** The pNext field is the only fields in the sqlite3_vfs +** structure that SQLite will ever modify. SQLite will only access +** or modify this field while holding a particular static mutex. +** The application should never modify anything within the sqlite3_vfs +** object once the object has been registered. +** +** The zName field holds the name of the VFS module. The name must +** be unique across all VFS modules. +** +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the +** filename if it needs to remember the filename for some reason. +** +** {F11142} The flags argument to xOpen() includes all bits set in +** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] +** or [sqlite3_open16()] is used, then flags includes at least +** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} +** If xOpen() opens a file read-only then it sets *pOutFlags to +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** +** {F11143} SQLite will also add one of the following flags to the xOpen() +** call, depending on the object being opened: +** +**
        +**
      • [SQLITE_OPEN_MAIN_DB] +**
      • [SQLITE_OPEN_MAIN_JOURNAL] +**
      • [SQLITE_OPEN_TEMP_DB] +**
      • [SQLITE_OPEN_TEMP_JOURNAL] +**
      • [SQLITE_OPEN_TRANSIENT_DB] +**
      • [SQLITE_OPEN_SUBJOURNAL] +**
      • [SQLITE_OPEN_MASTER_JOURNAL] +**
      {END} +** +** The file I/O implementation can use the object type flags to +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** +**
        +**
      • [SQLITE_OPEN_DELETEONCLOSE] +**
      • [SQLITE_OPEN_EXCLUSIVE] +**
      +** +** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be +** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] +** will be set for TEMP databases, journals and for subjournals. +** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** for exclusive access. This flag is set for all files except +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to +** allocate the structure; it should just fill it in. +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a +** directory. +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** +** The xRandomness(), xSleep(), and xCurrentTime() interfaces +** are not strictly a part of the filesystem, but they are +** included in the VFS structure for completeness. +** The xRandomness() function attempts to return nBytes bytes +** of good-quality randomness into zOut. The return value is +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at +** least the number of microseconds given. The xCurrentTime() +** method returns a Julian Day Number for the current date and +** time. +*/ +typedef struct sqlite3_vfs sqlite3_vfs; +struct sqlite3_vfs { + int iVersion; /* Structure version number */ + int szOsFile; /* Size of subclassed sqlite3_file */ + int mxPathname; /* Maximum file pathname length */ + sqlite3_vfs *pNext; /* Next registered VFS */ + const char *zName; /* Name of this virtual file system */ + void *pAppData; /* Pointer to application-specific data */ + int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, + int flags, int *pOutFlags); + int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); + int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); + void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); + void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); + void *(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol); + void (*xDlClose)(sqlite3_vfs*, void*); + int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); + int (*xSleep)(sqlite3_vfs*, int microseconds); + int (*xCurrentTime)(sqlite3_vfs*, double*); + /* New fields may be appended in figure versions. The iVersion + ** value will increment whenever this happens. */ +}; - if( SQLITE_ROW==sqlite3_step(pStmt) ){ - *piPageSize = sqlite3_column_int(pStmt, 0); - } - return sqlite3_finalize(pStmt); -} +/* +** CAPI3REF: Flags for the xAccess VFS method {F11190} +** +** {F11191} These integer constants can be used as the third parameter to +** the xAccess method of an [sqlite3_vfs] object. {END} They determine +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. +*/ +#define SQLITE_ACCESS_EXISTS 0 +#define SQLITE_ACCESS_READWRITE 1 +#define SQLITE_ACCESS_READ 2 + +/* +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. +** +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. +*/ +int sqlite3_extended_result_codes(sqlite3*, int onoff); + +/* +** CAPI3REF: Last Insert Rowid {F12220} +** +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. {F12223} If +** the table has a column of type INTEGER PRIMARY KEY then that column +** is another an alias for the rowid. +** +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. +** +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. +** +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. {F12231} When INSERT OR REPLACE +** encounters a constraint violation, it does not fail. The +** INSERT continues to completion after deleting rows that caused +** the constraint problem so INSERT OR REPLACE will always change +** the return value of this interface. +** +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. +*/ +sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); + +/* +** CAPI3REF: Count The Number Of Rows Modified {F12240} +** +** {F12241} This function returns the number of database rows that were changed +** or inserted or deleted by the most recently completed SQL statement +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function +** to find the total number of changes including changes caused by triggers. +** +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of +** changes in the most recently completed INSERT, UPDATE, or DELETE +** statement within the body of the same trigger. +** +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. +*/ +int sqlite3_changes(sqlite3*); + +/* +** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} +** +** See also the [sqlite3_change()] interface. +** +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use +** "DELETE FROM table WHERE 1" instead. +** +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} +*/ +int sqlite3_total_changes(sqlite3*); + +/* +** CAPI3REF: Interrupt A Long-Running Query {F12270} +** +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically +** called in response to a user action such as pressing "Cancel" +** or Ctrl-C where the user wants a long query operation to halt +** immediately. +** +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that +** is closed or might close before sqlite3_interrupt() returns. +** +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements +** that are started after sqlite3_interrupt() returns. +*/ +void sqlite3_interrupt(sqlite3*); + +/* +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} +** +** These routines are useful for command-line input to determine if the +** currently entered text seems to form complete a SQL statement or +** if additional input is needed before sending the text into +** SQLite for parsing. These routines return true if the input string +** appears to be a complete SQL statement. A statement is judged to be +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} +*/ +int sqlite3_complete(const char *sql); +int sqlite3_complete16(const void *sql); + +/* +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the +** busy callback returns 0, then no additional attempts are made to +** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. +** {F12317} If the callback returns non-zero, then another attempt +** is made to open the database for reading and the cycle repeats. +** +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} +** Consider a scenario where one process is holding a read lock that +** it is trying to promote to a reserved lock and +** a second process is holding a reserved lock that it is trying +** to promote to an exclusive lock. The first process cannot proceed +** because it is blocked by the second and the second process cannot +** proceed because it is blocked by the first. If both processes +** invoke the busy handlers, neither will make any progress. Therefore, +** SQLite returns [SQLITE_BUSY] for the first process, hoping that this +** will induce the first process to release its read lock and allow +** the second process to proceed. +** +** {F12321} The default busy callback is NULL. {END} +** +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** when SQLite is in the middle of a large transaction where all the +** changes will not fit into the in-memory cache. {F12323} SQLite will +** already hold a RESERVED lock on the database file, but it needs +** to promote this lock to EXCLUSIVE so that it can spill cache +** pages into the database file without harm to concurrent +** readers. {F12324} If it is unable to promote the lock, then the in-memory +** cache will be left in an inconsistent state and so the error +** code is promoted from the relatively benign [SQLITE_BUSY] to +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** +** CorruptionFollowingBusyError wiki page for a discussion of why +** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} +** +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. +** +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. +*/ +int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); + +/* +** CAPI3REF: Set A Busy Timeout {F12340} +** +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** +** {F12344} Calling this routine with an argument less than or equal to zero +** turns off all busy handlers. +** +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling +** this routine, that other busy handler is cleared. +*/ +int sqlite3_busy_timeout(sqlite3*, int ms); + +/* +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} +** +** As an example, suppose the query result where this table: +** +**
      +**        Name        | Age
      +**        -----------------------
      +**        Alice       | 43
      +**        Bob         | 28
      +**        Cindy       | 21
      +** 
      +** +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: +** +**
      +**        azResult[0] = "Name";
      +**        azResult[1] = "Age";
      +**        azResult[2] = "Alice";
      +**        azResult[3] = "43";
      +**        azResult[4] = "Bob";
      +**        azResult[5] = "28";
      +**        azResult[6] = "Cindy";
      +**        azResult[7] = "21";
      +** 
      +** +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). +** +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} +** +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. +*/ +int sqlite3_get_table( + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ +); +void sqlite3_free_table(char **result); + +/* +** CAPI3REF: Formatted String Printing Functions {F17400} +** +** These routines are workalikes of the "printf()" family of functions +** from the standard C library. +** +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** results into memory obtained from [sqlite3_malloc()]. +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a +** NULL pointer if [sqlite3_malloc()] is unable to allocate enough +** memory to hold the resulting string. +** +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from +** the standard C library. The result is written into the +** buffer supplied as the second parameter whose size is given by +** the first parameter. {END} Note that the order of the +** first two parameters is reversed from snprintf(). This is an +** historical accident that cannot be fixed without breaking +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() +** returns a pointer to its buffer instead of the number of +** characters actually written into the buffer. {END} We admit that +** the number of characters written would be a more useful return +** value but we cannot change the implementation of sqlite3_snprintf() +** now without breaking compatibility. +** +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first +** parameter "n" is the total size of the buffer, including space for +** the zero terminator. {END} So the longest string that can be completely +** written will be n-1 characters. +** +** These routines all implement some additional formatting +** options that are useful for constructing SQL statements. +** All of the usual printf formatting options apply. In addition, there +** is are "%q", "%Q", and "%z" options. +** +** {F17410} The %q option works like %s in that it substitutes a null-terminated +** string from the argument list. But %q also doubles every '\'' character. +** %q is designed for use inside a string literal. {END} By doubling each '\'' +** character it escapes that character and allows it to be inserted into +** the string. +** +** For example, so some string variable contains text as follows: +** +**
      +**  char *zText = "It's a happy day!";
      +** 
      +** +** One can use this text in an SQL statement as follows: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** Because the %q format string is used, the '\'' character in zText +** is escaped and the SQL generated is as follows: +** +**
      +**  INSERT INTO table1 VALUES('It''s a happy day!')
      +** 
      +** +** This is correct. Had we used %s instead of %q, the generated SQL +** would have looked like this: +** +**
      +**  INSERT INTO table1 VALUES('It's a happy day!');
      +** 
      +** +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. +** +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: +** +**
      +**  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      +**  sqlite3_exec(db, zSQL, 0, 0, 0);
      +**  sqlite3_free(zSQL);
      +** 
      +** +** The code above will render a correct SQL statement in the zSQL +** variable even if the zText variable is a NULL pointer. +** +** {F17412} The "%z" formatting option works exactly like "%s" with the +** addition that after the string has been read and copied into +** the result, [sqlite3_free()] is called on the input string. {END} +*/ +char *sqlite3_mprintf(const char*,...); +char *sqlite3_vmprintf(const char*, va_list); +char *sqlite3_snprintf(int,char*,const char*, ...); + +/* +** CAPI3REF: Memory Allocation Subsystem {F17300} +** +** {F17301} The SQLite core uses these three routines for all of its own +** internal memory allocation needs. {END} "Core" in the previous sentence +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** {F17302} The sqlite3_malloc() routine returns a pointer to a block +** of memory at least N bytes in length, where N is the parameter. +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free +** memory, it returns a NULL pointer. {F17304} If the parameter N to +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** {F17305} Calling sqlite3_free() with a pointer previously returned +** by sqlite3_malloc() or sqlite3_realloc() releases that memory so +** that it might be reused. {F17306} The sqlite3_free() routine is +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. {U17307} After being freed, memory +** should neither be read nor written. Even reading previously freed +** memory might result in a segmentation fault or other severe error. +** {U17309} Memory corruption, a segmentation fault, or other severe error +** might result if sqlite3_free() is called with a non-NULL pointer that +** was not obtained from sqlite3_malloc() or sqlite3_free(). +** +** {F17310} The sqlite3_realloc() interface attempts to resize a +** prior memory allocation to be at least N bytes, where N is the +** second parameter. The memory allocation to be resized is the first +** parameter. {F17311} If the first parameter to sqlite3_realloc() +** is a NULL pointer then its behavior is identical to calling +** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc(). +** {F17312} If the second parameter to sqlite3_realloc() is zero or +** negative then the behavior is exactly the same as calling +** sqlite3_free(P) where P is the first parameter to sqlite3_realloc(). +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation +** of at least N bytes in size or NULL if sufficient memory is unavailable. +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes +** of the prior allocation are copied into the beginning of buffer returned +** by sqlite3_realloc() and the prior allocation is freed. +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation +** is not freed. +** +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc() +** is always aligned to at least an 8 byte boundary. {END} +** +** {F17381} The default implementation +** of the memory allocation subsystem uses the malloc(), realloc() +** and free() provided by the standard C library. {F17382} However, if +** SQLite is compiled with the following C preprocessor macro +** +**
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. +** +** In SQLite version 3.5.0 and 3.5.1, it was possible to define +** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in +** implementation of these routines to be omitted. That capability +** is no longer provided. Only built-in memory allocators can be +** used. +** +** The windows OS interface layer calls +** the system malloc() and free() directly when converting +** filenames between the UTF-8 encoding used by SQLite +** and whatever filename encoding is used by the particular windows +** installation. Memory allocation errors are detected, but +** they are reported back as [SQLITE_CANTOPEN] or +** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. +*/ +void *sqlite3_malloc(int); +void *sqlite3_realloc(void*, int); +void sqlite3_free(void*); + +/* +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. +** +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} +** The authorizer callback is invoked as SQL statements are being compiled +** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various +** points during the compilation process, as logic is being created +** to perform various actions, the authorizer callback is invoked to +** see if those actions are allowed. The authorizer callback should +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the +** specific action but allow the SQL statement to continue to be +** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be +** rejected with an error. {F12504} If the authorizer callback returns +** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the +** [sqlite3_prepare_v2()] or equivalent call that triggered the +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} +** +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} +** +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For +** example, an application may allow a user to enter arbitrary +** SQL queries for evaluation by a database. But the application does +** not want the user to be able to make arbitrary changes to the +** database. An authorizer could then be put in place while the +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. +** +** {F12520} Only a single authorizer can be in place on a database connection +** at a time. Each call to sqlite3_set_authorizer overrides the +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} +** +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} +*/ +int sqlite3_set_authorizer( + sqlite3*, + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), + void *pUserData +); + +/* +** CAPI3REF: Authorizer Return Codes {F12590} +** +** The [sqlite3_set_authorizer | authorizer callback function] must +** return either [SQLITE_OK] or one of these two constants in order +** to signal SQLite whether or not the action is permitted. See the +** [sqlite3_set_authorizer | authorizer documentation] for additional +** information. +*/ +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */ +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */ + +/* +** CAPI3REF: Authorizer Action Codes {F12550} +** +** The [sqlite3_set_authorizer()] interface registers a callback function +** that is invoked to authorizer certain SQL statement actions. {F12551} The +** second parameter to the callback is an integer code that specifies +** what action is being authorized. These are the integer action codes that +** the authorizer callback may be passed. {END} +** +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization +** callback function will be parameters or NULL depending on which of these +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback +** is the name of the inner-most trigger or view that is responsible for +** the access attempt or NULL if this access attempt is directly from +** top-level SQL code. +*/ +/******************************************* 3rd ************ 4th ***********/ +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */ +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */ +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */ +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */ +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */ +#define SQLITE_DELETE 9 /* Table Name NULL */ +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */ +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */ +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */ +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */ +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */ +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */ +#define SQLITE_DROP_VIEW 17 /* View Name NULL */ +#define SQLITE_INSERT 18 /* Table Name NULL */ +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */ +#define SQLITE_READ 20 /* Table Name Column Name */ +#define SQLITE_SELECT 21 /* NULL NULL */ +#define SQLITE_TRANSACTION 22 /* NULL NULL */ +#define SQLITE_UPDATE 23 /* Table Name Column Name */ +#define SQLITE_ATTACH 24 /* Filename NULL */ +#define SQLITE_DETACH 25 /* Database Name NULL */ +#define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */ +#define SQLITE_REINDEX 27 /* Index Name NULL */ +#define SQLITE_ANALYZE 28 /* Table Name NULL */ +#define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */ +#define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */ +#define SQLITE_FUNCTION 31 /* Function Name NULL */ +#define SQLITE_COPY 0 /* No longer used */ + +/* +** CAPI3REF: Tracing And Profiling Functions {F12280} +** +** These routines register callback functions that can be used for +** tracing and profiling the execution of SQL statements. +** +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. +** +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} +** +** The sqlite3_profile() API is currently considered experimental and +** is subject to change. +*/ +void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); +void *sqlite3_profile(sqlite3*, + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** {F12911} This routine configures a callback function - the +** progress callback - that is invoked periodically during long +** running calls to [sqlite3_exec()], [sqlite3_step()] and +** [sqlite3_get_table()]. {END} An example use for this +** interface is to keep a GUI updated during a large query. +** +** {F12912} The progress callback is invoked once for every N virtual +** machine opcodes, where N is the second argument to this function. +** {F12913} The progress callback itself is identified by the third +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} +** +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} +** +** {F12918} If the progress callback returns a result other than 0, then +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. +*/ +void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); + +/* +** CAPI3REF: Opening A New Database Connection {F12700} +** +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** an English language description of the error. +** +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. +** +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. +** +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: +** +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      +** +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. +** +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be +** automatically deleted as soon as the database connection is closed. +** +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} +** +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever +** codepage is currently defined. Filenames containing international +** characters must be converted to UTF-8 prior to passing them into +** [sqlite3_open()] or [sqlite3_open_v2()]. +*/ +int sqlite3_open( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open16( + const void *filename, /* Database filename (UTF-16) */ + sqlite3 **ppDb /* OUT: SQLite db handle */ +); +int sqlite3_open_v2( + const char *filename, /* Database filename (UTF-8) */ + sqlite3 **ppDb, /* OUT: SQLite db handle */ + int flags, /* Flags */ + const char *zVfs /* Name of VFS module to use */ +); + +/* +** CAPI3REF: Error Codes And Messages {F12800} +** +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} +** +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} +** +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} +** +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. +*/ +int sqlite3_errcode(sqlite3 *db); +const char *sqlite3_errmsg(sqlite3*); +const void *sqlite3_errmsg16(sqlite3*); + +/* +** CAPI3REF: SQL Statement Object {F13000} +** +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a +** "compiled SQL statement" or simply as a "statement". +** +** The life of a statement object goes something like this: +** +**
        +**
      1. Create the object using [sqlite3_prepare_v2()] or a related +** function. +**
      2. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. +**
      3. Run the SQL by calling [sqlite3_step()] one or more times. +**
      4. Reset the statement using [sqlite3_reset()] then go back +** to step 2. Do this zero or more times. +**
      5. Destroy the object using [sqlite3_finalize()]. +**
      +** +** Refer to documentation on individual methods above for additional +** information. +*/ +typedef struct sqlite3_stmt sqlite3_stmt; + +/* +** CAPI3REF: Compiling An SQL Statement {F13010} +** +** To execute an SQL query, it must first be compiled into a byte-code +** program using one of these routines. +** +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded +** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} +** +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} +** +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. {END} +** +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. +** +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} +** +** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are +** recommended for all new programs. The two older interfaces are retained +** for backwards compatibility, but their use is discouraged. +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to +** behave a differently in two ways: +** +**
        +**
      1. {F13022} +** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it +** always used to do, [sqlite3_step()] will automatically recompile the SQL +** statement and try to run it again. {F12023} If the schema has changed in +** a way that makes the statement no longer valid, [sqlite3_step()] will still +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} +**
      2. +** +**
      3. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} +**
      4. +**
      +*/ +int sqlite3_prepare( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare_v2( + sqlite3 *db, /* Database handle */ + const char *zSql, /* SQL statement, UTF-8 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const char **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); +int sqlite3_prepare16_v2( + sqlite3 *db, /* Database handle */ + const void *zSql, /* SQL statement, UTF-16 encoded */ + int nByte, /* Maximum length of zSql in bytes. */ + sqlite3_stmt **ppStmt, /* OUT: Statement handle */ + const void **pzTail /* OUT: Pointer to unused portion of zSql */ +); + +/* +** CAPIREF: Retrieving Statement SQL {F13100} +** +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. +** +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. +*/ +typedef struct Mem sqlite3_value; + +/* +** CAPI3REF: SQL Function Context Object {F16001} +** +** The context in which an SQL function executes is stored in an +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. +*/ +typedef struct sqlite3_context sqlite3_context; + +/* +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: +** +**
        +**
      • ? +**
      • ?NNN +**
      • :AAA +**
      • @AAA +**
      • $VVV +**
      +** +** In the parameter forms shown above NNN is an integer literal, +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") +** can be set using the sqlite3_bind_*() routines defined here. +** +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index +** for "?NNN" parameters is the value of NNN. +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. +** +** {F13509} The third argument is the value to bind to the parameter. {END} +** +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} +** If the fourth parameter is negative, the length of the string is +** number of bytes up to the first zero terminator. {END} +** +** {F13513} +** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and +** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the +** information is in static, unmanaged space and does not need to be freed. +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. {END} +** +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} +** +** {F13530} The sqlite3_bind_*() routines must be called after +** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and +** before [sqlite3_step()]. {F13531} +** Bindings are not cleared by the [sqlite3_reset()] routine. +** {F13532} Unbound parameters are interpreted as NULL. {END} +** +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a +** virtual machine that is the wrong state or which has already been finalized. +*/ +int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); +int sqlite3_bind_double(sqlite3_stmt*, int, double); +int sqlite3_bind_int(sqlite3_stmt*, int, int); +int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); +int sqlite3_bind_null(sqlite3_stmt*, int); +int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); +int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); +int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); +int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); + +/* +** CAPI3REF: Number Of Host Parameters {F13600} +** +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} +** +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. +*/ +int sqlite3_bind_parameter_count(sqlite3_stmt*); + +/* +** CAPI3REF: Name Of A Host Parameter {F13620} +** +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. +** +** {F13623} The first host parameter has an index of 1, not 0. +** +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was +** originally specified as UTF-16 in [sqlite3_prepare16()] or +** [sqlite3_prepare16_v2()]. +*/ +const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); + +/* +** CAPI3REF: Index Of A Parameter With A Given Name {F13640} +** +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. +*/ +int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); + +/* +** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} +** +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt*); + +/* +** CAPI3REF: Number Of Columns In A Result Set {F13710} +** +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). +*/ +int sqlite3_column_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Column Names In A Result Set {F13720} +** +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. +** +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. +** +** {F13725} If sqlite3_malloc() fails during the processing of either routine +** (for example during a conversion from UTF-8 to UTF-16) then a +** NULL pointer is returned. +*/ +const char *sqlite3_column_name(sqlite3_stmt*, int N); +const void *sqlite3_column_name16(sqlite3_stmt*, int N); + +/* +** CAPI3REF: Source Of Data In A Query Result {F13740} +** +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return +** the database name, the _table_ routines return the table name, and +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested +** again in a different encoding. +** +** {F13745} The names returned are the original un-aliased names of the +** database, table, and column. +** +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by +** the statement, where N is the second function argument. +** +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. +** +** {F13750} As with all other SQLite APIs, those postfixed with "16" return +** UTF-16 encoded strings, the other functions return UTF-8. {END} +** +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +** +** {U13751} +** If two or more threads call one or more of these routines against the same +** prepared statement and column at the same time then the results are +** undefined. +*/ +const char *sqlite3_column_database_name(sqlite3_stmt*,int); +const void *sqlite3_column_database_name16(sqlite3_stmt*,int); +const char *sqlite3_column_table_name(sqlite3_stmt*,int); +const void *sqlite3_column_table_name16(sqlite3_stmt*,int); +const char *sqlite3_column_origin_name(sqlite3_stmt*,int); +const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); + +/* +** CAPI3REF: Declared Datatype Of A Query Result {F13760} +** +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an +** expression or subquery) then the declared type of the table +** column is returned. {F13762} If the Nth column of the result set is an +** expression or subquery, then a NULL pointer is returned. +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: +** +** CREATE TABLE t1(c1 VARIANT); +** +** And the following statement compiled: +** +** SELECT c1 + 1, c1 FROM t1; +** +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). +** +** SQLite uses dynamic run-time typing. So just because a column +** is declared to contain a particular type does not mean that the +** data stored in that column is of the declared type. SQLite is +** strongly typed, but the typing is dynamic not static. Type +** is associated with individual values, not with the containers +** used to hold those values. +*/ +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +const void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* -** This function is the implementation of both the xConnect and xCreate -** methods of the r-tree virtual table. +** CAPI3REF: Evaluate An SQL Statement {F13200} ** -** argv[0] -> module name -** argv[1] -> database name -** argv[2] -> table name -** argv[...] -> column names... +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. +** +** The details of the behavior of this sqlite3_step() interface depend +** on whether the statement was prepared using the newer "v2" interface +** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy +** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the +** new "v2" interface is recommended for new applications but the legacy +** interface will continue to be supported. +** +** In the lagacy interface, the return value will be either [SQLITE_BUSY], +** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. +** +** [SQLITE_BUSY] means that the database engine was unable to acquire the +** database locks it needs to do its job. If the statement is a COMMIT +** or occurs outside of an explicit transaction, then you can retry the +** statement. If the statement is not a COMMIT and occurs within a +** explicit transaction then you should rollback the transaction before +** continuing. +** +** [SQLITE_DONE] means that the statement has finished executing +** successfully. sqlite3_step() should not be called again on this virtual +** machine without first calling [sqlite3_reset()] to reset the virtual +** machine back to its initial state. +** +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. +** sqlite3_step() is called again to retrieve the next row of data. +** +** [SQLITE_ERROR] means that a run-time error (such as a constraint +** violation) has occurred. sqlite3_step() should not be called again on +** the VM. More information may be found by calling [sqlite3_errmsg()]. +** With the legacy interface, a more specific error code (example: +** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) +** can be obtained by calling [sqlite3_reset()] on the +** [sqlite3_stmt | prepared statement]. In the "v2" interface, +** the more specific error code is returned directly by sqlite3_step(). +** +** [SQLITE_MISUSE] means that the this routine was called inappropriately. +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had +** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could +** be the case that the same database connection is being used by two or +** more threads at the same moment in time. +** +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. +** We admit that this is a goofy design. The problem has been fixed +** with the "v2" interface. If you prepare all of your SQL statements +** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly +** by sqlite3_step(). The use of the "v2" interface is recommended. */ -static int rtreeInit( - sqlite3 *db, /* Database connection */ - void *pAux, /* Pointer to head of rtree list */ - int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */ - sqlite3_vtab **ppVtab, /* OUT: New virtual table */ - char **pzErr, /* OUT: Error message, if any */ - int isCreate, /* True for xCreate, false for xConnect */ - int eCoordType /* One of the RTREE_COORD_* constants */ +int sqlite3_step(sqlite3_stmt*); + +/* +** CAPI3REF: Number of columns in a result set {F13770} +** +** Return the number of values in the current row of the result set. +** +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. +*/ +int sqlite3_data_count(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Fundamental Datatypes {F10265} +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: +** +**
        +**
      • 64-bit signed integer +**
      • 64-bit IEEE floating point number +**
      • string +**
      • BLOB +**
      • NULL +**
      {END} +** +** These constants are codes for each of those types. +** +** Note that the SQLITE_TEXT constant was also used in SQLite version 2 +** for a completely different meaning. Software that links against both +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not +** SQLITE_TEXT. +*/ +#define SQLITE_INTEGER 1 +#define SQLITE_FLOAT 2 +#define SQLITE_BLOB 4 +#define SQLITE_NULL 5 +#ifdef SQLITE_TEXT +# undef SQLITE_TEXT +#else +# define SQLITE_TEXT 3 +#endif +#define SQLITE3_TEXT 3 + +/* +** CAPI3REF: Results Values From A Query {F13800} +** +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. +** +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. +** These routines may only be called when the most recent call to +** [sqlite3_step()] has returned [SQLITE_ROW] and neither +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. +** If any of these routines are called after [sqlite3_reset()] or +** [sqlite3_finalize()] or after [sqlite3_step()] has returned +** something other than [SQLITE_ROW], the results are undefined. +** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] +** are called from a different thread while any of these routines +** are pending, then the results are undefined. +** +** The sqlite3_column_type() routine returns +** [SQLITE_INTEGER | datatype code] for the initial data type +** of the result column. The returned value is one of [SQLITE_INTEGER], +** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value +** returned by sqlite3_column_type() is only meaningful if no type +** conversions have occurred as described below. After a type conversion, +** the value returned by sqlite3_column_type() is undefined. Future +** versions of SQLite may change the behavior of sqlite3_column_type() +** following a type conversion. +** +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** routine returns the number of bytes in that BLOB or string. +** If the result is a UTF-16 string, then sqlite3_column_bytes() converts +** the string to UTF-8 and then returns the number of bytes. +** If the result is a numeric value then sqlite3_column_bytes() uses +** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns +** the number of bytes in that string. +** The value returned does not include the zero terminator at the end +** of the string. For clarity: the value returned is the number of +** bytes in the string, not the number of characters. +** +** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary +** pointer, possibly even a NULL pointer. +** +** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() +** but leaves the result in UTF-16 instead of UTF-8. +** The zero terminator is not included in this count. +** +** These routines attempt to convert the value where appropriate. For +** example, if the internal representation is FLOAT and a text result +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: +** +**
      +** +**
      Internal
      Type
      Requested
      Type
      Conversion +** +**
      NULL INTEGER Result is 0 +**
      NULL FLOAT Result is 0.0 +**
      NULL TEXT Result is NULL pointer +**
      NULL BLOB Result is NULL pointer +**
      INTEGER FLOAT Convert from integer to float +**
      INTEGER TEXT ASCII rendering of the integer +**
      INTEGER BLOB Same as for INTEGER->TEXT +**
      FLOAT INTEGER Convert from float to integer +**
      FLOAT TEXT ASCII rendering of the float +**
      FLOAT BLOB Same as FLOAT->TEXT +**
      TEXT INTEGER Use atoi() +**
      TEXT FLOAT Use atof() +**
      TEXT BLOB No change +**
      BLOB INTEGER Convert to TEXT then use atoi() +**
      BLOB FLOAT Convert to TEXT then use atof() +**
      BLOB TEXT Add a zero terminator if needed +**
      +**
      +** +** The table above makes reference to standard C library functions atoi() +** and atof(). SQLite does not really use these functions. It has its +** on equavalent internal routines. The atoi() and atof() names are +** used in the table for brevity and because they are familiar to most +** C programmers. +** +** Note that when type conversions occur, pointers returned by prior +** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or +** sqlite3_column_text16() may be invalidated. +** Type conversions and pointer invalidations might occur +** in the following cases: +** +**
        +**
      • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

      • +** +**
      • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

      • +** +**
      • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

      • +**
      +** +** Conversions between UTF-16be and UTF-16le are always done in place and do +** not invalidate a prior pointer, though of course the content of the buffer +** that the prior pointer points to will have been modified. Other kinds +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. +** +** The safest and easiest to remember policy is to invoke these routines +** in one of the following ways: +** +**
        +**
      • sqlite3_column_text() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_blob() followed by sqlite3_column_bytes()
      • +**
      • sqlite3_column_text16() followed by sqlite3_column_bytes16()
      • +**
      +** +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). +** +** The pointers returned are valid until a type conversion occurs as +** described above, or until [sqlite3_step()] or [sqlite3_reset()] or +** [sqlite3_finalize()] is called. The memory space used to hold strings +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** [sqlite3_free()]. +** +** If a memory allocation error occurs during the evaluation of any +** of these routines, a default value is returned. The default value +** is either the integer 0, the floating point number 0.0, or a NULL +** pointer. Subsequent calls to [sqlite3_errcode()] will return +** [SQLITE_NOMEM]. +*/ +const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes(sqlite3_stmt*, int iCol); +int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); +double sqlite3_column_double(sqlite3_stmt*, int iCol); +int sqlite3_column_int(sqlite3_stmt*, int iCol); +sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol); +const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); +const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); +int sqlite3_column_type(sqlite3_stmt*, int iCol); +sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); + +/* +** CAPI3REF: Destroy A Prepared Statement Object {F13300} +** +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. +** +** This routine can be called at any point during the execution of the +** [sqlite3_stmt | virtual machine]. If the virtual machine has not +** completed execution when this routine is called, that is like +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. +*/ +int sqlite3_finalize(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Reset A Prepared Statement Object {F13330} +** +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. +** Any SQL statement variables that had values bound to them using +** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. +** Use [sqlite3_clear_bindings()] to reset the bindings. +*/ +int sqlite3_reset(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). +** +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. +** +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not +** characters. Any attempt to create a function with a longer name +** will result in an SQLITE_ERROR error. +** +** The third parameter is the number of arguments that the SQL function or +** aggregate takes. If this parameter is negative, then the SQL function or +** aggregate may take any number of arguments. +** +** The fourth parameter, eTextRep, specifies what +** [SQLITE_UTF8 | text encoding] this SQL function prefers for +** its parameters. Any SQL function implementation should be able to work +** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be +** more efficient with one encoding than another. It is allowed to +** invoke sqlite3_create_function() or sqlite3_create_function16() multiple +** times with the same function but with different values of eTextRep. +** When multiple implementations of the same function are available, SQLite +** will pick the one that involves the least amount of data conversion. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. +** +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. +** +** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. +** +** It is permitted to register multiple implementations of the same +** functions with the same name but with either differing numbers of +** arguments or differing perferred text encodings. SQLite will use +** the implementation most closely matches the way in which the +** SQL function is used. +*/ +int sqlite3_create_function( + sqlite3 *, + const char *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); +int sqlite3_create_function16( + sqlite3*, + const void *zFunctionName, + int nArg, + int eTextRep, + void*, + void (*xFunc)(sqlite3_context*,int,sqlite3_value**), + void (*xStep)(sqlite3_context*,int,sqlite3_value**), + void (*xFinal)(sqlite3_context*) +); + +/* +** CAPI3REF: Text Encodings {F10267} +** +** These constant define integer codes that represent the various +** text encodings supported by SQLite. +*/ +#define SQLITE_UTF8 1 +#define SQLITE_UTF16LE 2 +#define SQLITE_UTF16BE 3 +#define SQLITE_UTF16 4 /* Use native byte order */ +#define SQLITE_ANY 5 /* sqlite3_create_function only */ +#define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ + +/* +** CAPI3REF: Obsolete Functions +** +** These functions are all now obsolete. In order to maintain +** backwards compatibility with older code, we continue to support +** these functions. However, new development projects should avoid +** the use of these functions. To help encourage people to avoid +** using these functions, we are not going to tell you want they do. +*/ +int sqlite3_aggregate_count(sqlite3_context*); +int sqlite3_expired(sqlite3_stmt*); +int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); +int sqlite3_global_recover(void); +void sqlite3_thread_cleanup(void); +int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); + +/* +** CAPI3REF: Obtaining SQL Function Parameter Values {F15100} +** +** The C-language implementation of SQL functions and aggregates uses +** this set of interface routines to access the parameter values on +** the function or aggregate. +** +** The xFunc (for scalar functions) or xStep (for aggregates) parameters +** to [sqlite3_create_function()] and [sqlite3_create_function16()] +** define callbacks that implement the SQL functions and aggregates. +** The 4th parameter to these callbacks is an array of pointers to +** [sqlite3_value] objects. There is one [sqlite3_value] object for +** each parameter to the SQL function. These routines are used to +** extract values from the [sqlite3_value] objects. +** +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. +** +** The sqlite3_value_text16() interface extracts a UTF16 string +** in the native byte-order of the host machine. The +** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces +** extract UTF16 strings as big-endian and little-endian respectively. +** +** The sqlite3_value_numeric_type() interface attempts to apply +** numeric affinity to the value. This means that an attempt is +** made to convert the value to an integer or floating point. If +** such a conversion is possible without loss of information (in other +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. +** +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or +** [sqlite3_value_text16()] can be invalidated by a subsequent call to +** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], +** or [sqlite3_value_text16()]. +** +** These routines must be called from the same thread as +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. +** +*/ +const void *sqlite3_value_blob(sqlite3_value*); +int sqlite3_value_bytes(sqlite3_value*); +int sqlite3_value_bytes16(sqlite3_value*); +double sqlite3_value_double(sqlite3_value*); +int sqlite3_value_int(sqlite3_value*); +sqlite3_int64 sqlite3_value_int64(sqlite3_value*); +const unsigned char *sqlite3_value_text(sqlite3_value*); +const void *sqlite3_value_text16(sqlite3_value*); +const void *sqlite3_value_text16le(sqlite3_value*); +const void *sqlite3_value_text16be(sqlite3_value*); +int sqlite3_value_type(sqlite3_value*); +int sqlite3_value_numeric_type(sqlite3_value*); + +/* +** CAPI3REF: Obtain Aggregate Function Context {F16210} +** +** The implementation of aggregate SQL functions use this routine to allocate +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. +** +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} +** +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. +** +** This routine must be called from the same thread in which +** the aggregate SQL function is running. +*/ +void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); + +/* +** CAPI3REF: User Data For Functions {F16240} +** +** {F16241} The sqlite3_user_data() interface returns a copy of +** the pointer that was the pUserData parameter (the 5th parameter) +** of the the [sqlite3_create_function()] +** and [sqlite3_create_function16()] routines that originally +** registered the application defined function. {END} +** +** {U16243} This routine must be called from the same thread in which +** the application-defined function is running. +*/ +void *sqlite3_user_data(sqlite3_context*); + +/* +** CAPI3REF: Function Auxiliary Data {F16270} +** +** The following two functions may be used by scalar SQL functions to +** associate meta-data with argument values. If the same value is passed to +** multiple invocations of the same SQL function during query execution, under +** some circumstances the associated meta-data may be preserved. This may +** be used, for example, to add a regular-expression matching scalar +** function. The compiled version of the regular expression is stored as +** meta-data associated with the SQL value passed as the regular expression +** pattern. The compiled regular expression can be reused on multiple +** invocations of the same function so that the original pattern string +** does not need to be recompiled on each invocation. +** +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data +** associated by the sqlite3_set_auxdata() function with the Nth argument +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. +** +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent +** calls to sqlite3_get_auxdata() might return this data, if it has +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor +** function given by the 4th parameter to sqlite3_set_auxdata() on +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} +** +** In practice, meta-data is preserved between function calls for +** expressions that are constant at compile time. This includes literal +** values and SQL variables. +** +** These routines must be called from the same thread in which +** the SQL function is running. +*/ +void *sqlite3_get_auxdata(sqlite3_context*, int N); +void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); + + +/* +** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} +** +** These are special value for the destructor that is passed in as the +** final argument to routines like [sqlite3_result_blob()]. If the destructor +** argument is SQLITE_STATIC, it means that the content pointer is constant +** and will never change. It does not need to be destroyed. The +** SQLITE_TRANSIENT value means that the content will likely change in +** the near future and that SQLite should make its own private copy of +** the content before returning. +** +** The typedef is necessary to work around problems in certain +** C++ compilers. See ticket #2191. +*/ +typedef void (*sqlite3_destructor_type)(void*); +#define SQLITE_STATIC ((sqlite3_destructor_type)0) +#define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) + +/* +** CAPI3REF: Setting The Result Of An SQL Function {F16400} +** +** These routines are used by the xFunc or xFinal callbacks that +** implement SQL functions and aggregates. See +** [sqlite3_create_function()] and [sqlite3_create_function16()] +** for additional information. +** +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. +** +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed +** to by the second parameter and which is N bytes long where N is the +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero +** bytes and N bytes in size, where N is the value of the 2nd parameter. +** +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified +** by its 2nd argument. +** +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions +** cause the implemented SQL function to throw an exception. +** {F16411} SQLite uses the string pointed to by the +** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() +** or sqlite3_result_error16() is negative then SQLite takes as the error +** message all text up through the first zero character. +** {F16415} If the third parameter to sqlite3_result_error() or +** sqlite3_result_error16() is non-negative then SQLite takes that many +** bytes (not characters) from the 2nd parameter as the error message. +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or +** modify the text after they return without harm. +** +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. +** +** {F16431} The sqlite3_result_int() interface sets the return value +** of the application-defined function to be the 32-bit signed integer +** value given in the 2nd argument. +** {F16432} The sqlite3_result_int64() interface sets the return value +** of the application-defined function to be the 64-bit signed integer +** value given in the 2nd argument. +** +** {F16437} The sqlite3_result_null() interface sets the return value +** of the application-defined function to be NULL. +** +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), +** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces +** set the return value of the application-defined function to be +** a text string which is represented as UTF-8, UTF-16 native byte order, +** UTF-16 little endian, or UTF-16 big endian, respectively. +** {F16442} SQLite takes the text result from the application from +** the 2nd parameter of the sqlite3_result_text* interfaces. +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter +** through the first zero character. +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces +** is non-negative, then as many bytes (not characters) of the text +** pointed to by the 2nd parameter are taken as the application-defined +** function result. +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that +** function as the destructor on the text or blob result when it has +** finished using that result. +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT +** then SQLite makes a copy of the result into space obtained from +** from [sqlite3_malloc()] before it returns. +** +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The +** sqlite3_result_value() interface makes a copy of the [sqlite3_value] +** so that [sqlite3_value] specified in the parameter may change or +** be deallocated after sqlite3_result_value() returns without harm. +** +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved +** the [sqlite3_context] pointer, the results are undefined. +*/ +void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_double(sqlite3_context*, double); +void sqlite3_result_error(sqlite3_context*, const char*, int); +void sqlite3_result_error16(sqlite3_context*, const void*, int); +void sqlite3_result_error_toobig(sqlite3_context*); +void sqlite3_result_error_nomem(sqlite3_context*); +void sqlite3_result_int(sqlite3_context*, int); +void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); +void sqlite3_result_null(sqlite3_context*); +void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); +void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); +void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); +void sqlite3_result_value(sqlite3_context*, sqlite3_value*); +void sqlite3_result_zeroblob(sqlite3_context*, int n); + +/* +** CAPI3REF: Define New Collating Sequences {F16600} +** +** {F16601} +** These functions are used to add new collation sequences to the +** [sqlite3*] handle specified as the first argument. +** +** {F16602} +** The name of the new collation sequence is specified as a UTF-8 string +** for sqlite3_create_collation() and sqlite3_create_collation_v2() +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases +** the name is passed as the second function argument. +** +** {F16604} +** The third argument may be one of the constants [SQLITE_UTF8], +** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied +** routine expects to be passed pointers to strings encoded using UTF-8, +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The +** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that +** the routine expects pointers to 16-bit word aligned strings +** of UTF16 in the native byte order of the host computer. +** +** {F16607} +** A pointer to the user supplied routine must be passed as the fifth +** argument. {F16609} If it is NULL, this is the same as deleting the collation +** sequence (so that SQLite cannot call it anymore). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. +** +** {F16612} +** The remaining arguments to the application-supplied routine are two strings, +** each represented by a [length, data] pair and encoded in the encoding +** that was passed as the third argument when the collation sequence was +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). +** +** {F16615} +** The sqlite3_create_collation_v2() works like sqlite3_create_collation() +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is +** destroyed and is passed a copy of the fourth parameter void* pointer +** of the sqlite3_create_collation_v2(). +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. +*/ +int sqlite3_create_collation( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); +int sqlite3_create_collation_v2( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*), + void(*xDestroy)(void*) +); +int sqlite3_create_collation16( + sqlite3*, + const char *zName, + int eTextRep, + void*, + int(*xCompare)(void*,int,const void*,int,const void*) +); + +/* +** CAPI3REF: Collation Needed Callbacks {F16700} +** +** {F16701} +** To avoid having to register all collation sequences before a database +** can be used, a single callback function may be registered with the +** database handle to be called whenever an undefined collation sequence is +** required. +** +** {F16702} +** If the function is registered using the sqlite3_collation_needed() API, +** then it is passed the names of undefined collation sequences as strings +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. +** +** {F16705} When the callback is invoked, the first argument passed is a copy +** of the second argument to sqlite3_collation_needed() or +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} +** +** The callback function should register the desired collation using +** [sqlite3_create_collation()], [sqlite3_create_collation16()], or +** [sqlite3_create_collation_v2()]. +*/ +int sqlite3_collation_needed( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const char*) +); +int sqlite3_collation_needed16( + sqlite3*, + void*, + void(*)(void*,sqlite3*,int eTextRep,const void*) +); + +/* +** Specify the key for an encrypted database. This routine should be +** called right after sqlite3_open(). +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_key( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The key */ +); + +/* +** Change the key on an open database. If the current database is not +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the +** database is decrypted. +** +** The code to implement this API is not available in the public release +** of SQLite. +*/ +int sqlite3_rekey( + sqlite3 *db, /* Database to be rekeyed */ + const void *pKey, int nKey /* The new key */ +); + +/* +** CAPI3REF: Suspend Execution For A Short Time {F10530} +** +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution +** for at least a number of milliseconds specified in its parameter. +** +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually +** requested from the operating system is returned. +** +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} +*/ +int sqlite3_sleep(int); + +/* +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** +** If this global variable is made to point to a string which is +** the name of a folder (a.ka. directory), then all temporary files +** created by SQLite will be placed in that directory. If this variable +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. +** +** It is not safe to modify this variable once a database connection +** has been opened. It is intended that this variable be set once +** as part of process initialization and before any SQLite interface +** routines have been call and remain unchanged thereafter. +*/ +SQLITE_EXTERN char *sqlite3_temp_directory; + +/* +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or +** zero if the given database connection is or is not in autocommit mode, +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} +** +** If certain kinds of errors occur on a statement within a multi-statement +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], +** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} +** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} +*/ +int sqlite3_get_autocommit(sqlite3*); + +/* +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. +*/ +sqlite3 *sqlite3_db_handle(sqlite3_stmt*); + + +/* +** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} +** +** {F12951} The sqlite3_commit_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12953} The sqlite3_rollback_hook() interface registers a callback +** function to be invoked whenever a transaction is committed. +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() +** for the same database connection is overridden. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. +** +** {F12958} If another function was previously registered, its +** pArg value is returned. Otherwise NULL is returned. +** +** {F12959} Registering a NULL function disables the callback. +** +** {F12961} For the purposes of this API, a transaction is said to have been +** rolled back if an explicit "ROLLBACK" statement is executed, or +** an error or constraint causes an implicit rollback to occur. +** {F12962} The rollback callback is not invoked if a transaction is +** automatically rolled back because the database connection is closed. +** {F12964} The rollback callback is not invoked if a transaction is +** rolled back because a commit callback returned non-zero. +** Check on this {END} +** +** These are experimental interfaces and are subject to change. +*/ +void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); +void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); + +/* +** CAPI3REF: Data Change Notification Callbacks {F12970} +** +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. +** +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. +** +** {F12983} The update hook is not invoked when internal system tables are +** modified (i.e. sqlite_master and sqlite_sequence). +** +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. +*/ +void *sqlite3_update_hook( + sqlite3*, + void(*)(void *,int ,char const *,char const *,sqlite3_int64), + void* +); + +/* +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} +** +** {F10331} +** This routine enables or disables the sharing of the database cache +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. +** +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. +** +** {F10334} +** The cache sharing mode set by this interface effects all subsequent +** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} +** +** Virtual tables cannot be used with a shared cache. {F10336} When shared +** cache is enabled, the [sqlite3_create_module()] API used to register +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} +** +** {F10339} Shared cache is disabled by default. {END} But this might change in +** future releases of SQLite. Applications that care about shared +** cache setting should set it explicitly. +*/ +int sqlite3_enable_shared_cache(int); + +/* +** CAPI3REF: Attempt To Free Heap Memory {F17340} +** +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. +*/ +int sqlite3_release_memory(int); + +/* +** CAPI3REF: Impose A Limit On Heap Size {F17350} +** +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} +** +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, +** the memory is allocated anyway and the current operation proceeds. +** +** {F16354} +** A negative or zero value for N means that there is no soft heap limit and +** [sqlite3_release_memory()] will only be called when memory is exhausted. +** {F16355} The default value for the soft heap limit is zero. +** +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is +** called a "soft" limit. It is advisory only. +** +** Prior to SQLite version 3.5.0, this routine only constrained the memory +** allocated by a single thread - the same thread in which this routine +** runs. Beginning with SQLite version 3.5.0, the soft heap limit is +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In +** version 3.5.0 there is no mechanism for limiting the heap usage for +** individual threads. +*/ +void sqlite3_soft_heap_limit(int); + +/* +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. +** +** The column is identified by the second, third and fourth parameters to +** this function. The second parameter is either the name of the database +** (i.e. "main", "temp" or an attached database) containing the specified +** table or NULL. If it is NULL, then all attached databases are searched +** for the table using the same algorithm as the database engine uses to +** resolve unqualified table references. +** +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters +** may be NULL. +** +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. +** +**
      +** Parameter     Output Type      Description
      +** -----------------------------------
      +**
      +**   5th         const char*      Data type
      +**   6th         const char*      Name of the default collation sequence 
      +**   7th         int              True if the column has a NOT NULL constraint
      +**   8th         int              True if the column is part of the PRIMARY KEY
      +**   9th         int              True if the column is AUTOINCREMENT
      +** 
      +** +** +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. +** +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** parameters are set for the explicitly declared column. If there is no +** explicitly declared IPK column, then the output parameters are set as +** follows: +** +**
      +**     data type: "INTEGER"
      +**     collation sequence: "BINARY"
      +**     not null: 0
      +**     primary key: 1
      +**     auto increment: 0
      +** 
      +** +** This function may load one or more schemas from database files. If an +** error occurs during this process, or if the requested table or column +** cannot be found, an SQLITE error code is returned and an error message +** left in the database handle (to be retrieved using sqlite3_errmsg()). +** +** This API is only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. +*/ +int sqlite3_table_column_metadata( + sqlite3 *db, /* Connection handle */ + const char *zDbName, /* Database name or NULL */ + const char *zTableName, /* Table name */ + const char *zColumnName, /* Column name */ + char const **pzDataType, /* OUTPUT: Declared data type */ + char const **pzCollSeq, /* OUTPUT: Collation sequence name */ + int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */ + int *pPrimaryKey, /* OUTPUT: True if column part of PK */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ +); + +/* +** CAPI3REF: Load An Extension {F12600} +** +** {F12601} The sqlite3_load_extension() interface +** attempts to load an SQLite extension library contained in the file +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0 +** in which case the name of the entry point defaults +** to "sqlite3_extension_init". +** +** {F12604} The sqlite3_load_extension() interface shall +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. +** +** {F12605} +** If an error occurs and pzErrMsg is not 0, then the +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with +** error message text stored in memory obtained from [sqlite3_malloc()]. +** {END} The calling function should free this memory +** by calling [sqlite3_free()]. +** +** {F12606} +** Extension loading must be enabled using [sqlite3_enable_load_extension()] +** prior to calling this API or an error will be returned. +*/ +int sqlite3_load_extension( + sqlite3 *db, /* Load the extension into this database connection */ + const char *zFile, /* Name of the shared library containing extension */ + const char *zProc, /* Entry point. Derived from zFile if 0 */ + char **pzErrMsg /* Put error message here if not 0 */ +); + +/* +** CAPI3REF: Enable Or Disable Extension Loading {F12620} +** +** So as not to open security holes in older applications that are +** unprepared to deal with extension loading, and as a means of disabling +** extension loading while evaluating user-entered SQL, the following +** API is provided to turn the [sqlite3_load_extension()] mechanism on and +** off. {F12622} It is off by default. {END} See ticket #1863. +** +** {F12621} Call the sqlite3_enable_load_extension() routine +** with onoff==1 to turn extension loading on +** and call it with onoff==0 to turn it back off again. {END} +*/ +int sqlite3_enable_load_extension(sqlite3 *db, int onoff); + +/* +** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640} +** +** {F12641} This function +** registers an extension entry point that is automatically invoked +** whenever a new database connection is opened using +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END} +** +** This API can be invoked at program startup in order to register +** one or more statically linked extensions that will be available +** to all new database connections. +** +** {F12642} Duplicate extensions are detected so calling this routine multiple +** times with the same extension is harmless. +** +** {F12643} This routine stores a pointer to the extension in an array +** that is obtained from sqlite_malloc(). {END} If you run a memory leak +** checker on your program and it reports a leak because of this +** array, then invoke [sqlite3_reset_auto_extension()] prior +** to shutdown to free the memory. +** +** {F12644} Automatic extensions apply across all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +int sqlite3_auto_extension(void *xEntryPoint); + + +/* +** CAPI3REF: Reset Automatic Extension Loading {F12660} +** +** {F12661} This function disables all previously registered +** automatic extensions. {END} This +** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** calls. +** +** {F12662} This call disabled automatic extensions in all threads. {END} +** +** This interface is experimental and is subject to change or +** removal in future releases of SQLite. +*/ +void sqlite3_reset_auto_extension(void); + + +/* +****** EXPERIMENTAL - subject to change without notice ************** +** +** The interface to the virtual-table mechanism is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stablizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +*/ + +/* +** Structures used by the virtual table interface +*/ +typedef struct sqlite3_vtab sqlite3_vtab; +typedef struct sqlite3_index_info sqlite3_index_info; +typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor; +typedef struct sqlite3_module sqlite3_module; + +/* +** A module is a class of virtual tables. Each module is defined +** by an instance of the following structure. This structure consists +** mostly of methods for the module. +*/ +struct sqlite3_module { + int iVersion; + int (*xCreate)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xConnect)(sqlite3*, void *pAux, + int argc, const char *const*argv, + sqlite3_vtab **ppVTab, char**); + int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*); + int (*xDisconnect)(sqlite3_vtab *pVTab); + int (*xDestroy)(sqlite3_vtab *pVTab); + int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor); + int (*xClose)(sqlite3_vtab_cursor*); + int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr, + int argc, sqlite3_value **argv); + int (*xNext)(sqlite3_vtab_cursor*); + int (*xEof)(sqlite3_vtab_cursor*); + int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int); + int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid); + int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *); + int (*xBegin)(sqlite3_vtab *pVTab); + int (*xSync)(sqlite3_vtab *pVTab); + int (*xCommit)(sqlite3_vtab *pVTab); + int (*xRollback)(sqlite3_vtab *pVTab); + int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, + void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), + void **ppArg); + + int (*xRename)(sqlite3_vtab *pVtab, const char *zNew); +}; + +/* +** The sqlite3_index_info structure and its substructures is used to +** pass information into and receive the reply from the xBestIndex +** method of an sqlite3_module. The fields under **Inputs** are the +** inputs to xBestIndex and are read-only. xBestIndex inserts its +** results into the **Outputs** fields. +** +** The aConstraint[] array records WHERE clause constraints of the +** form: +** +** column OP expr +** +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in +** aConstraint[].iColumn. aConstraint[].usable is TRUE if the +** expr on the right-hand side can be evaluated (and thus the constraint +** is usable) and false if it cannot. +** +** The optimizer automatically inverts terms of the form "expr OP column" +** and makes other simplifications to the WHERE clause in an attempt to +** get as many WHERE clause terms into the form shown above as possible. +** The aConstraint[] array only reports WHERE clause terms in the correct +** form that refer to the particular virtual table being queried. +** +** Information about the ORDER BY clause is stored in aOrderBy[]. +** Each term of aOrderBy records a column of the ORDER BY clause. +** +** The xBestIndex method must fill aConstraintUsage[] with information +** about what parameters to pass to xFilter. If argvIndex>0 then +** the right-hand side of the corresponding aConstraint[] is evaluated +** and becomes the argvIndex-th entry in argv. If aConstraintUsage[].omit +** is true, then the constraint is assumed to be fully handled by the +** virtual table and is not checked again by SQLite. +** +** The idxNum and idxPtr values are recorded and passed into xFilter. +** sqlite3_free() is used to free idxPtr if needToFreeIdxPtr is true. +** +** The orderByConsumed means that output from xFilter will occur in +** the correct order to satisfy the ORDER BY clause so that no separate +** sorting step is required. +** +** The estimatedCost value is an estimate of the cost of doing the +** particular lookup. A full scan of a table with N entries should have +** a cost of N. A binary search of a table of N entries should have a +** cost of approximately log(N). +*/ +struct sqlite3_index_info { + /* Inputs */ + int nConstraint; /* Number of entries in aConstraint */ + struct sqlite3_index_constraint { + int iColumn; /* Column on left-hand side of constraint */ + unsigned char op; /* Constraint operator */ + unsigned char usable; /* True if this constraint is usable */ + int iTermOffset; /* Used internally - xBestIndex should ignore */ + } *aConstraint; /* Table of WHERE clause constraints */ + int nOrderBy; /* Number of terms in the ORDER BY clause */ + struct sqlite3_index_orderby { + int iColumn; /* Column number */ + unsigned char desc; /* True for DESC. False for ASC. */ + } *aOrderBy; /* The ORDER BY clause */ + + /* Outputs */ + struct sqlite3_index_constraint_usage { + int argvIndex; /* if >0, constraint is part of argv to xFilter */ + unsigned char omit; /* Do not code a test for this constraint */ + } *aConstraintUsage; + int idxNum; /* Number used to identify the index */ + char *idxStr; /* String, possibly obtained from sqlite3_malloc */ + int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */ + int orderByConsumed; /* True if output is already ordered */ + double estimatedCost; /* Estimated cost of using this index */ +}; +#define SQLITE_INDEX_CONSTRAINT_EQ 2 +#define SQLITE_INDEX_CONSTRAINT_GT 4 +#define SQLITE_INDEX_CONSTRAINT_LE 8 +#define SQLITE_INDEX_CONSTRAINT_LT 16 +#define SQLITE_INDEX_CONSTRAINT_GE 32 +#define SQLITE_INDEX_CONSTRAINT_MATCH 64 + +/* +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. +*/ +int sqlite3_create_module( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void * /* Client data for xCreate/xConnect */ +); + +/* +** This routine is identical to the sqlite3_create_module() method above, +** except that it allows a destructor function to be specified. It is +** even more experimental than the rest of the virtual tables API. +*/ +int sqlite3_create_module_v2( + sqlite3 *db, /* SQLite connection to register module with */ + const char *zName, /* Name of the module */ + const sqlite3_module *, /* Methods for the module */ + void *, /* Client data for xCreate/xConnect */ + void(*xDestroy)(void*) /* Module destructor function */ +); + +/* +** Every module implementation uses a subclass of the following structure +** to describe a particular instance of the module. Each subclass will +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. +** +** Virtual tables methods can set an error message by assigning a +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() +** prior to assigning a new string to zErrMsg. After the error message +** is delivered up to the client application, the string will be automatically +** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note +** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field +** since virtual tables are commonly implemented in loadable extensions which +** do not have access to sqlite3MPrintf() or sqlite3Free(). +*/ +struct sqlite3_vtab { + const sqlite3_module *pModule; /* The module for this virtual table */ + int nRef; /* Used internally */ + char *zErrMsg; /* Error message from sqlite3_mprintf() */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* Every module implementation uses a subclass of the following structure +** to describe cursors that point into the virtual table and are used +** to loop through the virtual table. Cursors are created using the +** xOpen method of the module. Each module implementation will define +** the content of a cursor structure to suit its own needs. +** +** This superclass exists in order to define fields of the cursor that +** are common to all implementations. +*/ +struct sqlite3_vtab_cursor { + sqlite3_vtab *pVtab; /* Virtual table of this cursor */ + /* Virtual table implementations will typically add additional fields */ +}; + +/* +** The xCreate and xConnect methods of a module use the following API +** to declare the format (the names and datatypes of the columns) of +** the virtual tables they implement. +*/ +int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); + +/* +** Virtual tables can provide alternative implementations of functions +** using the xFindFunction method. But global versions of those functions +** must exist in order to be overloaded. +** +** This API makes sure a global version of a function with a particular +** name and number of parameters exists. If no such function exists +** before this API is called, a new function is created. The implementation +** of the new function always causes an exception to be thrown. So +** the new function is not good for anything by itself. Its only +** purpose is to be a place-holder function that can be overloaded +** by virtual tables. +** +** This API should be considered part of the virtual table interface, +** which is experimental and subject to change. +*/ +int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); + +/* +** The interface to the virtual-table mechanism defined above (back up +** to a comment remarkably similar to this one) is currently considered +** to be experimental. The interface might change in incompatible ways. +** If this is a problem for you, do not use the interface at this time. +** +** When the virtual-table mechanism stabilizes, we will declare the +** interface fixed, support it indefinitely, and remove this comment. +** +****** EXPERIMENTAL - subject to change without notice ************** +*/ + +/* +** CAPI3REF: A Handle To An Open BLOB {F17800} +** +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. +** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. +*/ +typedef struct sqlite3_blob sqlite3_blob; + +/* +** CAPI3REF: Open A BLOB For Incremental I/O {F17810} +** +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: +** +**
      +**     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
      +** 
      {END} +** +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** We should go through and mark all interfaces that behave this +** way with a similar statement +*/ +int sqlite3_blob_open( + sqlite3*, + const char *zDb, + const char *zTable, + const char *zColumn, + sqlite3_int64 iRow, + int flags, + sqlite3_blob **ppBlob +); + +/* +** CAPI3REF: Close A BLOB Handle {F17830} +** +** Close an open [sqlite3_blob | blob handle]. +** +** {F17831} Closing a BLOB shall cause the current transaction to commit +** if there are no other BLOBs, no pending prepared statements, and the +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache +** until the close operation if they will fit. {END} +** Closing the BLOB often forces the changes +** out to disk and so if any I/O errors occur, they will likely occur +** at the time when the BLOB is closed. {F17833} Any errors that occur during +** closing are reported as a non-zero return value. +** +** {F17839} The BLOB is closed unconditionally. Even if this routine returns +** an error code, the BLOB is still closed. +*/ +int sqlite3_blob_close(sqlite3_blob *); + +/* +** CAPI3REF: Return The Size Of An Open BLOB {F17805} +** +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. +*/ +int sqlite3_blob_bytes(sqlite3_blob *); + +/* +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. +** +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. +** +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); + +/* +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. +** +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. +** +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is +** less than zero [SQLITE_ERROR] is returned and no data is written. +** +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. +*/ +int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); + +/* +** CAPI3REF: Virtual File System Objects {F11200} +** +** A virtual filesystem (VFS) is an [sqlite3_vfs] object +** that SQLite uses to interact +** with the underlying operating system. Most builds come with a +** single default VFS that is appropriate for the host computer. +** New VFSes can be registered and existing VFSes can be unregistered. +** The following interfaces are provided. +** +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} +** +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a +** VFS is registered with a name that is NULL or an empty string, +** then the behavior is undefined. +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as +** the default. The choice for the new VFS is arbitrary. +*/ +sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); +int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); +int sqlite3_vfs_unregister(sqlite3_vfs*); + +/* +** CAPI3REF: Mutexes {F17000} +** +** The SQLite core uses these routines for thread +** synchronization. Though they are intended for internal +** use by SQLite, code that links against SQLite is +** permitted to use any of these routines. +** +** The SQLite source code contains multiple implementations +** of these mutex routines. An appropriate implementation +** is selected automatically at compile-time. The following +** implementations are available in the SQLite core: +** +**
        +**
      • SQLITE_MUTEX_OS2 +**
      • SQLITE_MUTEX_PTHREAD +**
      • SQLITE_MUTEX_W32 +**
      • SQLITE_MUTEX_NOOP +**
      +** +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in +** a single-threaded application. The SQLITE_MUTEX_OS2, +** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations +** are appropriate for use on os/2, unix, and windows. +** +** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor +** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. +** +** {F17011} The sqlite3_mutex_alloc() routine allocates a new +** mutex and returns a pointer to it. {F17012} If it returns NULL +** that means that a mutex could not be allocated. {F17013} SQLite +** will unwind its stack and return an error. {F17014} The argument +** to sqlite3_mutex_alloc() is one of these integer constants: +** +**
        +**
      • SQLITE_MUTEX_FAST +**
      • SQLITE_MUTEX_RECURSIVE +**
      • SQLITE_MUTEX_STATIC_MASTER +**
      • SQLITE_MUTEX_STATIC_MEM +**
      • SQLITE_MUTEX_STATIC_MEM2 +**
      • SQLITE_MUTEX_STATIC_PRNG +**
      • SQLITE_MUTEX_STATIC_LRU +**
      {END} +** +** {F17015} The first two constants cause sqlite3_mutex_alloc() to create +** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE +** is used but not necessarily so when SQLITE_MUTEX_FAST is used. {END} +** The mutex implementation does not need to make a distinction +** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does +** not want to. {F17016} But SQLite will only request a recursive mutex in +** cases where it really needs one. {END} If a faster non-recursive mutex +** implementation is available on the host platform, the mutex subsystem +** might return such a mutex in response to SQLITE_MUTEX_FAST. +** +** {F17017} The other allowed parameters to sqlite3_mutex_alloc() each return +** a pointer to a static preexisting mutex. {END} Four static mutexes are +** used by the current version of SQLite. Future versions of SQLite +** may add additional static mutexes. Static mutexes are for internal +** use by SQLite only. Applications that use SQLite mutexes should +** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or +** SQLITE_MUTEX_RECURSIVE. +** +** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() +** returns a different mutex on every call. {F17034} But for the static +** mutex types, the same mutex is returned on every call that has +** the same type number. {END} +** +** {F17019} The sqlite3_mutex_free() routine deallocates a previously +** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static +** mutex results in undefined behavior. {F17023} SQLite never deallocates +** a static mutex. {END} +** +** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt +** to enter a mutex. {F17024} If another thread is already within the mutex, +** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK +** upon successful entry. {F17026} Mutexes created using +** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. +** {F17027} In such cases the, +** mutex must be exited an equal number of times before another thread +** can enter. {U17028} If the same thread tries to enter any other +** kind of mutex more than once, the behavior is undefined. +** {F17029} SQLite will never exhibit +** such behavior in its own use of mutexes. {END} +** +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} +** +** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was +** previously entered by the same thread. {U17032} The behavior +** is undefined if the mutex is not currently entered by the +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} +** +** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. +*/ +sqlite3_mutex *sqlite3_mutex_alloc(int); +void sqlite3_mutex_free(sqlite3_mutex*); +void sqlite3_mutex_enter(sqlite3_mutex*); +int sqlite3_mutex_try(sqlite3_mutex*); +void sqlite3_mutex_leave(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Verifcation Routines {F17080} +** +** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines +** are intended for use inside assert() statements. {F17081} The SQLite core +** never uses these routines except inside an assert() and applications +** are advised to follow the lead of the core. {F17082} The core only +** provides implementations for these routines when it is compiled +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations +** are only required to provide these routines if SQLITE_DEBUG is +** defined and if NDEBUG is not defined. +** +** {F17083} These routines should return true if the mutex in their argument +** is held or not held, respectively, by the calling thread. {END} +** +** {X17084} The implementation is not required to provided versions of these +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} +** +** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then +** the routine should return 1. {END} This seems counter-intuitive since +** clearly the mutex cannot be held if it does not exist. But the +** the reason the mutex does not exist is because the build is not +** using mutexes. And we do not want the assert() containing the +** call to sqlite3_mutex_held() to fail, so a non-zero return is +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** interface should also return 1 when given a NULL pointer. +*/ +int sqlite3_mutex_held(sqlite3_mutex*); +int sqlite3_mutex_notheld(sqlite3_mutex*); + +/* +** CAPI3REF: Mutex Types {F17001} +** +** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument +** which is one of these integer constants. {END} +*/ +#define SQLITE_MUTEX_FAST 0 +#define SQLITE_MUTEX_RECURSIVE 1 +#define SQLITE_MUTEX_STATIC_MASTER 2 +#define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ +#define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ +#define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ +#define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ + +/* +** CAPI3REF: Low-Level Control Of Database Files {F11300} +** +** {F11301} The [sqlite3_file_control()] interface makes a direct call to the +** xFileControl method for the [sqlite3_io_methods] object associated +** with a particular database identified by the second argument. {F11302} The +** name of the database is the name assigned to the database by the +** ATTACH SQL command that opened the +** database. {F11303} To control the main database file, use the name "main" +** or a NULL pointer. {F11304} The third and fourth parameters to this routine +** are passed directly through to the second and third parameters of +** the xFileControl method. {F11305} The return value of the xFileControl +** method becomes the return value of this routine. +** +** {F11306} If the second parameter (zDbName) does not match the name of any +** open database file, then SQLITE_ERROR is returned. {F11307} This error +** code is not remembered and will not be recalled by [sqlite3_errcode()] +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between +** an incorrect zDbName and an SQLITE_ERROR return from the underlying +** xFileControl method. {END} +** +** See also: [SQLITE_FCNTL_LOCKSTATE] +*/ +int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); + +/* +** Undo the hack that converts floating point types to integer for +** builds on processors without floating point support. +*/ +#ifdef SQLITE_OMIT_FLOATING_POINT +# undef double +#endif + +#if 0 +} /* End of the 'extern "C"' block */ +#endif +#endif + +/************** End of sqlite3.h *********************************************/ +/************** Continuing where we left off in fts3_tokenizer.h *************/ + +/* +** Structures used by the tokenizer interface. When a new tokenizer +** implementation is registered, the caller provides a pointer to +** an sqlite3_tokenizer_module containing pointers to the callback +** functions that make up an implementation. +** +** When an fts3 table is created, it passes any arguments passed to +** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the +** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer +** implementation. The xCreate() function in turn returns an +** sqlite3_tokenizer structure representing the specific tokenizer to +** be used for the fts3 table (customized by the tokenizer clause arguments). +** +** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen() +** method is called. It returns an sqlite3_tokenizer_cursor object +** that may be used to tokenize a specific input buffer based on +** the tokenization rules supplied by a specific sqlite3_tokenizer +** object. +*/ +typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module; +typedef struct sqlite3_tokenizer sqlite3_tokenizer; +typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor; + +struct sqlite3_tokenizer_module { + + /* + ** Structure version. Should always be set to 0. + */ + int iVersion; + + /* + ** Create a new tokenizer. The values in the argv[] array are the + ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL + ** TABLE statement that created the fts3 table. For example, if + ** the following SQL is executed: + ** + ** CREATE .. USING fts3( ... , tokenizer arg1 arg2) + ** + ** then argc is set to 2, and the argv[] array contains pointers + ** to the strings "arg1" and "arg2". + ** + ** This method should return either SQLITE_OK (0), or an SQLite error + ** code. If SQLITE_OK is returned, then *ppTokenizer should be set + ** to point at the newly created tokenizer structure. The generic + ** sqlite3_tokenizer.pModule variable should not be initialised by + ** this callback. The caller will do so. + */ + int (*xCreate)( + int argc, /* Size of argv array */ + const char *const*argv, /* Tokenizer argument strings */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ + ); + + /* + ** Destroy an existing tokenizer. The fts3 module calls this method + ** exactly once for each successful call to xCreate(). + */ + int (*xDestroy)(sqlite3_tokenizer *pTokenizer); + + /* + ** Create a tokenizer cursor to tokenize an input buffer. The caller + ** is responsible for ensuring that the input buffer remains valid + ** until the cursor is closed (using the xClose() method). + */ + int (*xOpen)( + sqlite3_tokenizer *pTokenizer, /* Tokenizer object */ + const char *pInput, int nBytes, /* Input buffer */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */ + ); + + /* + ** Destroy an existing tokenizer cursor. The fts3 module calls this + ** method exactly once for each successful call to xOpen(). + */ + int (*xClose)(sqlite3_tokenizer_cursor *pCursor); + + /* + ** Retrieve the next token from the tokenizer cursor pCursor. This + ** method should either return SQLITE_OK and set the values of the + ** "OUT" variables identified below, or SQLITE_DONE to indicate that + ** the end of the buffer has been reached, or an SQLite error code. + ** + ** *ppToken should be set to point at a buffer containing the + ** normalized version of the token (i.e. after any case-folding and/or + ** stemming has been performed). *pnBytes should be set to the length + ** of this buffer in bytes. The input text that generated the token is + ** identified by the byte offsets returned in *piStartOffset and + ** *piEndOffset. + ** + ** The buffer *ppToken is set to point at is managed by the tokenizer + ** implementation. It is only required to be valid until the next call + ** to xNext() or xClose(). + */ + /* TODO(shess) current implementation requires pInput to be + ** nul-terminated. This should either be fixed, or pInput/nBytes + ** should be converted to zInput. + */ + int (*xNext)( + sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */ + const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */ + int *piStartOffset, /* OUT: Byte offset of token in input buffer */ + int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */ + int *piPosition /* OUT: Number of tokens returned before this one */ + ); +}; + +struct sqlite3_tokenizer { + const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */ + /* Tokenizer implementations will typically add additional fields */ +}; + +struct sqlite3_tokenizer_cursor { + sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */ + /* Tokenizer implementations will typically add additional fields */ +}; + +#endif /* _FTS3_TOKENIZER_H_ */ + +/************** End of fts3_tokenizer.h **************************************/ +/************** Continuing where we left off in fts3_icu.c *******************/ + +#include +#include +#include +#include + +typedef struct IcuTokenizer IcuTokenizer; +typedef struct IcuCursor IcuCursor; + +struct IcuTokenizer { + sqlite3_tokenizer base; + char *zLocale; +}; + +struct IcuCursor { + sqlite3_tokenizer_cursor base; + + UBreakIterator *pIter; /* ICU break-iterator object */ + int nChar; /* Number of UChar elements in pInput */ + UChar *aChar; /* Copy of input using utf-16 encoding */ + int *aOffset; /* Offsets of each character in utf-8 input */ + + int nBuffer; + char *zBuffer; + + int iToken; +}; + +/* +** Create a new tokenizer instance. +*/ +static int icuCreate( + int argc, /* Number of entries in argv[] */ + const char * const *argv, /* Tokenizer creation arguments */ + sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */ ){ - int rc = SQLITE_OK; - int iPageSize = 0; - Rtree *pRtree; - int nDb; /* Length of string argv[1] */ - int nName; /* Length of string argv[2] */ + IcuTokenizer *p; + int n = 0; - const char *aErrMsg[] = { - 0, /* 0 */ - "Wrong number of columns for an rtree table", /* 1 */ - "Too few columns for an rtree table", /* 2 */ - "Too many columns for an rtree table" /* 3 */ - }; - - int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2; - if( aErrMsg[iErr] ){ - *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]); - return SQLITE_ERROR; + if( argc>0 ){ + n = strlen(argv[0])+1; } - - rc = getPageSize(db, argv[1], &iPageSize); - if( rc!=SQLITE_OK ){ - return rc; - } - - /* Allocate the sqlite3_vtab structure */ - nDb = strlen(argv[1]); - nName = strlen(argv[2]); - pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2); - if( !pRtree ){ + p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); + if( !p ){ return SQLITE_NOMEM; } - memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2); - pRtree->nBusy = 1; - pRtree->base.pModule = &rtreeModule; - pRtree->zDb = (char *)&pRtree[1]; - pRtree->zName = &pRtree->zDb[nDb+1]; - pRtree->nDim = (argc-4)/2; - pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2; - pRtree->eCoordType = eCoordType; - memcpy(pRtree->zDb, argv[1], nDb); - memcpy(pRtree->zName, argv[2], nName); + memset(p, 0, sizeof(IcuTokenizer)); - /* Figure out the node size to use. By default, use 64 bytes less than - ** the database page-size. This ensures that each node is stored on - ** a single database page. - ** - ** If the databasd page-size is so large that more than RTREE_MAXCELLS - ** entries would fit in a single node, use a smaller node-size. - */ - pRtree->iNodeSize = iPageSize-64; - if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)iNodeSize ){ - pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS; + if( n ){ + p->zLocale = (char *)&p[1]; + memcpy(p->zLocale, argv[0], n); } - /* Create/Connect to the underlying relational database schema. If - ** that is successful, call sqlite3_declare_vtab() to configure - ** the r-tree table schema. - */ - if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){ - *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db)); - }else{ - char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]); - char *zTmp; - int ii; - for(ii=4; zSql && ii*2 coordinates. -*/ -static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){ - char *zText = 0; - RtreeNode node; - Rtree tree; - int ii; - - memset(&node, 0, sizeof(RtreeNode)); - memset(&tree, 0, sizeof(Rtree)); - tree.nDim = sqlite3_value_int(apArg[0]); - tree.nBytesPerCell = 8 + 8 * tree.nDim; - node.zData = (u8 *)sqlite3_value_blob(apArg[1]); - - for(ii=0; iiaChar = (UChar *)&pCsr[1]; + pCsr->aOffset = (int *)&pCsr->aChar[nChar]; + + pCsr->aOffset[iOut] = iInput; + U8_NEXT(zInput, iInput, nInput, c); + while( c>0 ){ + int isError = 0; + c = u_foldCase(c, opt); + U16_APPEND(pCsr->aChar, iOut, nChar, c, isError); + if( isError ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->aOffset[iOut] = iInput; + + if( iInputpIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status); + if( !U_SUCCESS(status) ){ + sqlite3_free(pCsr); + return SQLITE_ERROR; + } + pCsr->nChar = iOut; + + ubrk_first(pCsr->pIter); + *ppCursor = (sqlite3_tokenizer_cursor *)pCsr; + return SQLITE_OK; } -#endif -#endif +/* +** Close a tokenization cursor previously opened by a call to icuOpen(). +*/ +static int icuClose(sqlite3_tokenizer_cursor *pCursor){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + ubrk_close(pCsr->pIter); + sqlite3_free(pCsr->zBuffer); + sqlite3_free(pCsr); + return SQLITE_OK; +} -/************** End of rtree.c ***********************************************/ +/* +** Extract the next token from a tokenization cursor. +*/ +static int icuNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ +){ + IcuCursor *pCsr = (IcuCursor *)pCursor; + + int iStart = 0; + int iEnd = 0; + int nByte = 0; + + while( iStart==iEnd ){ + UChar32 c; + + iStart = ubrk_current(pCsr->pIter); + iEnd = ubrk_next(pCsr->pIter); + if( iEnd==UBRK_DONE ){ + return SQLITE_DONE; + } + + while( iStartaChar, iWhite, pCsr->nChar, c); + if( u_isspace(c) ){ + iStart = iWhite; + }else{ + break; + } + } + assert(iStart<=iEnd); + } + + do { + UErrorCode status = U_ZERO_ERROR; + if( nByte ){ + char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte); + if( !zNew ){ + return SQLITE_NOMEM; + } + pCsr->zBuffer = zNew; + pCsr->nBuffer = nByte; + } + + u_strToUTF8( + pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */ + &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */ + &status /* Output success/failure */ + ); + } while( nByte>pCsr->nBuffer ); + + *ppToken = pCsr->zBuffer; + *pnBytes = nByte; + *piStartOffset = pCsr->aOffset[iStart]; + *piEndOffset = pCsr->aOffset[iEnd]; + *piPosition = pCsr->iToken++; + + return SQLITE_OK; +} + +/* +** The set of routines that implement the simple tokenizer +*/ +static const sqlite3_tokenizer_module icuTokenizerModule = { + 0, /* iVersion */ + icuCreate, /* xCreate */ + icuDestroy, /* xCreate */ + icuOpen, /* xOpen */ + icuClose, /* xClose */ + icuNext, /* xNext */ +}; + +/* +** Set *ppModule to point at the implementation of the ICU tokenizer. +*/ +void sqlite3Fts3IcuTokenizerModule( + sqlite3_tokenizer_module const**ppModule +){ + *ppModule = &icuTokenizerModule; +} + +#endif /* defined(SQLITE_ENABLE_ICU) */ +#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ + +/************** End of fts3_icu.c ********************************************/ diff --git a/db/sqlite3/src/sqlite3.h b/db/sqlite3/src/sqlite3.h index 0cb2931c4a95..5842b3c61700 100644 --- a/db/sqlite3/src/sqlite3.h +++ b/db/sqlite3/src/sqlite3.h @@ -17,7 +17,7 @@ ** ** Some of the definitions that are in this file are marked as ** "experimental". Experimental interfaces are normally new -** features recently added to SQLite. We do not anticipate changes +** features recently added to SQLite. We do not anticipate changes ** to experimental interfaces but reserve to make minor changes if ** experience from use "in the wild" suggest such changes are prudent. ** @@ -30,7 +30,7 @@ ** the version number) and changes its name to "sqlite3.h" as ** part of the build process. ** -** @(#) $Id: sqlite.h.in,v 1.372 2008/07/16 13:29:51 drh Exp $ +** @(#) $Id: sqlite3.h,v 1.17 2008/01/22 13:54:07 mozilla%weilbacher.org Exp $ */ #ifndef _SQLITE3_H_ #define _SQLITE3_H_ @@ -52,7 +52,8 @@ extern "C" { #endif /* -** Ensure these symbols were not defined by some previous header file. +** Make sure these symbols where not defined by some previous header +** file. */ #ifdef SQLITE_VERSION # undef SQLITE_VERSION @@ -64,62 +65,50 @@ extern "C" { /* ** CAPI3REF: Compile-Time Library Version Numbers {F10010} ** -** The SQLITE_VERSION and SQLITE_VERSION_NUMBER #defines in -** the sqlite3.h file specify the version of SQLite with which -** that header file is associated. +** {F10011} The #define in the sqlite3.h header file named +** SQLITE_VERSION resolves to a string literal that identifies +** the version of the SQLite library in the format "X.Y.Z", where +** X is the major version number, Y is the minor version number and Z +** is the release number. The X.Y.Z might be followed by "alpha" or "beta". +** {END} For example "3.1.1beta". ** -** The "version" of SQLite is a string of the form "X.Y.Z". -** The phrase "alpha" or "beta" might be appended after the Z. -** The X value is major version number always 3 in SQLite3. -** The X value only changes when backwards compatibility is -** broken and we intend to never break backwards compatibility. -** The Y value is the minor version number and only changes when +** The X value is always 3 in SQLite. The X value only changes when +** backwards compatibility is broken and we intend to never break +** backwards compatibility. The Y value only changes when ** there are major feature enhancements that are forwards compatible -** but not backwards compatible. -** The Z value is the release number and is incremented with -** each release but resets back to 0 whenever Y is incremented. +** but not backwards compatible. The Z value is incremented with +** each release but resets back to 0 when Y is incremented. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves to an integer +** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are as +** with SQLITE_VERSION. {END} For example, for version "3.1.1beta", +** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using +** version 3.1.1 or greater at compile time, programs may use the test +** (SQLITE_VERSION_NUMBER>=3001001). ** ** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()]. -** -** INVARIANTS: -** -** {F10011} The SQLITE_VERSION #define in the sqlite3.h header file shall -** evaluate to a string literal that is the SQLite version -** with which the header file is associated. -** -** {F10014} The SQLITE_VERSION_NUMBER #define shall resolve to an integer -** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z -** are the major version, minor version, and release number. */ -#define SQLITE_VERSION "3.6.0" -#define SQLITE_VERSION_NUMBER 3006000 +#define SQLITE_VERSION "3.5.4.1" +#define SQLITE_VERSION_NUMBER 3005004 /* ** CAPI3REF: Run-Time Library Version Numbers {F10020} -** KEYWORDS: sqlite3_version ** -** These features provide the same information as the [SQLITE_VERSION] -** and [SQLITE_VERSION_NUMBER] #defines in the header, but are associated -** with the library instead of the header file. Cautious programmers might -** include a check in their application to verify that -** sqlite3_libversion_number() always returns the value +** {F10021} The sqlite3_libversion_number() interface returns an integer +** equal to [SQLITE_VERSION_NUMBER]. {END} The value returned +** by this routine should only be different from the header values +** if the application is compiled using an sqlite3.h header from a +** different version of SQLite than library. Cautious programmers might +** include a check in their application to verify that +** sqlite3_libversion_number() always returns the value ** [SQLITE_VERSION_NUMBER]. ** -** The sqlite3_libversion() function returns the same information as is -** in the sqlite3_version[] string constant. The function is provided -** for use in DLLs since DLL users usually do not have direct access to string +** {F10022} The sqlite3_version[] string constant contains the text of the +** [SQLITE_VERSION] string. {F10023} The sqlite3_libversion() function returns +** a pointer to the sqlite3_version[] string constant. {END} The +** sqlite3_libversion() function +** is provided for DLL users who can only access functions and not ** constants within the DLL. -** -** INVARIANTS: -** -** {F10021} The [sqlite3_libversion_number()] interface shall return -** an integer equal to [SQLITE_VERSION_NUMBER]. -** -** {F10022} The [sqlite3_version] string constant shall contain -** the text of the [SQLITE_VERSION] string. -** -** {F10023} The [sqlite3_libversion()] function shall return -** a pointer to the [sqlite3_version] string constant. */ SQLITE_EXTERN const char sqlite3_version[]; const char *sqlite3_libversion(void); @@ -128,79 +117,52 @@ int sqlite3_libversion_number(void); /* ** CAPI3REF: Test To See If The Library Is Threadsafe {F10100} ** -** SQLite can be compiled with or without mutexes. When -** the [SQLITE_THREADSAFE] C preprocessor macro is true, mutexes -** are enabled and SQLite is threadsafe. When that macro is false, -** the mutexes are omitted. Without the mutexes, it is not safe -** to use SQLite concurrently from more than one thread. +** {F10101} The sqlite3_threadsafe() routine returns nonzero +** if SQLite was compiled with its mutexes enabled or zero if +** SQLite was compiled with mutexes disabled. {END} If this +** routine returns false, then it is not safe for simultaneously +** running threads to both invoke SQLite interfaces. ** -** Enabling mutexes incurs a measurable performance penalty. -** So if speed is of utmost importance, it makes sense to disable -** the mutexes. But for maximum safety, mutexes should be enabled. -** The default behavior is for mutexes to be enabled. -** -** This interface can be used by a program to make sure that the -** version of SQLite that it is linking against was compiled with -** the desired setting of the [SQLITE_THREADSAFE] macro. -** -** This interface only reports on the compile-time mutex setting -** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with -** SQLITE_THREADSAFE=1 then mutexes are enabled by default but -** can be fully or partially disabled using a call to [sqlite3_config()] -** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD], -** or [SQLITE_CONFIG_MUTEX]. The return value of this function shows -** only the default compile-time setting, not any run-time changes -** to that setting. -** -** INVARIANTS: -** -** {F10101} The [sqlite3_threadsafe()] function shall return nonzero if -** SQLite was compiled with the its mutexes enabled by default -** or zero if SQLite was compiled such that mutexes are -** permanently disabled. -** -** {F10102} The value returned by the [sqlite3_threadsafe()] function -** shall not change when mutex setting are modified at -** runtime using the [sqlite3_config()] interface and -** especially the [SQLITE_CONFIG_SINGLETHREAD], -** [SQLITE_CONFIG_MULTITHREAD], [SQLITE_CONFIG_SERIALIZED], -** and [SQLITE_CONFIG_MUTEX] verbs. +** Really all this routine does is return true if SQLite was +** compiled with the -DSQLITE_THREADSAFE=1 option and false if +** compiled with -DSQLITE_THREADSAFE=0. If SQLite uses an +** application-defined mutex subsystem, malloc subsystem, collating +** sequence, VFS, SQL function, progress callback, commit hook, +** extension, or other accessories and these add-ons are not +** threadsafe, then clearly the combination will not be threadsafe +** either. Hence, this routine never reports that the library +** is guaranteed to be threadsafe, only when it is guaranteed not +** to be. */ int sqlite3_threadsafe(void); /* ** CAPI3REF: Database Connection Handle {F12000} -** KEYWORDS: {database connection} {database connections} ** -** Each open SQLite database is represented by a pointer to an instance of -** the opaque structure named "sqlite3". It is useful to think of an sqlite3 +** Each open SQLite database is represented by pointer to an instance of the +** opaque structure named "sqlite3". It is useful to think of an sqlite3 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()] -** is its destructor. There are many other interfaces (such as -** [sqlite3_prepare_v2()], [sqlite3_create_function()], and -** [sqlite3_busy_timeout()] to name but three) that are methods on an -** sqlite3 object. +** [sqlite3_open_v2()] interfaces are its constructors +** and [sqlite3_close()] is its destructor. There are many other interfaces +** (such as [sqlite3_prepare_v2()], [sqlite3_create_function()], and +** [sqlite3_busy_timeout()] to name but three) that are methods on this +** object. */ typedef struct sqlite3 sqlite3; + /* ** CAPI3REF: 64-Bit Integer Types {F10200} -** KEYWORDS: sqlite_int64 sqlite_uint64 ** -** Because there is no cross-platform way to specify 64-bit integer types +** Because there is no cross-platform way to specify such types ** SQLite includes typedefs for 64-bit signed and unsigned integers. +** {F10201} The sqlite_int64 and sqlite3_int64 types specify a +** 64-bit signed integer. {F10202} The sqlite_uint64 and +** sqlite3_uint64 types specify a 64-bit unsigned integer. {END} ** -** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions. -** The sqlite_int64 and sqlite_uint64 types are supported for backwards -** compatibility only. -** -** INVARIANTS: -** -** {F10201} The [sqlite_int64] and [sqlite3_int64] type shall specify -** a 64-bit signed integer. -** -** {F10202} The [sqlite_uint64] and [sqlite3_uint64] type shall specify -** a 64-bit unsigned integer. +** The sqlite3_int64 and sqlite3_uint64 are the preferred type +** definitions. The sqlite_int64 and sqlite_uint64 types are +** supported for backwards compatibility only. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; @@ -217,7 +179,7 @@ typedef sqlite_uint64 sqlite3_uint64; /* ** If compiling for a processor that lacks floating point support, -** substitute integer for floating-point. +** substitute integer for floating-point */ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 @@ -226,53 +188,22 @@ typedef sqlite_uint64 sqlite3_uint64; /* ** CAPI3REF: Closing A Database Connection {F12010} ** -** This routine is the destructor for the [sqlite3] object. +** {F12011} The sqlite3_close() interfaces destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], [sqlite3_open16()], or +** [sqlite3_open_v2()]. {F12012} Sqlite3_close() releases all +** memory used by the connection and closes all open files. {END}. ** -** Applications should [sqlite3_finalize | finalize] all [prepared statements] -** and [sqlite3_blob_close | close] all [BLOB handles] associated with -** the [sqlite3] object prior to attempting to close the object. -** The [sqlite3_next_stmt()] interface can be used to locate all -** [prepared statements] associated with a [database connection] if desired. -** Typical code might look like this: +** {F12013} If the database connection contains +** [sqlite3_stmt | prepared statements] that have not been finalized +** by [sqlite3_finalize()], then sqlite3_close() returns SQLITE_BUSY +** and leaves the connection open. {F12014} Giving sqlite3_close() +** a NULL pointer is a harmless no-op. {END} ** -**
      -** sqlite3_stmt *pStmt;
      -** while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
      -**     sqlite3_finalize(pStmt);
      -** }
      -** 
      -** -** If [sqlite3_close()] is invoked while a transaction is open, -** the transaction is automatically rolled back. -** -** INVARIANTS: -** -** {F12011} A successful call to [sqlite3_close(C)] shall destroy the -** [database connection] object C. -** -** {F12012} A successful call to [sqlite3_close(C)] shall return SQLITE_OK. -** -** {F12013} A successful call to [sqlite3_close(C)] shall release all -** memory and system resources associated with [database connection] -** C. -** -** {F12014} A call to [sqlite3_close(C)] on a [database connection] C that -** has one or more open [prepared statements] shall fail with -** an [SQLITE_BUSY] error code. -** -** {F12015} A call to [sqlite3_close(C)] where C is a NULL pointer shall -** return SQLITE_OK. -** -** {F12019} When [sqlite3_close(C)] is invoked on a [database connection] C -** that has a pending transaction, the transaction shall be -** rolled back. -** -** LIMITATIONS: -** -** {A12016} The C parameter to [sqlite3_close(C)] must be either a NULL -** pointer or an [sqlite3] object pointer previously obtained -** from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()], and not previously closed. +** {U12015} Passing this routine a database connection that has already been +** closed results in undefined behavior. {U12016} If other interfaces that +** reference the same database connection are pending (either in the +** same thread or in different threads) when this routine is called, +** then the behavior is undefined and is almost certainly undesirable. */ int sqlite3_close(sqlite3 *); @@ -286,112 +217,64 @@ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* ** CAPI3REF: One-Step Query Execution Interface {F12100} ** -** The sqlite3_exec() interface is a convenient way of running one or more -** SQL statements without having to write a lot of C code. The UTF-8 encoded -** SQL statements are passed in as the second parameter to sqlite3_exec(). -** The statements are evaluated one by one until either an error or -** an interrupt is encountered, or until they are all done. The 3rd parameter -** is an optional callback that is invoked once for each row of any query -** results produced by the SQL statements. The 5th parameter tells where -** to write any error messages. +** {F12101} The sqlite3_exec() interface evaluates zero or more +** UTF-8 encoded, semicolon-separated SQL statements in the zero-terminated +** string of its second argument. {F12102} The SQL +** statements are evaluated in the context of the database connection +** specified by in the first argument. +** {F12103} SQL statements are prepared one by one using +** [sqlite3_prepare()] or the equivalent, evaluated +** using one or more calls to [sqlite3_step()], then destroyed +** using [sqlite3_finalize()]. {F12104} The return value of +** sqlite3_exec() is SQLITE_OK if all SQL statement run +** successfully. ** -** The error message passed back through the 5th parameter is held -** in memory obtained from [sqlite3_malloc()]. To avoid a memory leak, -** the calling application should call [sqlite3_free()] on any error -** message returned through the 5th parameter when it has finished using -** the error message. +** {F12105} If one or more of the SQL statements handed to +** sqlite3_exec() are queries, then +** the callback function specified by the 3rd parameter is +** invoked once for each row of the query result. {F12106} +** If the callback returns a non-zero value then the query +** is aborted, all subsequent SQL statements +** are skipped and the sqlite3_exec() function returns the [SQLITE_ABORT]. ** -** If the SQL statement in the 2nd parameter is NULL or an empty string -** or a string containing only whitespace and comments, then no SQL -** statements are evaluated and the database is not changed. +** {F12107} The 4th parameter to sqlite3_exec() is an arbitrary pointer +** that is passed through to the callback function as its first parameter. ** -** The sqlite3_exec() interface is implemented in terms of -** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. -** The sqlite3_exec() routine does nothing to the database that cannot be done -** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. +** {F12108} The 2nd parameter to the callback function is the number of +** columns in the query result. {F12109} The 3rd parameter to the callback +** is an array of pointers to strings holding the values for each column +** as extracted using [sqlite3_column_text()]. NULL values in the result +** set result in a NULL pointer. All other value are in their UTF-8 +** string representation. {F12117} +** The 4th parameter to the callback is an array of strings +** obtained using [sqlite3_column_name()] and holding +** the names of each column, also in UTF-8. ** -** INVARIANTS: +** {F12110} The callback function may be NULL, even for queries. A NULL +** callback is not an error. It just means that no callback +** will be invoked. ** -** {F12101} A successful invocation of [sqlite3_exec(D,S,C,A,E)] -** shall sequentially evaluate all of the UTF-8 encoded, -** semicolon-separated SQL statements in the zero-terminated -** string S within the context of the [database connection] D. +** {F12112} If an error occurs while parsing or evaluating the SQL +** then an appropriate error message is written into memory obtained +** from [sqlite3_malloc()] and *errmsg is made to point to that message +** assuming errmsg is not NULL. +** {U12113} The calling function is responsible for freeing the memory +** using [sqlite3_free()]. +** {F12116} If [sqlite3_malloc()] fails while attempting to generate +** the error message, *errmsg is set to NULL. +** {F12114} If errmsg is NULL then no attempt is made to generate an +** error message. Is the return code SQLITE_NOMEM or the original +** error code? What happens if there are multiple errors? +** Do we get code for the first error, or is the choice of reported +** error arbitrary? ** -** {F12102} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL then -** the actions of the interface shall be the same as if the -** S parameter were an empty string. -** -** {F12104} The return value of [sqlite3_exec()] shall be [SQLITE_OK] if all -** SQL statements run successfully and to completion. -** -** {F12105} The return value of [sqlite3_exec()] shall be an appropriate -** non-zero [error code] if any SQL statement fails. -** -** {F12107} If one or more of the SQL statements handed to [sqlite3_exec()] -** return results and the 3rd parameter is not NULL, then -** the callback function specified by the 3rd parameter shall be -** invoked once for each row of result. -** -** {F12110} If the callback returns a non-zero value then [sqlite3_exec()] -** shall abort the SQL statement it is currently evaluating, -** skip all subsequent SQL statements, and return [SQLITE_ABORT]. -** -** {F12113} The [sqlite3_exec()] routine shall pass its 4th parameter through -** as the 1st parameter of the callback. -** -** {F12116} The [sqlite3_exec()] routine shall set the 2nd parameter of its -** callback to be the number of columns in the current row of -** result. -** -** {F12119} The [sqlite3_exec()] routine shall set the 3rd parameter of its -** callback to be an array of pointers to strings holding the -** values for each column in the current result set row as -** obtained from [sqlite3_column_text()]. -** -** {F12122} The [sqlite3_exec()] routine shall set the 4th parameter of its -** callback to be an array of pointers to strings holding the -** names of result columns as obtained from [sqlite3_column_name()]. -** -** {F12125} If the 3rd parameter to [sqlite3_exec()] is NULL then -** [sqlite3_exec()] shall silently discard query results. -** -** {F12131} If an error occurs while parsing or evaluating any of the SQL -** statements in the S parameter of [sqlite3_exec(D,S,C,A,E)] and if -** the E parameter is not NULL, then [sqlite3_exec()] shall store -** in *E an appropriate error message written into memory obtained -** from [sqlite3_malloc()]. -** -** {F12134} The [sqlite3_exec(D,S,C,A,E)] routine shall set the value of -** *E to NULL if E is not NULL and there are no errors. -** -** {F12137} The [sqlite3_exec(D,S,C,A,E)] function shall set the [error code] -** and message accessible via [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()]. -** -** {F12138} If the S parameter to [sqlite3_exec(D,S,C,A,E)] is NULL or an -** empty string or contains nothing other than whitespace, comments, -** and/or semicolons, then results of [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** shall reset to indicate no errors. -** -** LIMITATIONS: -** -** {A12141} The first parameter to [sqlite3_exec()] must be an valid and open -** [database connection]. -** -** {A12142} The database connection must not be closed while -** [sqlite3_exec()] is running. -** -** {A12143} The calling function should use [sqlite3_free()] to free -** the memory that *errmsg is left pointing at once the error -** message is no longer needed. -** -** {A12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()] -** must remain unchanged while [sqlite3_exec()] is running. +** {F12115} The return value is is SQLITE_OK if there are no errors and +** some other [SQLITE_OK | return code] if there is an error. +** The particular return value depends on the type of error. {END} */ int sqlite3_exec( sqlite3*, /* An open database */ - const char *sql, /* SQL to be evaluated */ + const char *sql, /* SQL to be evaluted */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ @@ -399,15 +282,18 @@ int sqlite3_exec( /* ** CAPI3REF: Result Codes {F10210} -** KEYWORDS: SQLITE_OK {error code} {error codes} -** KEYWORDS: {result code} {result codes} +** KEYWORDS: SQLITE_OK ** ** Many SQLite functions return an integer result code from the set shown -** here in order to indicates success or failure. +** above in order to indicates success or failure. ** -** New error codes may be added in future versions of SQLite. +** {F10211} The result codes shown here are the only ones returned +** by SQLite in its default configuration. {F10212} However, the +** [sqlite3_extended_result_codes()] API can be used to set a database +** connectoin to return more detailed result codes. {END} ** ** See also: [SQLITE_IOERR_READ | extended result codes] +** */ #define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ @@ -443,61 +329,51 @@ int sqlite3_exec( /* ** CAPI3REF: Extended Result Codes {F10220} -** KEYWORDS: {extended error code} {extended error codes} -** KEYWORDS: {extended result code} {extended result codes} ** ** In its default configuration, SQLite API routines return one of 26 integer -** [SQLITE_OK | result codes]. However, experience has shown that many of -** these result codes are too coarse-grained. They do not provide as +** [SQLITE_OK | result codes]. However, experience has shown that +** many of these result codes are too course-grained. They do not provide as ** much information about problems as programmers might like. In an effort to ** address this, newer versions of SQLite (version 3.3.8 and later) include ** support for additional result codes that provide more detailed information -** about errors. The extended result codes are enabled or disabled -** on a per database connection basis using the -** [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed here. -** One may expect the number of extended result codes will be expand -** over time. Software that uses extended result codes should expect -** to see new result codes in future releases of SQLite. +** about errors. {F10221} The extended result codes are enabled or disabled +** for each database connection using the [sqlite3_extended_result_codes()] +** API. {END} +** +** Some of the available extended result codes are listed above. +** We expect the number of extended result codes will be expand +** over time. {U10422} Software that uses extended result codes should expect +** to see new result codes in future releases of SQLite. {END} +** +** {F10223} The symbolic name for an extended result code always contains +** a related primary result code as a prefix. {F10224} Primary result +** codes contain a single "_" character. {F10225} Extended result codes +** contain two or more "_" characters. {F10226} The numeric value of an +** extended result code can be converted to its +** corresponding primary result code by masking off the lower 8 bytes. {END} ** ** The SQLITE_OK result code will never be extended. It will always ** be exactly zero. -** -** INVARIANTS: -** -** {F10223} The symbolic name for an extended result code shall contains -** a related primary result code as a prefix. -** -** {F10224} Primary result code names shall contain a single "_" character. -** -** {F10225} Extended result code names shall contain two or more "_" characters. -** -** {F10226} The numeric value of an extended result code shall contain the -** numeric value of its corresponding primary result code in -** its least significant 8 bits. */ -#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) -#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) -#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) -#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) -#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) -#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) -#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) -#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) -#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) -#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) -#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) -#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) -#define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) -#define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) +#define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) +#define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) +#define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) +#define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) +#define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) +#define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) +#define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) +#define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) +#define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) +#define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) +#define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) /* ** CAPI3REF: Flags For File Open Operations {F10230} ** -** These bit values are intended for use in the -** 3rd parameter to the [sqlite3_open_v2()] interface and -** in the 4th parameter to the xOpen method of the +** {F10231} Some combination of the these bit values are used as the +** third argument to the [sqlite3_open_v2()] interface and +** as fourth argument to the xOpen method of the ** [sqlite3_vfs] object. */ #define SQLITE_OPEN_READONLY 0x00000001 @@ -512,25 +388,24 @@ int sqlite3_exec( #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 -#define SQLITE_OPEN_NOMUTEX 0x00008000 /* ** CAPI3REF: Device Characteristics {F10240} ** -** The xDeviceCapabilities method of the [sqlite3_io_methods] +** {F10241} The xDeviceCapabilities method of the [sqlite3_io_methods] ** object returns an integer which is a vector of the these ** bit values expressing I/O characteristics of the mass storage ** device that holds the file that the [sqlite3_io_methods] -** refers to. +** refers to. {END} ** -** The SQLITE_IOCAP_ATOMIC property means that all writes of -** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values +** {F10242} The SQLITE_IOCAP_ATOMIC property means that all writes of +** any size are atomic. {F10243} The SQLITE_IOCAP_ATOMICnnn values ** mean that writes of blocks that are nnn bytes in size and ** are aligned to an address which is an integer multiple of -** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means +** nnn are atomic. {F10244} The SQLITE_IOCAP_SAFE_APPEND value means ** that when data is appended to a file, the data is appended ** first then the size of the file is extended, never the other -** way around. The SQLITE_IOCAP_SEQUENTIAL property means that +** way around. {F10245} The SQLITE_IOCAP_SEQUENTIAL property means that ** information is written to disk in the same order as calls ** to xWrite(). */ @@ -549,9 +424,9 @@ int sqlite3_exec( /* ** CAPI3REF: File Locking Levels {F10250} ** -** SQLite uses one of these integer values as the second +** {F10251} SQLite uses one of the following integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods -** of an [sqlite3_io_methods] object. +** of an [sqlite3_io_methods] object. {END} */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 @@ -562,20 +437,21 @@ int sqlite3_exec( /* ** CAPI3REF: Synchronization Type Flags {F10260} ** -** When SQLite invokes the xSync() method of an -** [sqlite3_io_methods] object it uses a combination of +** {F10261} When SQLite invokes the xSync() method of an +** [sqlite3_io_methods] object it uses a combination of the ** these integer values as the second argument. ** -** When the SQLITE_SYNC_DATAONLY flag is used, it means that the +** {F10262} When the SQLITE_SYNC_DATAONLY flag is used, it means that the ** sync operation only needs to flush data to mass storage. Inode -** information need not be flushed. The SQLITE_SYNC_NORMAL flag means -** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means +** information need not be flushed. {F10263} The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. {F10264} The SQLITE_SYNC_FULL flag means ** to use Mac OS-X style fullsync instead of fsync(). */ #define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 + /* ** CAPI3REF: OS Interface Open File Handle {F11110} ** @@ -594,18 +470,17 @@ struct sqlite3_file { /* ** CAPI3REF: OS Interface File Virtual Methods Object {F11120} ** -** Every file opened by the [sqlite3_vfs] xOpen method populates an -** [sqlite3_file] object (or, more commonly, a subclass of the -** [sqlite3_file] object) with a pointer to an instance of this object. -** This object defines the methods used to perform various operations -** against the open file represented by the [sqlite3_file] object. +** Every file opened by the [sqlite3_vfs] xOpen method contains a pointer to +** an instance of the this object. This object defines the +** methods used to perform various operations against the open file. ** ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync(). -** The second choice is a Mac OS-X style fullsync. The [SQLITE_SYNC_DATAONLY] -** flag may be ORed in to indicate that only the data of the file -** and not its inode needs to be synced. -** +* The second choice is an +** OS-X style fullsync. The SQLITE_SYNC_DATA flag may be ORed in to +** indicate that only the data of the file and not its inode needs to be +** synced. +** ** The integer values to xLock() and xUnlock() are one of **
        **
      • [SQLITE_LOCK_NONE], @@ -614,24 +489,26 @@ struct sqlite3_file { **
      • [SQLITE_LOCK_PENDING], or **
      • [SQLITE_LOCK_EXCLUSIVE]. **
      -** xLock() increases the lock. xUnlock() decreases the lock. -** The xCheckReservedLock() method checks whether any database connection, -** either in this process or in some other process, is holding a RESERVED, +** xLock() increases the lock. xUnlock() decreases the lock. +** The xCheckReservedLock() method looks +** to see if any database connection, either in this +** process or in some other process, is holding an RESERVED, ** PENDING, or EXCLUSIVE lock on the file. It returns true -** if such a lock exists and false otherwise. -** +** if such a lock exists and false if not. +** ** The xFileControl() method is a generic interface that allows custom ** VFS implementations to directly control an open file using the -** [sqlite3_file_control()] interface. The second "op" argument is an -** integer opcode. The third argument is a generic pointer intended to -** point to a structure that may contain arguments or space in which to +** [sqlite3_file_control()] interface. The second "op" argument +** is an integer opcode. The third +** argument is a generic pointer which is intended to be a pointer +** to a structure that may contain arguments or space in which to ** write return values. Potential uses for xFileControl() might be ** functions to enable blocking locks with timeouts, to change the ** locking strategy (for example to use dot-file locks), to inquire ** about the status of a lock, or to break stale locks. The SQLite -** core reserves all opcodes less than 100 for its own use. +** core reserves opcodes less than 100 for its own use. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available. -** Applications that define a custom xFileControl method should use opcodes +** Applications that define a custom xFileControl method should use opcodes ** greater than 100 to avoid conflicts. ** ** The xSectorSize() method returns the sector size of the @@ -677,7 +554,7 @@ struct sqlite3_io_methods { int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize); int (*xLock)(sqlite3_file*, int); int (*xUnlock)(sqlite3_file*, int); - int (*xCheckReservedLock)(sqlite3_file*, int *pResOut); + int (*xCheckReservedLock)(sqlite3_file*); int (*xFileControl)(sqlite3_file*, int op, void *pArg); int (*xSectorSize)(sqlite3_file*); int (*xDeviceCharacteristics)(sqlite3_file*); @@ -688,14 +565,14 @@ struct sqlite3_io_methods { ** CAPI3REF: Standard File Control Opcodes {F11310} ** ** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()] +** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] ** interface. ** -** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This -** opcode causes the xFileControl method to write the current state of +** {F11311} The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This +** opcode cases the xFileControl method to write the current state of ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED], ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE]) -** into an integer that the pArg argument points to. This capability +** into an integer that the pArg argument points to. {F11312} This capability ** is used during testing and only needs to be supported when SQLITE_TEST ** is defined. */ @@ -705,8 +582,8 @@ struct sqlite3_io_methods { ** CAPI3REF: Mutex Handle {F17110} ** ** The mutex module within SQLite defines [sqlite3_mutex] to be an -** abstract type for a mutex object. The SQLite core never looks -** at the internal representation of an [sqlite3_mutex]. It only +** abstract type for a mutex object. {F17111} The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. {END} It only ** deals with pointers to the [sqlite3_mutex] object. ** ** Mutexes are created using [sqlite3_mutex_alloc()]. @@ -716,29 +593,25 @@ typedef struct sqlite3_mutex sqlite3_mutex; /* ** CAPI3REF: OS Interface Object {F11140} ** -** An instance of the sqlite3_vfs object defines the interface between -** the SQLite core and the underlying operating system. The "vfs" +** An instance of this object defines the interface between the +** SQLite core and the underlying operating system. The "vfs" ** in the name of the object stands for "virtual file system". ** -** The value of the iVersion field is initially 1 but may be larger in -** future versions of SQLite. Additional fields may be appended to this -** object when the iVersion value is increased. Note that the structure -** of the sqlite3_vfs object changes in the transaction between -** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not -** modified. +** The iVersion field is initially 1 but may be larger for future +** versions of SQLite. Additional fields may be appended to this +** object when the iVersion value is increased. ** ** The szOsFile field is the size of the subclassed [sqlite3_file] ** structure used by this VFS. mxPathname is the maximum length of ** a pathname in this VFS. ** -** Registered sqlite3_vfs objects are kept on a linked list formed by +** Registered vfs modules are kept on a linked list formed by ** the pNext pointer. The [sqlite3_vfs_register()] ** and [sqlite3_vfs_unregister()] interfaces manage this list ** in a thread-safe way. The [sqlite3_vfs_find()] interface -** searches the list. Neither the application code nor the VFS -** implementation should use the pNext pointer. +** searches the list. ** -** The pNext field is the only field in the sqlite3_vfs +** The pNext field is the only fields in the sqlite3_vfs ** structure that SQLite will ever modify. SQLite will only access ** or modify this field while holding a particular static mutex. ** The application should never modify anything within the sqlite3_vfs @@ -747,28 +620,23 @@ typedef struct sqlite3_mutex sqlite3_mutex; ** The zName field holds the name of the VFS module. The name must ** be unique across all VFS modules. ** -** {F11141} SQLite will guarantee that the zFilename parameter to xOpen -** is either a NULL pointer or string obtained -** from xFullPathname(). SQLite further guarantees that -** the string will be valid and unchanged until xClose() is -** called. {END} Becasue of the previous sentense, -** the [sqlite3_file] can safely store a pointer to the +** {F11141} SQLite will guarantee that the zFilename string passed to +** xOpen() is a full pathname as generated by xFullPathname() and +** that the string will be valid and unchanged until xClose() is +** called. {END} So the [sqlite3_file] can store a pointer to the ** filename if it needs to remember the filename for some reason. -** If the zFilename parameter is xOpen is a NULL pointer then xOpen -** must invite its own temporary name for the file. Whenever the -** xFilename parameter is NULL it will also be the case that the -** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE]. ** ** {F11142} The flags argument to xOpen() includes all bits set in ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()] ** or [sqlite3_open16()] is used, then flags includes at least ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. {END} ** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set. -** +** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be +** set. +** ** {F11143} SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: -** +** **
        **
      • [SQLITE_OPEN_MAIN_DB] **
      • [SQLITE_OPEN_MAIN_JOURNAL] @@ -780,56 +648,59 @@ typedef struct sqlite3_mutex sqlite3_mutex; **
      {END} ** ** The file I/O implementation can use the object type flags to -** change the way it deals with files. For example, an application -** that does not care about crash recovery or rollback might make -** the open of a journal file a no-op. Writes to this journal would -** also be no-ops, and any attempt to read the journal would return -** SQLITE_IOERR. Or the implementation might recognize that a database -** file will be doing page-aligned sector reads and writes in a random -** order and set up its I/O subsystem accordingly. -** -** SQLite might also add one of the following flags to the xOpen method: -** +** changes the way it deals with files. For example, an application +** that does not care about crash recovery or rollback, might make +** the open of a journal file a no-op. Writes to this journal are +** also a no-op. Any attempt to read the journal return SQLITE_IOERR. +** Or the implementation might recognize the a database file will +** be doing page-aligned sector reads and writes in a random order +** and set up its I/O subsystem accordingly. +** +** {F11144} SQLite might also add one of the following flags to the xOpen +** method: +** **
        **
      • [SQLITE_OPEN_DELETEONCLOSE] **
      • [SQLITE_OPEN_EXCLUSIVE] **
      -** +** ** {F11145} The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be ** deleted when it is closed. {F11146} The [SQLITE_OPEN_DELETEONCLOSE] -** will be set for TEMP databases, journals and for subjournals. -** +** will be set for TEMP databases, journals and for subjournals. ** {F11147} The [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened ** for exclusive access. This flag is set for all files except -** for the main database file. -** -** {F11148} At least szOsFile bytes of memory are allocated by SQLite -** to hold the [sqlite3_file] structure passed as the third -** argument to xOpen. {END} The xOpen method does not have to +** for the main database file. {END} +** +** {F11148} At least szOsFile bytes of memory is allocated by SQLite +** to hold the [sqlite3_file] structure passed as the third +** argument to xOpen. {END} The xOpen method does not have to ** allocate the structure; it should just fill it in. -** -** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] -** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to -** test whether a file is readable and writable, or [SQLITE_ACCESS_READ] -** to test whether a file is at least readable. {END} The file can be a +** +** {F11149} The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** to test for the existance of a file, +** or [SQLITE_ACCESS_READWRITE] to test to see +** if a file is readable and writable, or [SQLITE_ACCESS_READ] +** to test to see if a file is at least readable. {END} The file can be a ** directory. -** -** {F11150} SQLite will always allocate at least mxPathname+1 bytes for the -** output buffer xFullPathname. {F11151} The exact size of the output buffer -** is also passed as a parameter to both methods. {END} If the output buffer -** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is -** handled as a fatal error by SQLite, vfs implementations should endeavor -** to prevent this by setting mxPathname to a sufficiently large value. -** +** +** {F11150} SQLite will always allocate at least mxPathname+1 byte for +** the output buffers for xGetTempname and xFullPathname. {F11151} The exact +** size of the output buffer is also passed as a parameter to both +** methods. {END} If the output buffer is not large enough, SQLITE_CANTOPEN +** should be returned. As this is handled as a fatal error by SQLite, +** vfs implementations should endeavor to prevent this by setting +** mxPathname to a sufficiently large value. +** ** The xRandomness(), xSleep(), and xCurrentTime() interfaces ** are not strictly a part of the filesystem, but they are ** included in the VFS structure for completeness. ** The xRandomness() function attempts to return nBytes bytes ** of good-quality randomness into zOut. The return value is -** the actual number of bytes of randomness obtained. -** The xSleep() method causes the calling thread to sleep for at +** the actual number of bytes of randomness obtained. The +** xSleep() method cause the calling thread to sleep for at ** least the number of microseconds given. The xCurrentTime() -** method returns a Julian Day Number for the current date and time. +** method returns a Julian Day Number for the current date and +** time. */ typedef struct sqlite3_vfs sqlite3_vfs; struct sqlite3_vfs { @@ -842,7 +713,8 @@ struct sqlite3_vfs { int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*, int flags, int *pOutFlags); int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir); - int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut); + int (*xAccess)(sqlite3_vfs*, const char *zName, int flags); + int (*xGetTempname)(sqlite3_vfs*, int nOut, char *zOut); int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut); void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename); void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg); @@ -851,7 +723,6 @@ struct sqlite3_vfs { int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut); int (*xSleep)(sqlite3_vfs*, int microseconds); int (*xCurrentTime)(sqlite3_vfs*, double*); - int (*xGetLastError)(sqlite3_vfs*, int, char *); /* New fields may be appended in figure versions. The iVersion ** value will increment whenever this happens. */ }; @@ -861,528 +732,164 @@ struct sqlite3_vfs { ** ** {F11191} These integer constants can be used as the third parameter to ** the xAccess method of an [sqlite3_vfs] object. {END} They determine -** what kind of permissions the xAccess method is looking for. -** {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks whether the file exists. -** {F11193} With SQLITE_ACCESS_READWRITE, the xAccess method -** checks whether the file is both readable and writable. -** {F11194} With SQLITE_ACCESS_READ, the xAccess method -** checks whether the file is readable. +** the kind of what kind of permissions the xAccess method is +** looking for. {F11192} With SQLITE_ACCESS_EXISTS, the xAccess method +** simply checks to see if the file exists. {F11193} With +** SQLITE_ACCESS_READWRITE, the xAccess method checks to see +** if the file is both readable and writable. {F11194} With +** SQLITE_ACCESS_READ the xAccess method +** checks to see if the file is readable. */ #define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 #define SQLITE_ACCESS_READ 2 -/* -** CAPI3REF: Initialize The SQLite Library {F10130} -** -** The sqlite3_initialize() routine initializes the -** SQLite library. The sqlite3_shutdown() routine -** deallocates any resources that were allocated by sqlite3_initialize(). -** -** A call to sqlite3_initialize() is an "effective" call if it is -** the first time sqlite3_initialize() is invoked during the lifetime of -** the process, or if it is the first time sqlite3_initialize() is invoked -** following a call to sqlite3_shutdown(). Only an effective call -** of sqlite3_initialize() does any initialization. All other calls -** are harmless no-ops. -** -** Among other things, sqlite3_initialize() shall invoke -** sqlite3_os_init(). Similarly, sqlite3_shutdown() -** shall invoke sqlite3_os_end(). -** -** The sqlite3_initialize() routine returns SQLITE_OK on success. -** If for some reason, sqlite3_initialize() is unable to initialize -** the library (perhaps it is unable to allocate a needed resource such -** as a mutex) it returns an [error code] other than SQLITE_OK. -** -** The sqlite3_initialize() routine is called internally by many other -** SQLite interfaces so that an application usually does not need to -** invoke sqlite3_initialize() directly. For example, [sqlite3_open()] -** calls sqlite3_initialize() so the SQLite library will be automatically -** initialized when [sqlite3_open()] is called if it has not be initialized -** already. However, if SQLite is compiled with the SQLITE_OMIT_AUTOINIT -** compile-time option, then the automatic calls to sqlite3_initialize() -** are omitted and the application must call sqlite3_initialize() directly -** prior to using any other SQLite interface. For maximum portability, -** it is recommended that applications always invoke sqlite3_initialize() -** directly prior to using any other SQLite interface. Future releases -** of SQLite may require this. In other words, the behavior exhibited -** when SQLite is compiled with SQLITE_OMIT_AUTOINIT might become the -** default behavior in some future release of SQLite. -** -** The sqlite3_os_init() routine does operating-system specific -** initialization of the SQLite library. The sqlite3_os_end() -** routine undoes the effect of sqlite3_os_init(). Typical tasks -** performed by these routines include allocation or deallocation -** of static resources, initialization of global variables, -** setting up a default [sqlite3_vfs] module, or setting up -** a default configuration using [sqlite3_config()]. -** -** The application should never invoke either sqlite3_os_init() -** or sqlite3_os_end() directly. The application should only invoke -** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init() -** interface is called automatically by sqlite3_initialize() and -** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate -** implementations for sqlite3_os_init() and sqlite3_os_end() -** are built into SQLite when it is compiled for unix, windows, or os/2. -** When built for other platforms (using the SQLITE_OS_OTHER=1 compile-time -** option) the application must supply a suitable implementation for -** sqlite3_os_init() and sqlite3_os_end(). An application-supplied -** implementation of sqlite3_os_init() or sqlite3_os_end() -** must return SQLITE_OK on success and some other [error code] upon -** failure. -*/ -int sqlite3_initialize(void); -int sqlite3_shutdown(void); -int sqlite3_os_init(void); -int sqlite3_os_end(void); - -/* -** CAPI3REF: Configuring The SQLite Library {F10145} -** -** The sqlite3_config() interface is used to make global configuration -** changes to SQLite in order to tune SQLite to the specific needs of -** the application. The default configuration is recommended for most -** applications and so this routine is usually not necessary. It is -** provided to support rare applications with unusual needs. -** -** The sqlite3_config() interface is not threadsafe. The application -** must insure that no other SQLite interfaces are invoked by other -** threads while sqlite3_config() is running. Furthermore, sqlite3_config() -** may only be invoked prior to library initialization using -** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()]. -** Note, however, that sqlite3_config() can be called as part of the -** implementation of an application-defined [sqlite3_os_init()]. -** -** The first argument to sqlite3_config() is an integer -** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines -** what property of SQLite is to be configured. Subsequent arguments -** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option] -** in the first argument. -** -** When a configuration option is set, sqlite3_config() returns SQLITE_OK. -** If the option is unknown or SQLite is unable to set the option -** then this routine returns a non-zero [error code]. -** -** The sqlite3_config() interface is considered experimental in that -** new configuration options may be added in future releases and existing -** configuration options may be discontinued or modified. -*/ -int sqlite3_config(int, ...); - -/* -** CAPI3REF: Memory Allocation Routines {F10155} -** -** An instance of this object defines the interface between SQLite -** and low-level memory allocation routines. -** -** This object is used in only one place in the SQLite interface. -** A pointer to an instance of this object is the argument to -** [sqlite3_config()] when the configuration option is -** [SQLITE_CONFIG_MALLOC]. By creating an instance of this object -** and passing it to [sqlite3_config()] during configuration, an -** application can specify an alternative memory allocation subsystem -** for SQLite to use for all of its dynamic memory needs. -** -** Note that SQLite comes with a built-in memory allocator that is -** perfectly adequate for the overwhelming majority of applications -** and that this object is only useful to a tiny minority of applications -** with specialized memory allocation requirements. This object is -** also used during testing of SQLite in order to specify an alternative -** memory allocator that simulates memory out-of-memory conditions in -** order to verify that SQLite recovers gracefully from such -** conditions. -** -** The xMalloc, xFree, and xRealloc methods must work like the -** malloc(), free(), and realloc() functions from the standard library. -** -** xSize should return the allocated size of a memory allocation -** previously obtained from xMalloc or xRealloc. The allocated size -** is always at least as big as the requested size but may be larger. -** -** The xRoundup method returns what would be the allocated size of -** a memory allocation given a particular requested size. Most memory -** allocators round up memory allocations at least to the next multiple -** of 8. Some allocators round up to a larger multiple or to a power of 2. -** -** The xInit method initializes the memory allocator. (For example, -** it might allocate any require mutexes or initialize internal data -** structures. The xShutdown method is invoked (indirectly) by -** [sqlite3_shutdown()] and should deallocate any resources acquired -** by xInit. The pAppData pointer is used as the only parameter to -** xInit and xShutdown. -*/ -typedef struct sqlite3_mem_methods sqlite3_mem_methods; -struct sqlite3_mem_methods { - void *(*xMalloc)(int); /* Memory allocation function */ - void (*xFree)(void*); /* Free a prior allocation */ - void *(*xRealloc)(void*,int); /* Resize an allocation */ - int (*xSize)(void*); /* Return the size of an allocation */ - int (*xRoundup)(int); /* Round up request size to allocation size */ - int (*xInit)(void*); /* Initialize the memory allocator */ - void (*xShutdown)(void*); /* Deinitialize the memory allocator */ - void *pAppData; /* Argument to xInit() and xShutdown() */ -}; - -/* -** CAPI3REF: Configuration Options {F10160} -** -** These constants are the available integer configuration options that -** can be passed as the first argument to the [sqlite3_config()] interface. -** -** New configuration options may be added in future releases of SQLite. -** Existing configuration options might be discontinued. Applications -** should check the return code from [sqlite3_config()] to make sure that -** the call worked. The [sqlite3_config()] interface will return a -** non-zero [error code] if a discontinued or unsupported configuration option -** is invoked. -** -**
      -**
      SQLITE_CONFIG_SINGLETHREAD
      -**
      There are no arguments to this option. This option disables -** all mutexing and puts SQLite into a mode where it can only be used -** by a single thread.
      -** -**
      SQLITE_CONFIG_MULTITHREAD
      -**
      There are no arguments to this option. This option disables -** mutexing on [database connection] and [prepared statement] objects. -** The application is responsible for serializing access to -** [database connections] and [prepared statements]. But other mutexes -** are enabled so that SQLite will be safe to use in a multi-threaded -** environment.
      -** -**
      SQLITE_CONFIG_SERIALIZED
      -**
      There are no arguments to this option. This option enables -** all mutexes including the recursive -** mutexes on [database connection] and [prepared statement] objects. -** In this mode (which is the default when SQLite is compiled with -** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access -** to [database connections] and [prepared statements] so that the -** application is free to use the same [database connection] or the -** same [prepared statement] in different threads at the same time. -** -**

      This configuration option merely sets the default mutex -** behavior to serialize access to [database connections]. Individual -** [database connections] can override this setting -** using the [SQLITE_OPEN_NOMUTEX] flag to [sqlite3_open_v2()].

      -** -**
      SQLITE_CONFIG_MALLOC
      -**
      This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The argument specifies -** alternative low-level memory allocation routines to be used in place of -** the memory allocation routines built into SQLite.
      -** -**
      SQLITE_CONFIG_GETMALLOC
      -**
      This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods] -** structure is filled with the currently defined memory allocation routines. -** This option can be used to overload the default memory allocation -** routines with a wrapper that simulations memory allocation failure or -** tracks memory usage, for example.
      -** -**
      SQLITE_CONFIG_MEMSTATUS
      -**
      This option takes single boolean argument which enables or disables -** the collection of memory allocation statistics. When disabled, the -** following SQLite interfaces become non-operational: -**
        -**
      • [sqlite3_memory_used()] -**
      • [sqlite3_memory_highwater()] -**
      • [sqlite3_soft_heap_limit()] -**
      • sqlite3_memory_status() -**
      -**
      -** -**
      SQLITE_CONFIG_SCRATCH
      -**
      This option specifies a static memory buffer that SQLite can use for -** scratch memory. There are three arguments: A pointer to the memory, the -** size of each scratch buffer (sz), and the number of buffers (N). The sz -** argument must be a multiple of 16. The first -** argument should point to an allocation of at least (sz+4)*N bytes of memory. -** SQLite will use no more than one scratch buffer at once per thread, so -** N should be set to the expected maximum number of threads. The sz -** parameter should be 6 times the size of the largest database page size. -** Scratch buffers are used as part of the btree balance operation. If -** The btree balancer needs additional memory beyond what is provided by -** scratch buffers or if no scratch buffer space is specified, then SQLite -** goes to [sqlite3_malloc()] to obtain the memory it needs.
      -** -**
      SQLITE_CONFIG_PAGECACHE
      -**
      This option specifies a static memory buffer that SQLite can use for -** the database page cache. There are three arguments: A pointer to the -** memory, the size of each page buffer (sz), and the number of pages (N). -** The sz argument must be a power of two between 512 and 32768. The first -** argument should point to an allocation of at least (sz+4)*N bytes of memory. -** SQLite will use the memory provided by the first argument to satisfy its -** memory needs for the first N pages that it adds to cache. If additional -** page cache memory is needed beyond what is provided by this option, then -** SQLite goes to [sqlite3_malloc()] for the additional storage space.
      -** -**
      SQLITE_CONFIG_HEAP
      -**
      This option specifies a static memory buffer that SQLite will use -** for all of its dynamic memory allocation needs beyond those provided -** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE]. -** There are three arguments: A pointer to the memory, the number of -** bytes in the memory buffer, and the minimum allocation size. If -** the first pointer (the memory pointer) is NULL, then SQLite reverts -** to using its default memory allocator (the system malloc() implementation), -** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. If the -** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or -** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory -** allocator is engaged to handle all of SQLites memory allocation needs.
      -** -**
      SQLITE_CONFIG_MUTEX
      -**
      This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The argument specifies -** alternative low-level mutex routines to be used in place -** the mutex routines built into SQLite.
      -** -**
      SQLITE_CONFIG_GETMUTEX
      -**
      This option takes a single argument which is a pointer to an -** instance of the [sqlite3_mutex_methods] structure. The -** [sqlite3_mutex_methods] -** structure is filled with the currently defined mutex routines. -** This option can be used to overload the default mutex allocation -** routines with a wrapper used to track mutex usage for performance -** profiling or testing, for example.
      -*/ -#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ -#define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ -#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ -#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ -#define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */ -#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ -#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ -#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ -#define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ -#define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ - - /* ** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} ** -** The sqlite3_extended_result_codes() routine enables or disables the -** [extended result codes] feature of SQLite. The extended result -** codes are disabled by default for historical compatibility considerations. +** {F12201} The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature on a database +** connection if its 2nd parameter is +** non-zero or zero, respectively. {F12202} +** By default, SQLite API routines return one of only 26 integer +** [SQLITE_OK | result codes]. {F12203} When extended result codes +** are enabled by this routine, the repetoire of result codes can be +** much larger and can (hopefully) provide more detailed information +** about the cause of an error. ** -** INVARIANTS: -** -** {F12201} Each new [database connection] shall have the -** [extended result codes] feature disabled by default. -** -** {F12202} The [sqlite3_extended_result_codes(D,F)] interface shall enable -** [extended result codes] for the [database connection] D -** if the F parameter is true, or disable them if F is false. +** {F12204} The second argument is a boolean value that turns extended result +** codes on and off. {F12205} Extended result codes are off by default for +** backwards compatibility with older versions of SQLite. */ int sqlite3_extended_result_codes(sqlite3*, int onoff); /* ** CAPI3REF: Last Insert Rowid {F12220} ** -** Each entry in an SQLite table has a unique 64-bit signed -** integer key called the "rowid". The rowid is always available +** {F12221} Each entry in an SQLite table has a unique 64-bit signed +** integer key called the "rowid". {F12222} The rowid is always available ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those -** names are not also used by explicitly declared columns. If +** names are not also used by explicitly declared columns. {F12223} If ** the table has a column of type INTEGER PRIMARY KEY then that column -** is another alias for the rowid. +** is another an alias for the rowid. ** -** This routine returns the rowid of the most recent -** successful INSERT into the database from the [database connection] -** in the first argument. If no successful INSERTs -** have ever occurred on that database connection, zero is returned. +** {F12224} This routine returns the rowid of the most recent +** successful INSERT into the database from the database connection +** shown in the first argument. {F12225} If no successful inserts +** have ever occurred on this database connection, zero is returned. ** -** If an INSERT occurs within a trigger, then the rowid of the inserted -** row is returned by this routine as long as the trigger is running. -** But once the trigger terminates, the value returned by this routine -** reverts to the last value inserted before the trigger fired. +** {F12226} If an INSERT occurs within a trigger, then the rowid of the +** inserted row is returned by this routine as long as the trigger +** is running. {F12227} But once the trigger terminates, the value returned +** by this routine reverts to the last value inserted before the +** trigger fired. ** -** An INSERT that fails due to a constraint violation is not a -** successful INSERT and does not change the value returned by this -** routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, +** {F12228} An INSERT that fails due to a constraint violation is not a +** successful insert and does not change the value returned by this +** routine. {F12229} Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, ** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. When INSERT OR REPLACE +** routine when their insertion fails. {F12231} When INSERT OR REPLACE ** encounters a constraint violation, it does not fail. The ** INSERT continues to completion after deleting rows that caused ** the constraint problem so INSERT OR REPLACE will always change -** the return value of this interface. +** the return value of this interface. ** -** For the purposes of this routine, an INSERT is considered to -** be successful even if it is subsequently rolled back. -** -** INVARIANTS: -** -** {F12221} The [sqlite3_last_insert_rowid()] function returns the rowid -** of the most recent successful INSERT performed on the same -** [database connection] and within the same or higher level -** trigger context, or zero if there have been no qualifying inserts. -** -** {F12223} The [sqlite3_last_insert_rowid()] function returns the -** same value when called from the same trigger context -** immediately before and after a ROLLBACK. -** -** LIMITATIONS: -** -** {A12232} If a separate thread performs a new INSERT on the same -** database connection while the [sqlite3_last_insert_rowid()] -** function is running and thus changes the last insert rowid, -** then the value returned by [sqlite3_last_insert_rowid()] is -** unpredictable and might not equal either the old or the new -** last insert rowid. +** {UF12232} If another thread does a new insert on the same database connection +** while this routine is running and thus changes the last insert rowid, +** then the return value of this routine is undefined. */ sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* ** CAPI3REF: Count The Number Of Rows Modified {F12240} ** -** This function returns the number of database rows that were changed +** {F12241} This function returns the number of database rows that were changed ** or inserted or deleted by the most recently completed SQL statement -** on the [database connection] specified by the first parameter. -** Only changes that are directly specified by the INSERT, UPDATE, -** or DELETE statement are counted. Auxiliary changes caused by -** triggers are not counted. Use the [sqlite3_total_changes()] function +** on the connection specified by the first parameter. {F12242} Only +** changes that are directly specified by the INSERT, UPDATE, or +** DELETE statement are counted. Auxiliary changes caused by +** triggers are not counted. {F12243} Use the [sqlite3_total_changes()] function ** to find the total number of changes including changes caused by triggers. ** -** A "row change" is a change to a single row of a single table -** caused by an INSERT, DELETE, or UPDATE statement. Rows that -** are changed as side effects of REPLACE constraint resolution, -** rollback, ABORT processing, DROP TABLE, or by any other -** mechanisms do not count as direct row changes. -** -** A "trigger context" is a scope of execution that begins and -** ends with the script of a trigger. Most SQL statements are -** evaluated outside of any trigger. This is the "top level" -** trigger context. If a trigger fires from the top level, a -** new trigger context is entered for the duration of that one -** trigger. Subtriggers create subcontexts for their duration. -** -** Calling [sqlite3_exec()] or [sqlite3_step()] recursively does -** not create a new trigger context. -** -** This function returns the number of direct row changes in the -** most recent INSERT, UPDATE, or DELETE statement within the same -** trigger context. -** -** Thus, when called from the top level, this function returns the -** number of changes in the most recent INSERT, UPDATE, or DELETE -** that also occurred at the top level. Within the body of a trigger, -** the sqlite3_changes() interface can be called to find the number of +** {F12244} Within the body of a trigger, the sqlite3_changes() interface +** can be called to find the number of ** changes in the most recently completed INSERT, UPDATE, or DELETE ** statement within the body of the same trigger. -** However, the number returned does not include changes -** caused by subtriggers since those have their own context. ** -** SQLite implements the command "DELETE FROM table" without a WHERE clause -** by dropping and recreating the table. (This is much faster than going -** through and deleting individual elements from the table.) Because of this -** optimization, the deletions in "DELETE FROM table" are not row changes and -** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()] -** functions, regardless of the number of elements that were originally -** in the table. To get an accurate count of the number of rows deleted, use +** {F12245} All changes are counted, even if they are later undone by a +** ROLLBACK or ABORT. {F12246} Except, changes associated with creating and +** dropping tables are not counted. +** +** {F12247} If a callback invokes [sqlite3_exec()] or [sqlite3_step()] +** recursively, then the changes in the inner, recursive call are +** counted together with the changes in the outer call. +** +** {F12248} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going through and deleting individual elements from the +** table.) Because of this optimization, the change count for +** "DELETE FROM table" will be zero regardless of the number of elements +** that were originally in the table. {F12251} To get an accurate count +** of the number of rows deleted, use ** "DELETE FROM table WHERE 1" instead. ** -** INVARIANTS: -** -** {F12241} The [sqlite3_changes()] function shall return the number of -** row changes caused by the most recent INSERT, UPDATE, -** or DELETE statement on the same database connection and -** within the same or higher trigger context, or zero if there have -** not been any qualifying row changes. -** -** {F12243} Statements of the form "DELETE FROM tablename" with no -** WHERE clause shall cause subsequent calls to -** [sqlite3_changes()] to return zero, regardless of the -** number of rows originally in the table. -** -** LIMITATIONS: -** -** {A12252} If a separate thread makes changes on the same database connection -** while [sqlite3_changes()] is running then the value returned -** is unpredictable and not meaningful. +** {UF12252} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. */ int sqlite3_changes(sqlite3*); /* ** CAPI3REF: Total Number Of Rows Modified {F12260} +*** +** {F12261} This function returns the number of database rows that have been +** modified by INSERT, UPDATE or DELETE statements since the database handle +** was opened. {F12262} The count includes UPDATE, INSERT and DELETE +** statements executed as part of trigger programs. {F12263} All changes +** are counted as soon as the statement that makes them is completed +** (when the statement handle is passed to [sqlite3_reset()] or +** [sqlite3_finalize()]). {END} ** -** This function returns the number of row changes caused by INSERT, -** UPDATE or DELETE statements since the [database connection] was opened. -** The count includes all changes from all trigger contexts. However, -** the count does not include changes used to implement REPLACE constraints, -** do rollbacks or ABORT processing, or DROP table processing. -** The changes are counted as soon as the statement that makes them is -** completed (when the statement handle is passed to [sqlite3_reset()] or -** [sqlite3_finalize()]). +** See also the [sqlite3_change()] interface. ** -** SQLite implements the command "DELETE FROM table" without a WHERE clause -** by dropping and recreating the table. (This is much faster than going -** through and deleting individual elements from the table.) Because of this -** optimization, the deletions in "DELETE FROM table" are not row changes and -** will not be counted by the sqlite3_changes() or [sqlite3_total_changes()] -** functions, regardless of the number of elements that were originally -** in the table. To get an accurate count of the number of rows deleted, use +** {F12265} SQLite implements the command "DELETE FROM table" without +** a WHERE clause by dropping and recreating the table. (This is much +** faster than going +** through and deleting individual elements form the table.) Because of +** this optimization, the change count for "DELETE FROM table" will be +** zero regardless of the number of elements that were originally in the +** table. To get an accurate count of the number of rows deleted, use ** "DELETE FROM table WHERE 1" instead. ** -** See also the [sqlite3_changes()] interface. -** -** INVARIANTS: -** -** {F12261} The [sqlite3_total_changes()] returns the total number -** of row changes caused by INSERT, UPDATE, and/or DELETE -** statements on the same [database connection], in any -** trigger context, since the database connection was created. -** -** {F12263} Statements of the form "DELETE FROM tablename" with no -** WHERE clause shall not change the value returned -** by [sqlite3_total_changes()]. -** -** LIMITATIONS: -** -** {A12264} If a separate thread makes changes on the same database connection -** while [sqlite3_total_changes()] is running then the value -** returned is unpredictable and not meaningful. +** {U12264} If another thread makes changes on the same database connection +** while this routine is running then the return value of this routine +** is undefined. {END} */ int sqlite3_total_changes(sqlite3*); /* ** CAPI3REF: Interrupt A Long-Running Query {F12270} ** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. This routine is typically +** {F12271} This function causes any pending database operation to abort and +** return at its earliest opportunity. {END} This routine is typically ** called in response to a user action such as pressing "Cancel" ** or Ctrl-C where the user wants a long query operation to halt ** immediately. ** -** It is safe to call this routine from a thread different from the -** thread that is currently running the database operation. But it -** is not safe to call this routine with a [database connection] that +** {F12272} It is safe to call this routine from a thread different from the +** thread that is currently running the database operation. {U12273} But it +** is not safe to call this routine with a database connection that ** is closed or might close before sqlite3_interrupt() returns. ** -** If an SQL operation is very nearly finished at the time when -** sqlite3_interrupt() is called, then it might not have an opportunity -** to be interrupted and might continue to completion. -** -** An SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If the interrupted SQL operation is an INSERT, UPDATE, or DELETE -** that is inside an explicit transaction, then the entire transaction -** will be rolled back automatically. -** -** A call to sqlite3_interrupt() has no effect on SQL statements +** If an SQL is very nearly finished at the time when sqlite3_interrupt() +** is called, then it might not have an opportunity to be interrupted. +** It might continue to completion. +** {F12274} The SQL operation that is interrupted will return +** [SQLITE_INTERRUPT]. {F12275} If the interrupted SQL operation is an +** INSERT, UPDATE, or DELETE that is inside an explicit transaction, +** then the entire transaction will be rolled back automatically. +** {F12276} A call to sqlite3_interrupt() has no effect on SQL statements ** that are started after sqlite3_interrupt() returns. -** -** INVARIANTS: -** -** {F12271} The [sqlite3_interrupt()] interface will force all running -** SQL statements associated with the same database connection -** to halt after processing at most one additional row of data. -** -** {F12272} Any SQL statement that is interrupted by [sqlite3_interrupt()] -** will return [SQLITE_INTERRUPT]. -** -** LIMITATIONS: -** -** {A12279} If the database connection closes while [sqlite3_interrupt()] -** is running then bad things will likely happen. */ void sqlite3_interrupt(sqlite3*); @@ -1394,34 +901,21 @@ void sqlite3_interrupt(sqlite3*); ** if additional input is needed before sending the text into ** SQLite for parsing. These routines return true if the input string ** appears to be a complete SQL statement. A statement is judged to be -** complete if it ends with a semicolon token and is not a fragment of a -** CREATE TRIGGER statement. Semicolons that are embedded within -** string literals or quoted identifier names or comments are not -** independent tokens (they are part of the token in which they are -** embedded) and thus do not count as a statement terminator. +** complete if it ends with a semicolon and is not a fragment of a +** CREATE TRIGGER statement. These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. ** -** These routines do not parse the SQL statements thus -** will not detect syntactically incorrect SQL. -** -** INVARIANTS: -** -** {F10511} A successful evaluation of [sqlite3_complete()] or -** [sqlite3_complete16()] functions shall -** return a numeric 1 if and only if the last non-whitespace -** token in their input is a semicolon that is not in between -** the BEGIN and END of a CREATE TRIGGER statement. -** -** {F10512} If a memory allocation error occurs during an invocation -** of [sqlite3_complete()] or [sqlite3_complete16()] then the -** routine shall return [SQLITE_NOMEM]. -** -** LIMITATIONS: -** -** {A10512} The input to [sqlite3_complete()] must be a zero-terminated -** UTF-8 string. -** -** {A10513} The input to [sqlite3_complete16()] must be a zero-terminated -** UTF-16 string in native byte order. +** {F10511} These functions return true if the given input string +** ends with a semicolon optionally followed by whitespace or +** comments. {F10512} For sqlite3_complete(), +** the parameter must be a zero-terminated UTF-8 string. {F10513} For +** sqlite3_complete16(), a zero-terminated machine byte order UTF-16 string +** is required. {F10514} These routines return false if the terminal +** semicolon is within a comment, a string literal or a quoted identifier +** (in other words if the final semicolon is not really a separate token +** but part of a larger token) or if the final semicolon is +** in between the BEGIN and END keywords of a CREATE TRIGGER statement. +** {END} */ int sqlite3_complete(const char *sql); int sqlite3_complete16(const void *sql); @@ -1429,27 +923,29 @@ int sqlite3_complete16(const void *sql); /* ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} ** -** This routine sets a callback function that might be invoked whenever -** an attempt is made to open a database table that another thread -** or process has locked. -** -** If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] -** is returned immediately upon encountering the lock. If the busy callback -** is not NULL, then the callback will be invoked with two arguments. -** -** The first argument to the handler is a copy of the void* pointer which -** is the third argument to sqlite3_busy_handler(). The second argument to -** the handler callback is the number of times that the busy handler has -** been invoked for this locking event. If the +** {F12311} This routine identifies a callback function that might be +** invoked whenever an attempt is made to open a database table +** that another thread or process has locked. +** {F12312} If the busy callback is NULL, then [SQLITE_BUSY] +** or [SQLITE_IOERR_BLOCKED] +** is returned immediately upon encountering the lock. +** {F12313} If the busy callback is not NULL, then the +** callback will be invoked with two arguments. {F12314} The +** first argument to the handler is a copy of the void* pointer which +** is the third argument to this routine. {F12315} The second argument to +** the handler is the number of times that the busy handler has +** been invoked for this locking event. {F12316} If the ** busy callback returns 0, then no additional attempts are made to ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned. -** If the callback returns non-zero, then another attempt +** {F12317} If the callback returns non-zero, then another attempt ** is made to open the database for reading and the cycle repeats. ** -** The presence of a busy handler does not guarantee that it will be invoked -** when there is lock contention. If SQLite determines that invoking the busy -** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY] -** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler. +** The presence of a busy handler does not guarantee that +** it will be invoked when there is lock contention. {F12319} +** If SQLite determines that invoking the busy handler could result in +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. {END} ** Consider a scenario where one process is holding a read lock that ** it is trying to promote to a reserved lock and ** a second process is holding a reserved lock that it is trying @@ -1461,118 +957,74 @@ int sqlite3_complete16(const void *sql); ** will induce the first process to release its read lock and allow ** the second process to proceed. ** -** The default busy callback is NULL. +** {F12321} The default busy callback is NULL. {END} ** -** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] +** {F12322} The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] ** when SQLite is in the middle of a large transaction where all the -** changes will not fit into the in-memory cache. SQLite will +** changes will not fit into the in-memory cache. {F12323} SQLite will ** already hold a RESERVED lock on the database file, but it needs ** to promote this lock to EXCLUSIVE so that it can spill cache ** pages into the database file without harm to concurrent -** readers. If it is unable to promote the lock, then the in-memory +** readers. {F12324} If it is unable to promote the lock, then the in-memory ** cache will be left in an inconsistent state and so the error ** code is promoted from the relatively benign [SQLITE_BUSY] to -** the more severe [SQLITE_IOERR_BLOCKED]. This error code promotion -** forces an automatic rollback of the changes. See the -** +** the more severe [SQLITE_IOERR_BLOCKED]. {F12325} This error code promotion +** forces an automatic rollback of the changes. {END} See the +** ** CorruptionFollowingBusyError wiki page for a discussion of why ** this is important. +** +** {F12326} Sqlite is re-entrant, so the busy handler may start a new +** query. {END} (It is not clear why anyone would every want to do this, +** but it is allowed, in theory.) {U12327} But the busy handler may not +** close the database. Closing the database from a busy handler will delete +** data structures out from under the executing query and will +** probably result in a segmentation fault or other runtime error. {END} ** -** There can only be a single busy handler defined for each -** [database connection]. Setting a new busy handler clears any -** previously set handler. Note that calling [sqlite3_busy_timeout()] -** will also set or clear the busy handler. +** {F12328} There can only be a single busy handler defined for each database +** connection. Setting a new busy handler clears any previous one. +** {F12329} Note that calling [sqlite3_busy_timeout()] will also set or clear +** the busy handler. ** -** INVARIANTS: -** -** {F12311} The [sqlite3_busy_handler(D,C,A)] function shall replace -** busy callback in the [database connection] D with a new -** a new busy handler C and application data pointer A. -** -** {F12312} Newly created [database connections] shall have a busy -** handler of NULL. -** -** {F12314} When two or more [database connections] share a -** [sqlite3_enable_shared_cache | common cache], -** the busy handler for the database connection currently using -** the cache shall be invoked when the cache encounters a lock. -** -** {F12316} If a busy handler callback returns zero, then the SQLite interface -** that provoked the locking event shall return [SQLITE_BUSY]. -** -** {F12318} SQLite shall invokes the busy handler with two arguments which -** are a copy of the pointer supplied by the 3rd parameter to -** [sqlite3_busy_handler()] and a count of the number of prior -** invocations of the busy handler for the same locking event. -** -** LIMITATIONS: -** -** {A12319} A busy handler must not close the database connection -** or [prepared statement] that invoked the busy handler. +** {F12331} When operating in [sqlite3_enable_shared_cache | shared cache mode], +** only a single busy handler can be defined for each database file. +** So if two database connections share a single cache, then changing +** the busy handler on one connection will also change the busy +** handler in the other connection. {F12332} The busy handler is invoked +** in the thread that was running when the lock contention occurs. */ int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); /* ** CAPI3REF: Set A Busy Timeout {F12340} ** -** This routine sets a [sqlite3_busy_handler | busy handler] that sleeps -** for a specified amount of time when a table is locked. The handler -** will sleep multiple times until at least "ms" milliseconds of sleeping -** have accumulated. {F12343} After "ms" milliseconds of sleeping, -** the handler returns 0 which causes [sqlite3_step()] to return -** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. +** {F12341} This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a +** table is locked. {F12342} The handler will sleep multiple times until +** at least "ms" milliseconds of sleeping have been done. {F12343} After +** "ms" milliseconds of sleeping, the handler returns 0 which +** causes [sqlite3_step()] to return [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]. ** -** Calling this routine with an argument less than or equal to zero +** {F12344} Calling this routine with an argument less than or equal to zero ** turns off all busy handlers. ** -** There can only be a single busy handler for a particular -** [database connection] any any given moment. If another busy handler -** was defined (using [sqlite3_busy_handler()]) prior to calling +** {F12345} There can only be a single busy handler for a particular database +** connection. If another busy handler was defined +** (using [sqlite3_busy_handler()]) prior to calling ** this routine, that other busy handler is cleared. -** -** INVARIANTS: -** -** {F12341} The [sqlite3_busy_timeout()] function shall override any prior -** [sqlite3_busy_timeout()] or [sqlite3_busy_handler()] setting -** on the same [database connection]. -** -** {F12343} If the 2nd parameter to [sqlite3_busy_timeout()] is less than -** or equal to zero, then the busy handler shall be cleared so that -** all subsequent locking events immediately return [SQLITE_BUSY]. -** -** {F12344} If the 2nd parameter to [sqlite3_busy_timeout()] is a positive -** number N, then a busy handler shall be set that repeatedly calls -** the xSleep() method in the [sqlite3_vfs | VFS interface] until -** either the lock clears or until the cumulative sleep time -** reported back by xSleep() exceeds N milliseconds. */ int sqlite3_busy_timeout(sqlite3*, int ms); /* ** CAPI3REF: Convenience Routines For Running Queries {F12370} ** -** Definition: A result table is memory data structure created by the -** [sqlite3_get_table()] interface. A result table records the -** complete query results from one or more queries. +** This next routine is a convenience wrapper around [sqlite3_exec()]. +** {F12371} Instead of invoking a user-supplied callback for each row of the +** result, this routine remembers each row of the result in memory +** obtained from [sqlite3_malloc()], then returns all of the result after the +** query has finished. {F12372} ** -** The table conceptually has a number of rows and columns. But -** these numbers are not part of the result table itself. These -** numbers are obtained separately. Let N be the number of rows -** and M be the number of columns. -** -** A result table is an array of pointers to zero-terminated UTF-8 strings. -** There are (N+1)*M elements in the array. The first M pointers point -** to zero-terminated strings that contain the names of the columns. -** The remaining entries all point to query results. NULL values result -** in NULL pointers. All other values are in their UTF-8 zero-terminated -** string representation as returned by [sqlite3_column_text()]. -** -** A result table might consist of one or more memory allocations. -** It is not safe to pass a result table directly to [sqlite3_free()]. -** A result table should be deallocated using [sqlite3_free_table()]. -** -** As an example of the result table format, suppose a query result -** is as follows: +** As an example, suppose the query result where this table: ** **
       **        Name        | Age
      @@ -1582,9 +1034,8 @@ int sqlite3_busy_timeout(sqlite3*, int ms);
       **        Cindy       | 21
       ** 
      ** -** There are two column (M==2) and three rows (N==3). Thus the -** result table has 8 entries. Suppose the result table is stored -** in an array names azResult. Then azResult holds this content: +** If the 3rd argument were &azResult then after the function returns +** azResult will contain the following data: ** **
       **        azResult[0] = "Name";
      @@ -1597,65 +1048,28 @@ int sqlite3_busy_timeout(sqlite3*, int ms);
       **        azResult[7] = "21";
       ** 
      ** -** The sqlite3_get_table() function evaluates one or more -** semicolon-separated SQL statements in the zero-terminated UTF-8 -** string of its 2nd parameter. It returns a result table to the -** pointer given in its 3rd parameter. +** Notice that there is an extra row of data containing the column +** headers. But the *nrow return value is still 3. *ncolumn is +** set to 2. In general, the number of values inserted into azResult +** will be ((*nrow) + 1)*(*ncolumn). ** -** After the calling function has finished using the result, it should -** pass the pointer to the result table to sqlite3_free_table() in order to -** release the memory that was malloced. Because of the way the -** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling -** function must not try to call [sqlite3_free()] directly. Only -** [sqlite3_free_table()] is able to release the memory properly and safely. +** {U12374} After the calling function has finished using the result, it should +** pass the result data pointer to sqlite3_free_table() in order to +** release the memory that was malloc-ed. Because of the way the +** [sqlite3_malloc()] happens, the calling function must not try to call +** [sqlite3_free()] directly. Only [sqlite3_free_table()] is able to release +** the memory properly and safely. {END} ** -** The sqlite3_get_table() interface is implemented as a wrapper around -** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access -** to any internal data structures of SQLite. It uses only the public -** interface defined here. As a consequence, errors that occur in the -** wrapper layer outside of the internal [sqlite3_exec()] call are not -** reflected in subsequent calls to [sqlite3_errcode()] or [sqlite3_errmsg()]. -** -** INVARIANTS: -** -** {F12371} If a [sqlite3_get_table()] fails a memory allocation, then -** it shall free the result table under construction, abort the -** query in process, skip any subsequent queries, set the -** *pazResult output pointer to NULL and return [SQLITE_NOMEM]. -** -** {F12373} If the pnColumn parameter to [sqlite3_get_table()] is not NULL -** then a successful invocation of [sqlite3_get_table()] shall -** write the number of columns in the -** result set of the query into *pnColumn. -** -** {F12374} If the pnRow parameter to [sqlite3_get_table()] is not NULL -** then a successful invocation of [sqlite3_get_table()] shall -** writes the number of rows in the -** result set of the query into *pnRow. -** -** {F12376} A successful invocation of [sqlite3_get_table()] that computes -** N rows of result with C columns per row shall make *pazResult -** point to an array of pointers to (N+1)*C strings where the first -** C strings are column names as obtained from -** [sqlite3_column_name()] and the rest are column result values -** obtained from [sqlite3_column_text()]. -** -** {F12379} The values in the pazResult array returned by [sqlite3_get_table()] -** shall remain valid until cleared by [sqlite3_free_table()]. -** -** {F12382} When an error occurs during evaluation of [sqlite3_get_table()] -** the function shall set *pazResult to NULL, write an error message -** into memory obtained from [sqlite3_malloc()], make -** **pzErrmsg point to that error message, and return a -** appropriate [error code]. +** {F12373} The return value of this routine is the same as +** from [sqlite3_exec()]. */ int sqlite3_get_table( - sqlite3 *db, /* An open database */ - const char *zSql, /* SQL to be evaluated */ - char ***pazResult, /* Results of the query */ - int *pnRow, /* Number of result rows written here */ - int *pnColumn, /* Number of result columns written here */ - char **pzErrmsg /* Error msg written here */ + sqlite3*, /* An open database */ + const char *sql, /* SQL to be executed */ + char ***resultp, /* Result written to a char *[] that this points to */ + int *nrow, /* Number of result rows written here */ + int *ncolumn, /* Number of result columns written here */ + char **errmsg /* Error msg written here */ ); void sqlite3_free_table(char **result); @@ -1665,44 +1079,44 @@ void sqlite3_free_table(char **result); ** These routines are workalikes of the "printf()" family of functions ** from the standard C library. ** -** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their +** {F17401} The sqlite3_mprintf() and sqlite3_vmprintf() routines write their ** results into memory obtained from [sqlite3_malloc()]. -** The strings returned by these two routines should be -** released by [sqlite3_free()]. Both routines return a +** {U17402} The strings returned by these two routines should be +** released by [sqlite3_free()]. {F17403} Both routines return a ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough ** memory to hold the resulting string. ** -** In sqlite3_snprintf() routine is similar to "snprintf()" from +** {F17404} In sqlite3_snprintf() routine is similar to "snprintf()" from ** the standard C library. The result is written into the ** buffer supplied as the second parameter whose size is given by -** the first parameter. Note that the order of the +** the first parameter. {END} Note that the order of the ** first two parameters is reversed from snprintf(). This is an ** historical accident that cannot be fixed without breaking -** backwards compatibility. Note also that sqlite3_snprintf() +** backwards compatibility. {F17405} Note also that sqlite3_snprintf() ** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. We admit that +** characters actually written into the buffer. {END} We admit that ** the number of characters written would be a more useful return ** value but we cannot change the implementation of sqlite3_snprintf() ** now without breaking compatibility. ** -** As long as the buffer size is greater than zero, sqlite3_snprintf() -** guarantees that the buffer is always zero-terminated. The first +** {F17406} As long as the buffer size is greater than zero, sqlite3_snprintf() +** guarantees that the buffer is always zero-terminated. {F17407} The first ** parameter "n" is the total size of the buffer, including space for -** the zero terminator. So the longest string that can be completely +** the zero terminator. {END} So the longest string that can be completely ** written will be n-1 characters. ** ** These routines all implement some additional formatting ** options that are useful for constructing SQL statements. -** All of the usual printf() formatting options apply. In addition, there +** All of the usual printf formatting options apply. In addition, there ** is are "%q", "%Q", and "%z" options. ** -** The %q option works like %s in that it substitutes a null-terminated +** {F17410} The %q option works like %s in that it substitutes a null-terminated ** string from the argument list. But %q also doubles every '\'' character. -** %q is designed for use inside a string literal. By doubling each '\'' +** %q is designed for use inside a string literal. {END} By doubling each '\'' ** character it escapes that character and allows it to be inserted into ** the string. ** -** For example, assume the string variable zText contains text as follows: +** For example, so some string variable contains text as follows: ** **
       **  char *zText = "It's a happy day!";
      @@ -1730,13 +1144,14 @@ void sqlite3_free_table(char **result);
       **  INSERT INTO table1 VALUES('It's a happy day!');
       ** 
      ** -** This second example is an SQL syntax error. As a general rule you should -** always use %q instead of %s when inserting text into a string literal. +** This second example is an SQL syntax error. As a general rule you +** should always use %q instead of %s when inserting text into a string +** literal. ** -** The %Q option works like %q except it also adds single quotes around -** the outside of the total string. Additionally, if the parameter in the -** argument list is a NULL pointer, %Q substitutes the text "NULL" (without -** single quotes) in place of the %Q option. So, for example, one could say: +** {F17411} The %Q option works like %q except it also adds single quotes around +** the outside of the total string. Or if the parameter in the argument +** list is a NULL pointer, %Q substitutes the text "NULL" (without single +** quotes) in place of the %Q option. {END} So, for example, one could say: ** **
       **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
      @@ -1747,26 +1162,9 @@ void sqlite3_free_table(char **result);
       ** The code above will render a correct SQL statement in the zSQL
       ** variable even if the zText variable is a NULL pointer.
       **
      -** The "%z" formatting option works exactly like "%s" with the
      +** {F17412} The "%z" formatting option works exactly like "%s" with the
       ** addition that after the string has been read and copied into
       ** the result, [sqlite3_free()] is called on the input string. {END}
      -**
      -** INVARIANTS:
      -**
      -** {F17403}  The [sqlite3_mprintf()] and [sqlite3_vmprintf()] interfaces
      -**           return either pointers to zero-terminated UTF-8 strings held in
      -**           memory obtained from [sqlite3_malloc()] or NULL pointers if
      -**           a call to [sqlite3_malloc()] fails.
      -**
      -** {F17406}  The [sqlite3_snprintf()] interface writes a zero-terminated
      -**           UTF-8 string into the buffer pointed to by the second parameter
      -**           provided that the first parameter is greater than zero.
      -**
      -** {F17407}  The [sqlite3_snprintf()] interface does not write slots of
      -**           its output buffer (the second parameter) outside the range
      -**           of 0 through N-1 (where N is the first parameter)
      -**           regardless of the length of the string
      -**           requested by the format specification.
       */
       char *sqlite3_mprintf(const char*,...);
       char *sqlite3_vmprintf(const char*, va_list);
      @@ -1775,122 +1173,74 @@ char *sqlite3_snprintf(int,char*,const char*, ...);
       /*
       ** CAPI3REF: Memory Allocation Subsystem {F17300}
       **
      -** The SQLite core  uses these three routines for all of its own
      -** internal memory allocation needs. "Core" in the previous sentence
      +** {F17301} The SQLite core  uses these three routines for all of its own
      +** internal memory allocation needs. {END}  "Core" in the previous sentence
       ** does not include operating-system specific VFS implementation.  The
      -** Windows VFS uses native malloc() and free() for some operations.
      +** windows VFS uses native malloc and free for some operations.
       **
      -** The sqlite3_malloc() routine returns a pointer to a block
      +** {F17302} The sqlite3_malloc() routine returns a pointer to a block
       ** of memory at least N bytes in length, where N is the parameter.
      -** If sqlite3_malloc() is unable to obtain sufficient free
      -** memory, it returns a NULL pointer.  If the parameter N to
      +** {F17303} If sqlite3_malloc() is unable to obtain sufficient free
      +** memory, it returns a NULL pointer.  {F17304} If the parameter N to
       ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
       ** a NULL pointer.
       **
      -** Calling sqlite3_free() with a pointer previously returned
      +** {F17305} Calling sqlite3_free() with a pointer previously returned
       ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
      -** that it might be reused.  The sqlite3_free() routine is
      +** that it might be reused.  {F17306} The sqlite3_free() routine is
       ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
      -** to sqlite3_free() is harmless.  After being freed, memory
      +** to sqlite3_free() is harmless.  {U17307} After being freed, memory
       ** should neither be read nor written.  Even reading previously freed
       ** memory might result in a segmentation fault or other severe error.
      -** Memory corruption, a segmentation fault, or other severe error
      +** {U17309} Memory corruption, a segmentation fault, or other severe error
       ** might result if sqlite3_free() is called with a non-NULL pointer that
       ** was not obtained from sqlite3_malloc() or sqlite3_free().
       **
      -** The sqlite3_realloc() interface attempts to resize a
      +** {F17310} The sqlite3_realloc() interface attempts to resize a
       ** prior memory allocation to be at least N bytes, where N is the
       ** second parameter.  The memory allocation to be resized is the first
      -** parameter.  If the first parameter to sqlite3_realloc()
      +** parameter.  {F17311} If the first parameter to sqlite3_realloc()
       ** is a NULL pointer then its behavior is identical to calling
       ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
      -** If the second parameter to sqlite3_realloc() is zero or
      +** {F17312} If the second parameter to sqlite3_realloc() is zero or
       ** negative then the behavior is exactly the same as calling
       ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
      -** sqlite3_realloc() returns a pointer to a memory allocation
      +** {F17313} Sqlite3_realloc() returns a pointer to a memory allocation
       ** of at least N bytes in size or NULL if sufficient memory is unavailable.
      -** If M is the size of the prior allocation, then min(N,M) bytes
      +** {F17314} If M is the size of the prior allocation, then min(N,M) bytes
       ** of the prior allocation are copied into the beginning of buffer returned
       ** by sqlite3_realloc() and the prior allocation is freed.
      -** If sqlite3_realloc() returns NULL, then the prior allocation
      +** {F17315} If sqlite3_realloc() returns NULL, then the prior allocation
       ** is not freed.
       **
      -** The memory returned by sqlite3_malloc() and sqlite3_realloc()
      +** {F17316} The memory returned by sqlite3_malloc() and sqlite3_realloc()
       ** is always aligned to at least an 8 byte boundary. {END}
       **
      -** The default implementation of the memory allocation subsystem uses
      -** the malloc(), realloc() and free() provided by the standard C library.
      -** {F17382} However, if SQLite is compiled with the
      -** SQLITE_MEMORY_SIZE=NNN C preprocessor macro (where NNN
      -** is an integer), then SQLite create a static array of at least
      -** NNN bytes in size and uses that array for all of its dynamic
      -** memory allocation needs. {END}  Additional memory allocator options
      -** may be added in future releases.
      +** {F17381} The default implementation
      +** of the memory allocation subsystem uses the malloc(), realloc()
      +** and free() provided by the standard C library. {F17382} However, if 
      +** SQLite is compiled with the following C preprocessor macro
      +**
      +** 
      SQLITE_MEMORY_SIZE=NNN
      +** +** where NNN is an integer, then SQLite create a static +** array of at least NNN bytes in size and use that array +** for all of its dynamic memory allocation needs. {END} Additional +** memory allocator options may be added in future releases. ** ** In SQLite version 3.5.0 and 3.5.1, it was possible to define ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in ** implementation of these routines to be omitted. That capability -** is no longer provided. Only built-in memory allocators can be used. +** is no longer provided. Only built-in memory allocators can be +** used. ** -** The Windows OS interface layer calls +** The windows OS interface layer calls ** the system malloc() and free() directly when converting ** filenames between the UTF-8 encoding used by SQLite -** and whatever filename encoding is used by the particular Windows +** and whatever filename encoding is used by the particular windows ** installation. Memory allocation errors are detected, but ** they are reported back as [SQLITE_CANTOPEN] or ** [SQLITE_IOERR] rather than [SQLITE_NOMEM]. -** -** INVARIANTS: -** -** {F17303} The [sqlite3_malloc(N)] interface returns either a pointer to -** a newly checked-out block of at least N bytes of memory -** that is 8-byte aligned, or it returns NULL if it is unable -** to fulfill the request. -** -** {F17304} The [sqlite3_malloc(N)] interface returns a NULL pointer if -** N is less than or equal to zero. -** -** {F17305} The [sqlite3_free(P)] interface releases memory previously -** returned from [sqlite3_malloc()] or [sqlite3_realloc()], -** making it available for reuse. -** -** {F17306} A call to [sqlite3_free(NULL)] is a harmless no-op. -** -** {F17310} A call to [sqlite3_realloc(0,N)] is equivalent to a call -** to [sqlite3_malloc(N)]. -** -** {F17312} A call to [sqlite3_realloc(P,0)] is equivalent to a call -** to [sqlite3_free(P)]. -** -** {F17315} The SQLite core uses [sqlite3_malloc()], [sqlite3_realloc()], -** and [sqlite3_free()] for all of its memory allocation and -** deallocation needs. -** -** {F17318} The [sqlite3_realloc(P,N)] interface returns either a pointer -** to a block of checked-out memory of at least N bytes in size -** that is 8-byte aligned, or a NULL pointer. -** -** {F17321} When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first -** copies the first K bytes of content from P into the newly -** allocated block, where K is the lesser of N and the size of -** the buffer P. -** -** {F17322} When [sqlite3_realloc(P,N)] returns a non-NULL pointer, it first -** releases the buffer P. -** -** {F17323} When [sqlite3_realloc(P,N)] returns NULL, the buffer P is -** not modified or released. -** -** LIMITATIONS: -** -** {A17350} The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] -** must be either NULL or else pointers obtained from a prior -** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have -** not yet been released. -** -** {A17351} The application must not read or write any part of -** a block of memory after it has been released using -** [sqlite3_free()] or [sqlite3_realloc()]. */ void *sqlite3_malloc(int); void *sqlite3_realloc(void*, int); @@ -1899,173 +1249,94 @@ void sqlite3_free(void*); /* ** CAPI3REF: Memory Allocator Statistics {F17370} ** -** SQLite provides these two interfaces for reporting on the status -** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] -** routines, which form the built-in memory allocation subsystem. +** In addition to the basic three allocation routines +** [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()], +** the memory allocation subsystem included with the SQLite +** sources provides the interfaces shown here. ** -** INVARIANTS: -** -** {F17371} The [sqlite3_memory_used()] routine returns the number of bytes -** of memory currently outstanding (malloced but not freed). -** -** {F17373} The [sqlite3_memory_highwater()] routine returns the maximum -** value of [sqlite3_memory_used()] since the high-water mark -** was last reset. -** -** {F17374} The values returned by [sqlite3_memory_used()] and -** [sqlite3_memory_highwater()] include any overhead -** added by SQLite in its implementation of [sqlite3_malloc()], -** but not overhead added by the any underlying system library -** routines that [sqlite3_malloc()] may call. -** -** {F17375} The memory high-water mark is reset to the current value of -** [sqlite3_memory_used()] if and only if the parameter to -** [sqlite3_memory_highwater()] is true. The value returned -** by [sqlite3_memory_highwater(1)] is the high-water mark -** prior to the reset. +** {F17371} The sqlite3_memory_used() routine returns the +** number of bytes of memory currently outstanding (malloced but not freed). +** {F17372} The value returned by sqlite3_memory_used() includes +** any overhead added by SQLite, but not overhead added by the +** library malloc() that backs the sqlite3_malloc() implementation. +** {F17373} The sqlite3_memory_highwater() routines returns the +** maximum number of bytes that have been outstanding at any time +** since the highwater mark was last reset. +** {F17374} The byte count returned by sqlite3_memory_highwater() +** uses the same byte counting rules as sqlite3_memory_used(). {END} +** In other words, overhead added internally by SQLite is counted, +** but overhead from the underlying system malloc is not. +** {F17375} If the parameter to sqlite3_memory_highwater() is true, +** then the highwater mark is reset to the current value of +** sqlite3_memory_used() and the prior highwater mark (before the +** reset) is returned. {F17376} If the parameter to +** sqlite3_memory_highwater() is zero, then the highwater mark is +** unchanged. */ sqlite3_int64 sqlite3_memory_used(void); sqlite3_int64 sqlite3_memory_highwater(int resetFlag); -/* -** CAPI3REF: Pseudo-Random Number Generator {F17390} -** -** SQLite contains a high-quality pseudo-random number generator (PRNG) used to -** select random ROWIDs when inserting new records into a table that -** already uses the largest possible ROWID. The PRNG is also used for -** the build-in random() and randomblob() SQL functions. This interface allows -** applications to access the same PRNG for other purposes. -** -** A call to this routine stores N bytes of randomness into buffer P. -** -** The first time this routine is invoked (either internally or by -** the application) the PRNG is seeded using randomness obtained -** from the xRandomness method of the default [sqlite3_vfs] object. -** On all subsequent invocations, the pseudo-randomness is generated -** internally and without recourse to the [sqlite3_vfs] xRandomness -** method. -** -** INVARIANTS: -** -** {F17392} The [sqlite3_randomness(N,P)] interface writes N bytes of -** high-quality pseudo-randomness into buffer P. -*/ -void sqlite3_randomness(int N, void *P); - /* ** CAPI3REF: Compile-Time Authorization Callbacks {F12500} ** -** This routine registers a authorizer callback with a particular -** [database connection], supplied in the first argument. +** {F12501} This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. {F12502} ** The authorizer callback is invoked as SQL statements are being compiled ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()], -** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. At various +** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. {F12503} At various ** points during the compilation process, as logic is being created ** to perform various actions, the authorizer callback is invoked to ** see if those actions are allowed. The authorizer callback should -** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the +** return SQLITE_OK to allow the action, [SQLITE_IGNORE] to disallow the ** specific action but allow the SQL statement to continue to be ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be -** rejected with an error. If the authorizer callback returns +** rejected with an error. {F12504} If the authorizer callback returns ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY] -** then the [sqlite3_prepare_v2()] or equivalent call that triggered -** the authorizer will fail with an error message. +** then [sqlite3_prepare_v2()] or equivalent call that triggered +** the authorizer shall +** fail with an SQLITE_ERROR error code and an appropriate error message. {END} ** ** When the callback returns [SQLITE_OK], that means the operation -** requested is ok. When the callback returns [SQLITE_DENY], the +** requested is ok. {F12505} When the callback returns [SQLITE_DENY], the ** [sqlite3_prepare_v2()] or equivalent call that triggered the -** authorizer will fail with an error message explaining that -** access is denied. If the authorizer code is [SQLITE_READ] -** and the callback returns [SQLITE_IGNORE] then the -** [prepared statement] statement is constructed to substitute -** a NULL value in place of the table column that would have -** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE] -** return can be used to deny an untrusted user access to individual -** columns of a table. +** authorizer shall fail +** with an SQLITE_ERROR error code and an error message explaining that +** access is denied. {F12506} If the authorizer code (the 2nd parameter +** to the authorizer callback is anything other than [SQLITE_READ], then +** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. +** If the authorizer code is [SQLITE_READ] and the callback returns +** [SQLITE_IGNORE] then the prepared statement is constructed to +** insert a NULL value in place of the table column that would have +** been read if [SQLITE_OK] had been returned. {END} ** -** The first parameter to the authorizer callback is a copy of the third -** parameter to the sqlite3_set_authorizer() interface. The second parameter -** to the callback is an integer [SQLITE_COPY | action code] that specifies -** the particular action to be authorized. The third through sixth parameters -** to the callback are zero-terminated strings that contain additional -** details about the action to be authorized. +** {F12510} The first parameter to the authorizer callback is a copy of +** the third parameter to the sqlite3_set_authorizer() interface. +** {F12511} The second parameter to the callback is an integer +** [SQLITE_COPY | action code] that specifies the particular action +** to be authorized. {END} The available action codes are +** [SQLITE_COPY | documented separately]. {F12512} The third through sixth +** parameters to the callback are zero-terminated strings that contain +** additional details about the action to be authorized. {END} ** -** An authorizer is used when [sqlite3_prepare | preparing] -** SQL statements from an untrusted source, to ensure that the SQL statements -** do not try to access data they are not allowed to see, or that they do not -** try to execute malicious statements that damage the database. For +** An authorizer is used when preparing SQL statements from an untrusted +** source, to ensure that the SQL statements do not try to access data +** that they are not allowed to see, or that they do not try to +** execute malicious statements that damage the database. For ** example, an application may allow a user to enter arbitrary ** SQL queries for evaluation by a database. But the application does ** not want the user to be able to make arbitrary changes to the ** database. An authorizer could then be put in place while the -** user-entered SQL is being [sqlite3_prepare | prepared] that -** disallows everything except [SELECT] statements. +** user-entered SQL is being prepared that disallows everything +** except SELECT statements. ** -** Applications that need to process SQL from untrusted sources -** might also consider lowering resource limits using [sqlite3_limit()] -** and limiting database size using the [max_page_count] [PRAGMA] -** in addition to using an authorizer. -** -** Only a single authorizer can be in place on a database connection +** {F12520} Only a single authorizer can be in place on a database connection ** at a time. Each call to sqlite3_set_authorizer overrides the -** previous call. Disable the authorizer by installing a NULL callback. -** The authorizer is disabled by default. +** previous call. {F12521} A NULL authorizer means that no authorization +** callback is invoked. {F12522} The default authorizer is NULL. {END} ** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -** -** INVARIANTS: -** -** {F12501} The [sqlite3_set_authorizer(D,...)] interface registers a -** authorizer callback with database connection D. -** -** {F12502} The authorizer callback is invoked as SQL statements are -** being compiled. -** -** {F12503} If the authorizer callback returns any value other than -** [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY], then -** the [sqlite3_prepare_v2()] or equivalent call that caused -** the authorizer callback to run shall fail with an -** [SQLITE_ERROR] error code and an appropriate error message. -** -** {F12504} When the authorizer callback returns [SQLITE_OK], the operation -** described is processed normally. -** -** {F12505} When the authorizer callback returns [SQLITE_DENY], the -** [sqlite3_prepare_v2()] or equivalent call that caused the -** authorizer callback to run shall fail -** with an [SQLITE_ERROR] error code and an error message -** explaining that access is denied. -** -** {F12506} If the authorizer code (the 2nd parameter to the authorizer -** callback) is [SQLITE_READ] and the authorizer callback returns -** [SQLITE_IGNORE], then the prepared statement is constructed to -** insert a NULL value in place of the table column that would have -** been read if [SQLITE_OK] had been returned. -** -** {F12507} If the authorizer code (the 2nd parameter to the authorizer -** callback) is anything other than [SQLITE_READ], then -** a return of [SQLITE_IGNORE] has the same effect as [SQLITE_DENY]. -** -** {F12510} The first parameter to the authorizer callback is a copy of -** the third parameter to the [sqlite3_set_authorizer()] interface. -** -** {F12511} The second parameter to the callback is an integer -** [SQLITE_COPY | action code] that specifies the particular action -** to be authorized. -** -** {F12512} The third through sixth parameters to the callback are -** zero-terminated strings that contain -** additional details about the action to be authorized. -** -** {F12520} Each call to [sqlite3_set_authorizer()] overrides -** any previously installed authorizer. -** -** {F12521} A NULL authorizer means that no authorization -** callback is invoked. -** -** {F12522} The default authorizer is NULL. +** Note that the authorizer callback is invoked only during +** [sqlite3_prepare()] or its variants. {F12523} Authorization is not +** performed during statement evaluation in [sqlite3_step()]. {END} */ int sqlite3_set_authorizer( sqlite3*, @@ -2089,42 +1360,20 @@ int sqlite3_set_authorizer( ** CAPI3REF: Authorizer Action Codes {F12550} ** ** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorize certain SQL statement actions. The +** that is invoked to authorizer certain SQL statement actions. {F12551} The ** second parameter to the callback is an integer code that specifies ** what action is being authorized. These are the integer action codes that -** the authorizer callback may be passed. +** the authorizer callback may be passed. {END} ** -** These action code values signify what kind of operation is to be -** authorized. The 3rd and 4th parameters to the authorization +** These action code values signify what kind of operation is to be +** authorized. {F12552} The 3rd and 4th parameters to the authorization ** callback function will be parameters or NULL depending on which of these -** codes is used as the second parameter. The 5th parameter to the -** authorizer callback is the name of the database ("main", "temp", -** etc.) if applicable. The 6th parameter to the authorizer callback +** codes is used as the second parameter. {F12553} The 5th parameter to the +** authorizer callback is the name of the database ("main", "temp", +** etc.) if applicable. {F12554} The 6th parameter to the authorizer callback ** is the name of the inner-most trigger or view that is responsible for -** the access attempt or NULL if this access attempt is directly from +** the access attempt or NULL if this access attempt is directly from ** top-level SQL code. -** -** INVARIANTS: -** -** {F12551} The second parameter to an -** [sqlite3_set_authorizer | authorizer callback] is always an integer -** [SQLITE_COPY | authorizer code] that specifies what action -** is being authorized. -** -** {F12552} The 3rd and 4th parameters to the -** [sqlite3_set_authorizer | authorization callback] -** will be parameters or NULL depending on which -** [SQLITE_COPY | authorizer code] is used as the second parameter. -** -** {F12553} The 5th parameter to the -** [sqlite3_set_authorizer | authorizer callback] is the name -** of the database (example: "main", "temp", etc.) if applicable. -** -** {F12554} The 6th parameter to the -** [sqlite3_set_authorizer | authorizer callback] is the name -** of the inner-most trigger or view that is responsible for -** the access attempt or NULL if this access attempt is directly from -** top-level SQL code. */ /******************************************* 3rd ************ 4th ***********/ #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */ @@ -2166,60 +1415,31 @@ int sqlite3_set_authorizer( ** These routines register callback functions that can be used for ** tracing and profiling the execution of SQL statements. ** -** The callback function registered by sqlite3_trace() is invoked at -** various times when an SQL statement is being run by [sqlite3_step()]. -** The callback returns a UTF-8 rendering of the SQL statement text -** as the statement first begins executing. Additional callbacks occur -** as each triggered subprogram is entered. The callbacks for triggers -** contain a UTF-8 SQL comment that identifies the trigger. +** {F12281} The callback function registered by sqlite3_trace() is invoked +** at the first [sqlite3_step()] for the evaluation of an SQL statement. +** {F12282} Only a single trace callback can be registered at a time. +** Each call to sqlite3_trace() overrides the previous. {F12283} A +** NULL callback for sqlite3_trace() disables tracing. {F12284} The +** first argument to the trace callback is a copy of the pointer which +** was the 3rd argument to sqlite3_trace. {F12285} The second argument +** to the trace callback is a zero-terminated UTF8 string containing +** the original text of the SQL statement as it was passed into +** [sqlite3_prepare_v2()] or the equivalent. {END} Note that the +** host parameter are not expanded in the SQL statement text. ** -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes. The profile callback contains -** the original statement text and an estimate of wall-clock time -** of how long that statement took to run. +** {F12287} The callback function registered by sqlite3_profile() is invoked +** as each SQL statement finishes. {F12288} The first parameter to the +** profile callback is a copy of the 3rd parameter to sqlite3_profile(). +** {F12289} The second parameter to the profile callback is a +** zero-terminated UTF-8 string that contains the complete text of +** the SQL statement as it was processed by [sqlite3_prepare_v2()] or +** the equivalent. {F12290} The third parameter to the profile +** callback is an estimate of the number of nanoseconds of +** wall-clock time required to run the SQL statement from start +** to finish. {END} ** ** The sqlite3_profile() API is currently considered experimental and -** is subject to change or removal in a future release. -** -** The trigger reporting feature of the trace callback is considered -** experimental and is subject to change or removal in future releases. -** Future versions of SQLite might also add new trace callback -** invocations. -** -** INVARIANTS: -** -** {F12281} The callback function registered by [sqlite3_trace()] is -** whenever an SQL statement first begins to execute and -** whenever a trigger subprogram first begins to run. -** -** {F12282} Each call to [sqlite3_trace()] overrides the previously -** registered trace callback. -** -** {F12283} A NULL trace callback disables tracing. -** -** {F12284} The first argument to the trace callback is a copy of -** the pointer which was the 3rd argument to [sqlite3_trace()]. -** -** {F12285} The second argument to the trace callback is a -** zero-terminated UTF-8 string containing the original text -** of the SQL statement as it was passed into [sqlite3_prepare_v2()] -** or the equivalent, or an SQL comment indicating the beginning -** of a trigger subprogram. -** -** {F12287} The callback function registered by [sqlite3_profile()] is invoked -** as each SQL statement finishes. -** -** {F12288} The first parameter to the profile callback is a copy of -** the 3rd parameter to [sqlite3_profile()]. -** -** {F12289} The second parameter to the profile callback is a -** zero-terminated UTF-8 string that contains the complete text of -** the SQL statement as it was processed by [sqlite3_prepare_v2()] -** or the equivalent. -** -** {F12290} The third parameter to the profile callback is an estimate -** of the number of nanoseconds of wall-clock time required to -** run the SQL statement from start to finish. +** is subject to change. */ void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); void *sqlite3_profile(sqlite3*, @@ -2228,196 +1448,111 @@ void *sqlite3_profile(sqlite3*, /* ** CAPI3REF: Query Progress Callbacks {F12910} ** -** This routine configures a callback function - the +** {F12911} This routine configures a callback function - the ** progress callback - that is invoked periodically during long ** running calls to [sqlite3_exec()], [sqlite3_step()] and -** [sqlite3_get_table()]. An example use for this +** [sqlite3_get_table()]. {END} An example use for this ** interface is to keep a GUI updated during a large query. ** -** If the progress callback returns non-zero, the operation is -** interrupted. This feature can be used to implement a -** "Cancel" button on a GUI dialog box. -** -** INVARIANTS: -** -** {F12911} The callback function registered by sqlite3_progress_handler() -** is invoked periodically during long running calls to -** [sqlite3_step()]. -** ** {F12912} The progress callback is invoked once for every N virtual -** machine opcodes, where N is the second argument to -** the [sqlite3_progress_handler()] call that registered -** the callback. If N is less than 1, sqlite3_progress_handler() -** acts as if a NULL progress handler had been specified. -** +** machine opcodes, where N is the second argument to this function. ** {F12913} The progress callback itself is identified by the third -** argument to sqlite3_progress_handler(). +** argument to this function. {F12914} The fourth argument to this +** function is a void pointer passed to the progress callback +** function each time it is invoked. {END} ** -** {F12914} The fourth argument to sqlite3_progress_handler() is a -** void pointer passed to the progress callback -** function each time it is invoked. -** -** {F12915} If a call to [sqlite3_step()] results in fewer than N opcodes -** being executed, then the progress callback is never invoked. -** -** {F12916} Every call to [sqlite3_progress_handler()] -** overwrites any previously registered progress handler. -** -** {F12917} If the progress handler callback is NULL then no progress -** handler is invoked. +** {F12915} If a call to [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] results in fewer than N opcodes being executed, +** then the progress callback is never invoked. {END} +** +** {F12916} Only a single progress callback function may be registered for each +** open database connection. Every call to sqlite3_progress_handler() +** overwrites the results of the previous call. {F12917} +** To remove the progress callback altogether, pass NULL as the third +** argument to this function. {END} ** ** {F12918} If the progress callback returns a result other than 0, then -** the behavior is a if [sqlite3_interrupt()] had been called. +** the current query is immediately terminated and any database changes +** rolled back. {F12919} +** The containing [sqlite3_exec()], [sqlite3_step()], or +** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. {END} This feature +** can be used, for example, to implement the "Cancel" button on a +** progress dialog box in a GUI. */ void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* ** CAPI3REF: Opening A New Database Connection {F12700} ** -** These routines open an SQLite database file whose name is given by the -** filename argument. The filename argument is interpreted as UTF-8 for -** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte -** order for sqlite3_open16(). A [database connection] handle is usually -** returned in *ppDb, even if an error occurs. The only exception is that -** if SQLite is unable to allocate memory to hold the [sqlite3] object, -** a NULL will be written into *ppDb instead of a pointer to the [sqlite3] -** object. If the database is opened (and/or created) successfully, then -** [SQLITE_OK] is returned. Otherwise an [error code] is returned. The -** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain +** {F12701} These routines open an SQLite database file whose name +** is given by the filename argument. +** {F12702} The filename argument is interpreted as UTF-8 +** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 +** in the native byte order for [sqlite3_open16()]. +** {F12703} An [sqlite3*] handle is returned in *ppDb, even +** if an error occurs. {F12723} (Exception: if SQLite is unable +** to allocate memory to hold the [sqlite3] object, a NULL will +** be written into *ppDb instead of a pointer to the [sqlite3] object.) +** {F12704} If the database is opened (and/or created) +** successfully, then [SQLITE_OK] is returned. {F12705} Otherwise an +** error code is returned. {F12706} The +** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain ** an English language description of the error. ** -** The default encoding for the database will be UTF-8 if -** sqlite3_open() or sqlite3_open_v2() is called and -** UTF-16 in the native byte order if sqlite3_open16() is used. +** {F12707} The default encoding for the database will be UTF-8 if +** [sqlite3_open()] or [sqlite3_open_v2()] is called and +** UTF-16 in the native byte order if [sqlite3_open16()] is used. ** -** Whether or not an error occurs when it is opened, resources -** associated with the [database connection] handle should be released by -** passing it to [sqlite3_close()] when it is no longer required. +** {F12708} Whether or not an error occurs when it is opened, resources +** associated with the [sqlite3*] handle should be released by passing it +** to [sqlite3_close()] when it is no longer required. ** -** The sqlite3_open_v2() interface works like sqlite3_open() -** except that it accepts two additional parameters for additional control -** over the new database connection. The flags parameter can take one of -** the following three values, optionally combined with the -** [SQLITE_OPEN_NOMUTEX] flag: +** {F12709} The [sqlite3_open_v2()] interface works like [sqlite3_open()] +** except that it acccepts two additional parameters for additional control +** over the new database connection. {F12710} The flags parameter can be +** one of: ** -**
      -**
      [SQLITE_OPEN_READONLY]
      -**
      The database is opened in read-only mode. If the database does not -** already exist, an error is returned.
      +**
        +**
      1. [SQLITE_OPEN_READONLY] +**
      2. [SQLITE_OPEN_READWRITE] +**
      3. [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +**
      ** -**
      [SQLITE_OPEN_READWRITE]
      -**
      The database is opened for reading and writing if possible, or reading -** only if the file is write protected by the operating system. In either -** case the database must already exist, otherwise an error is returned.
      +** {F12711} The first value opens the database read-only. +** {F12712} If the database does not previously exist, an error is returned. +** {F12713} The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. {F12714} In either case the database +** must already exist or an error is returned. {F12715} The third option +** opens the database for reading and writing and creates it if it does +** not already exist. {F12716} +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. ** -**
      [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]
      -**
      The database is opened for reading and writing, and is creates it if -** it does not already exist. This is the behavior that is always used for -** sqlite3_open() and sqlite3_open16().
      -**
      +** {F12717} If the filename is ":memory:", then an private +** in-memory database is created for the connection. {F12718} This in-memory +** database will vanish when the database connection is closed. {END} Future +** version of SQLite might make use of additional special filenames +** that begin with the ":" character. It is recommended that +** when a database filename really does begin with +** ":" that you prefix the filename with a pathname like "./" to +** avoid ambiguity. ** -** If the 3rd parameter to sqlite3_open_v2() is not one of the -** combinations shown above or one of the combinations shown above combined -** with the [SQLITE_OPEN_NOMUTEX] flag, then the behavior is undefined. -** -** If the [SQLITE_OPEN_NOMUTEX] flag is set, then mutexes on the -** opened [database connection] are disabled and the appliation must -** insure that access to the [database connection] and its associated -** [prepared statements] is serialized. The [SQLITE_OPEN_NOMUTEX] flag -** is the default behavior is SQLite is configured using the -** [SQLITE_CONFIG_MULTITHREAD] or [SQLITE_CONFIG_SINGLETHREAD] options -** to [sqlite3_config()]. The [SQLITE_OPEN_NOMUTEX] flag only makes a -** difference when SQLite is in its default [SQLITE_CONFIG_SERIALIZED] mode. -** -** If the filename is ":memory:", then a private, temporary in-memory database -** is created for the connection. This in-memory database will vanish when -** the database connection is closed. Future versions of SQLite might -** make use of additional special filenames that begin with the ":" character. -** It is recommended that when a database filename actually does begin with -** a ":" character you should prefix the filename with a pathname such as -** "./" to avoid ambiguity. -** -** If the filename is an empty string, then a private, temporary -** on-disk database will be created. This private database will be +** {F12719} If the filename is an empty string, then a private temporary +** on-disk database will be created. {F12720} This private database will be ** automatically deleted as soon as the database connection is closed. ** -** The fourth parameter to sqlite3_open_v2() is the name of the -** [sqlite3_vfs] object that defines the operating system interface that -** the new database connection should use. If the fourth parameter is -** a NULL pointer then the default [sqlite3_vfs] object is used. +** {F12721} The fourth parameter to sqlite3_open_v2() is the name of the +** [sqlite3_vfs] object that defines the operating system +** interface that the new database connection should use. {F12722} If the +** fourth parameter is a NULL pointer then the default [sqlite3_vfs] +** object is used. {END} ** -** Note to Windows users: The encoding used for the filename argument -** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever +** Note to windows users: The encoding used for the filename argument +** of [sqlite3_open()] and [sqlite3_open_v2()] must be UTF-8, not whatever ** codepage is currently defined. Filenames containing international ** characters must be converted to UTF-8 prior to passing them into -** sqlite3_open() or sqlite3_open_v2(). -** -** INVARIANTS: -** -** {F12701} The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces create a new -** [database connection] associated with -** the database file given in their first parameter. -** -** {F12702} The filename argument is interpreted as UTF-8 -** for [sqlite3_open()] and [sqlite3_open_v2()] and as UTF-16 -** in the native byte order for [sqlite3_open16()]. -** -** {F12703} A successful invocation of [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] writes a pointer to a new -** [database connection] into *ppDb. -** -** {F12704} The [sqlite3_open()], [sqlite3_open16()], and -** [sqlite3_open_v2()] interfaces return [SQLITE_OK] upon success, -** or an appropriate [error code] on failure. -** -** {F12706} The default text encoding for a new database created using -** [sqlite3_open()] or [sqlite3_open_v2()] will be UTF-8. -** -** {F12707} The default text encoding for a new database created using -** [sqlite3_open16()] will be UTF-16. -** -** {F12709} The [sqlite3_open(F,D)] interface is equivalent to -** [sqlite3_open_v2(F,D,G,0)] where the G parameter is -** [SQLITE_OPEN_READWRITE]|[SQLITE_OPEN_CREATE]. -** -** {F12711} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the -** bit value [SQLITE_OPEN_READONLY] then the database is opened -** for reading only. -** -** {F12712} If the G parameter to [sqlite3_open_v2(F,D,G,V)] contains the -** bit value [SQLITE_OPEN_READWRITE] then the database is opened -** reading and writing if possible, or for reading only if the -** file is write protected by the operating system. -** -** {F12713} If the G parameter to [sqlite3_open(v2(F,D,G,V)] omits the -** bit value [SQLITE_OPEN_CREATE] and the database does not -** previously exist, an error is returned. -** -** {F12714} If the G parameter to [sqlite3_open(v2(F,D,G,V)] contains the -** bit value [SQLITE_OPEN_CREATE] and the database does not -** previously exist, then an attempt is made to create and -** initialize the database. -** -** {F12717} If the filename argument to [sqlite3_open()], [sqlite3_open16()], -** or [sqlite3_open_v2()] is ":memory:", then an private, -** ephemeral, in-memory database is created for the connection. -** Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required -** in sqlite3_open_v2()? -** -** {F12719} If the filename is NULL or an empty string, then a private, -** ephemeral on-disk database will be created. -** Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required -** in sqlite3_open_v2()? -** -** {F12721} The [database connection] created by [sqlite3_open_v2(F,D,G,V)] -** will use the [sqlite3_vfs] object identified by the V parameter, -** or the default [sqlite3_vfs] object if V is a NULL pointer. -** -** {F12723} Two [database connections] will share a common cache if both were -** opened with the same VFS while [shared cache mode] was enabled and -** if both filenames compare equal using memcmp() after having been -** processed by the [sqlite3_vfs | xFullPathname] method of the VFS. +** [sqlite3_open()] or [sqlite3_open_v2()]. */ int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ @@ -2437,47 +1572,35 @@ int sqlite3_open_v2( /* ** CAPI3REF: Error Codes And Messages {F12800} ** -** The sqlite3_errcode() interface returns the numeric [result code] or -** [extended result code] for the most recent failed sqlite3_* API call -** associated with a [database connection]. If a prior API call failed -** but the most recent API call succeeded, the return value from -** sqlite3_errcode() is undefined. +** {F12801} The sqlite3_errcode() interface returns the numeric +** [SQLITE_OK | result code] or [SQLITE_IOERR_READ | extended result code] +** for the most recent failed sqlite3_* API call associated +** with [sqlite3] handle 'db'. {U12802} If a prior API call failed but the +** most recent API call succeeded, the return value from sqlite3_errcode() +** is undefined. {END} ** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF-8 or UTF-16 respectively. -** Memory to hold the error message string is managed internally. -** The application does not need to worry about freeing the result. -** However, the error string might be overwritten or deallocated by -** subsequent calls to other SQLite interface functions. +** {F12803} The sqlite3_errmsg() and sqlite3_errmsg16() return English-language +** text that describes the error, as either UTF8 or UTF16 respectively. +** {F12804} Memory to hold the error message string is managed internally. +** {U12805} The +** string may be overwritten or deallocated by subsequent calls to SQLite +** interface functions. {END} ** -** If an interface fails with SQLITE_MISUSE, that means the interface -** was invoked incorrectly by the application. In that case, the -** error code and message may or may not be set. +** {F12806} Calls to many sqlite3_* functions set the error code and +** string returned by [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] overwriting the previous values. {F12807} +** Except, calls to [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations. {F12808} Calls to API routines that +** do not return an error code (example: [sqlite3_data_count()]) do not +** change the error code returned by this routine. {F12809} Interfaces that +** are not associated with a specific database connection (examples: +** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change +** the return code. {END} ** -** INVARIANTS: -** -** {F12801} The [sqlite3_errcode(D)] interface returns the numeric -** [result code] or [extended result code] for the most recently -** failed interface call associated with the [database connection] D. -** -** {F12803} The [sqlite3_errmsg(D)] and [sqlite3_errmsg16(D)] -** interfaces return English-language text that describes -** the error in the mostly recently failed interface call, -** encoded as either UTF-8 or UTF-16 respectively. -** -** {F12807} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()] -** are valid until the next SQLite interface call. -** -** {F12808} Calls to API routines that do not return an error code -** (example: [sqlite3_data_count()]) do not -** change the error code or message returned by -** [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()]. -** -** {F12809} Interfaces that are not associated with a specific -** [database connection] (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] -** do not change the values returned by -** [sqlite3_errcode()], [sqlite3_errmsg()], or [sqlite3_errmsg16()]. +** {F12810} Assuming no other intervening sqlite3_* API calls are made, +** the error code returned by this function is associated with the same +** error as the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()]. */ int sqlite3_errcode(sqlite3 *db); const char *sqlite3_errmsg(sqlite3*); @@ -2485,19 +1608,18 @@ const void *sqlite3_errmsg16(sqlite3*); /* ** CAPI3REF: SQL Statement Object {F13000} -** KEYWORDS: {prepared statement} {prepared statements} ** -** An instance of this object represents a single SQL statement. -** This object is variously known as a "prepared statement" or a +** An instance of this object represent single SQL statements. This +** object is variously known as a "prepared statement" or a ** "compiled SQL statement" or simply as a "statement". -** +** ** The life of a statement object goes something like this: ** **
        **
      1. Create the object using [sqlite3_prepare_v2()] or a related ** function. -**
      2. Bind values to [host parameters] using the sqlite3_bind_*() -** interfaces. +**
      3. Bind values to host parameters using +** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. **
      4. Run the SQL by calling [sqlite3_step()] one or more times. **
      5. Reset the statement using [sqlite3_reset()] then go back ** to step 2. Do this zero or more times. @@ -2509,214 +1631,78 @@ const void *sqlite3_errmsg16(sqlite3*); */ typedef struct sqlite3_stmt sqlite3_stmt; -/* -** CAPI3REF: Run-time Limits {F12760} -** -** This interface allows the size of various constructs to be limited -** on a connection by connection basis. The first parameter is the -** [database connection] whose limit is to be set or queried. The -** second parameter is one of the [limit categories] that define a -** class of constructs to be size limited. The third parameter is the -** new limit for that construct. The function returns the old limit. -** -** If the new limit is a negative number, the limit is unchanged. -** For the limit category of SQLITE_LIMIT_XYZ there is a hard upper -** bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ. -** (The "_LIMIT_" in the name is changed to "_MAX_".) -** Attempts to increase a limit above its hard upper bound are -** silently truncated to the hard upper limit. -** -** Run time limits are intended for use in applications that manage -** both their own internal database and also databases that are controlled -** by untrusted external sources. An example application might be a -** webbrowser that has its own databases for storing history and -** separate databases controlled by JavaScript applications downloaded -** off the Internet. The internal databases can be given the -** large, default limits. Databases managed by external sources can -** be given much smaller limits designed to prevent a denial of service -** attack. Developers might also want to use the [sqlite3_set_authorizer()] -** interface to further control untrusted SQL. The size of the database -** created by an untrusted script can be contained using the -** [max_page_count] [PRAGMA]. -** -** New run-time limit categories may be added in future releases. -** -** INVARIANTS: -** -** {F12762} A successful call to [sqlite3_limit(D,C,V)] where V is -** positive changes the limit on the size of construct C in the -** [database connection] D to the lesser of V and the hard upper -** bound on the size of C that is set at compile-time. -** -** {F12766} A successful call to [sqlite3_limit(D,C,V)] where V is negative -** leaves the state of the [database connection] D unchanged. -** -** {F12769} A successful call to [sqlite3_limit(D,C,V)] returns the -** value of the limit on the size of construct C in the -** [database connection] D as it was prior to the call. -*/ -int sqlite3_limit(sqlite3*, int id, int newVal); - -/* -** CAPI3REF: Run-Time Limit Categories {F12790} -** KEYWORDS: {limit category} {limit categories} -** -** These constants define various aspects of a [database connection] -** that can be limited in size by calls to [sqlite3_limit()]. -** The meanings of the various limits are as follows: -** -**
        -**
        SQLITE_LIMIT_LENGTH
        -**
        The maximum size of any string or BLOB or table row.
        -** -**
        SQLITE_LIMIT_SQL_LENGTH
        -**
        The maximum length of an SQL statement.
        -** -**
        SQLITE_LIMIT_COLUMN
        -**
        The maximum number of columns in a table definition or in the -** result set of a SELECT or the maximum number of columns in an index -** or in an ORDER BY or GROUP BY clause.
        -** -**
        SQLITE_LIMIT_EXPR_DEPTH
        -**
        The maximum depth of the parse tree on any expression.
        -** -**
        SQLITE_LIMIT_COMPOUND_SELECT
        -**
        The maximum number of terms in a compound SELECT statement.
        -** -**
        SQLITE_LIMIT_VDBE_OP
        -**
        The maximum number of instructions in a virtual machine program -** used to implement an SQL statement.
        -** -**
        SQLITE_LIMIT_FUNCTION_ARG
        -**
        The maximum number of arguments on a function.
        -** -**
        SQLITE_LIMIT_ATTACHED
        -**
        The maximum number of attached databases.
        -** -**
        SQLITE_LIMIT_LIKE_PATTERN_LENGTH
        -**
        The maximum length of the pattern argument to the LIKE or -** GLOB operators.
        -** -**
        SQLITE_LIMIT_VARIABLE_NUMBER
        -**
        The maximum number of variables in an SQL statement that can -** be bound.
        -**
        -*/ -#define SQLITE_LIMIT_LENGTH 0 -#define SQLITE_LIMIT_SQL_LENGTH 1 -#define SQLITE_LIMIT_COLUMN 2 -#define SQLITE_LIMIT_EXPR_DEPTH 3 -#define SQLITE_LIMIT_COMPOUND_SELECT 4 -#define SQLITE_LIMIT_VDBE_OP 5 -#define SQLITE_LIMIT_FUNCTION_ARG 6 -#define SQLITE_LIMIT_ATTACHED 7 -#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 -#define SQLITE_LIMIT_VARIABLE_NUMBER 9 - /* ** CAPI3REF: Compiling An SQL Statement {F13010} -** KEYWORDS: {SQL statement compiler} ** ** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. +** program using one of these routines. ** -** The first argument, "db", is a [database connection] obtained from a -** prior call to [sqlite3_open()], [sqlite3_open_v2()] or [sqlite3_open16()]. -** -** The second argument, "zSql", is the statement to be compiled, encoded +** {F13011} The first argument "db" is an [sqlite3 | SQLite database handle] +** obtained from a prior call to [sqlite3_open()], [sqlite3_open_v2()] +** or [sqlite3_open16()]. {F13012} +** The second argument "zSql" is the statement to be compiled, encoded ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2() -** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2() -** use UTF-16. +** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2() +** use UTF-16. {END} ** -** If the nByte argument is less than zero, then zSql is read up to the -** first zero terminator. If nByte is non-negative, then it is the maximum -** number of bytes read from zSql. When nByte is non-negative, the -** zSql string ends at either the first '\000' or '\u0000' character or -** the nByte-th byte, whichever comes first. If the caller knows -** that the supplied string is nul-terminated, then there is a small -** performance advantage to be gained by passing an nByte parameter that -** is equal to the number of bytes in the input string including -** the nul-terminator bytes. +** {F13013} If the nByte argument is less +** than zero, then zSql is read up to the first zero terminator. +** {F13014} If nByte is non-negative, then it is the maximum number of +** bytes read from zSql. When nByte is non-negative, the +** zSql string ends at either the first '\000' or '\u0000' character or +** until the nByte-th byte, whichever comes first. {END} ** -** *pzTail is made to point to the first byte past the end of the -** first SQL statement in zSql. These routines only compile the first +** {F13015} *pzTail is made to point to the first byte past the end of the +** first SQL statement in zSql. These routines only compiles the first ** statement in zSql, so *pzTail is left pointing to what remains -** uncompiled. +** uncompiled. {END} ** -** *ppStmt is left pointing to a compiled [prepared statement] that can be -** executed using [sqlite3_step()]. If there is an error, *ppStmt is set -** to NULL. If the input text contains no SQL (if the input is an empty -** string or a comment) then *ppStmt is set to NULL. -** {A13018} The calling procedure is responsible for deleting the compiled -** SQL statement using [sqlite3_finalize()] after it has finished with it. +** {F13016} *ppStmt is left pointing to a compiled +** [sqlite3_stmt | SQL statement structure] that can be +** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be +** set to NULL. {F13017} If the input text contains no SQL (if the input +** is and empty string or a comment) then *ppStmt is set to NULL. +** {U13018} The calling procedure is responsible for deleting the +** compiled SQL statement +** using [sqlite3_finalize()] after it has finished with it. ** -** On success, [SQLITE_OK] is returned, otherwise an [error code] is returned. +** {F13019} On success, [SQLITE_OK] is returned. Otherwise an +** [SQLITE_ERROR | error code] is returned. {END} ** ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are ** recommended for all new programs. The two older interfaces are retained ** for backwards compatibility, but their use is discouraged. -** In the "v2" interfaces, the prepared statement -** that is returned (the [sqlite3_stmt] object) contains a copy of the -** original SQL text. This causes the [sqlite3_step()] interface to +** {F13020} In the "v2" interfaces, the prepared statement +** that is returned (the [sqlite3_stmt] object) contains a copy of the +** original SQL text. {END} This causes the [sqlite3_step()] interface to ** behave a differently in two ways: ** **
          -**
        1. +**
        2. {F13022} ** If the database schema changes, instead of returning [SQLITE_SCHEMA] as it ** always used to do, [sqlite3_step()] will automatically recompile the SQL -** statement and try to run it again. If the schema has changed in +** statement and try to run it again. {F12023} If the schema has changed in ** a way that makes the statement no longer valid, [sqlite3_step()] will still -** return [SQLITE_SCHEMA]. But unlike the legacy behavior, [SQLITE_SCHEMA] is -** now a fatal error. Calling [sqlite3_prepare_v2()] again will not make the -** error go away. Note: use [sqlite3_errmsg()] to find the text -** of the parsing error that results in an [SQLITE_SCHEMA] return. +** return [SQLITE_SCHEMA]. {END} But unlike the legacy behavior, +** [SQLITE_SCHEMA] is now a fatal error. {F12024} Calling +** [sqlite3_prepare_v2()] again will not make the +** error go away. {F12025} Note: use [sqlite3_errmsg()] to find the text +** of the parsing error that results in an [SQLITE_SCHEMA] return. {END} **
        3. ** **
        4. -** When an error occurs, [sqlite3_step()] will return one of the detailed -** [error codes] or [extended error codes]. The legacy behavior was that -** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code -** and you would have to make a second call to [sqlite3_reset()] in order -** to find the underlying cause of the problem. With the "v2" prepare -** interfaces, the underlying reason for the error is returned immediately. +** {F13030} When an error occurs, +** [sqlite3_step()] will return one of the detailed +** [SQLITE_ERROR | result codes] or +** [SQLITE_IOERR_READ | extended result codes]. {F13031} +** The legacy behavior was that [sqlite3_step()] would only return a generic +** [SQLITE_ERROR] result code and you would have to make a second call to +** [sqlite3_reset()] in order to find the underlying cause of the problem. +** {F13032} +** With the "v2" prepare interfaces, the underlying reason for the error is +** returned immediately. {END} **
        5. **
        -** -** INVARIANTS: -** -** {F13011} The [sqlite3_prepare(db,zSql,...)] and -** [sqlite3_prepare_v2(db,zSql,...)] interfaces interpret the -** text in their zSql parameter as UTF-8. -** -** {F13012} The [sqlite3_prepare16(db,zSql,...)] and -** [sqlite3_prepare16_v2(db,zSql,...)] interfaces interpret the -** text in their zSql parameter as UTF-16 in the native byte order. -** -** {F13013} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)] -** and its variants is less than zero, the SQL text is -** read from zSql is read up to the first zero terminator. -** -** {F13014} If the nByte argument to [sqlite3_prepare_v2(db,zSql,nByte,...)] -** and its variants is non-negative, then at most nBytes bytes of -** SQL text is read from zSql. -** -** {F13015} In [sqlite3_prepare_v2(db,zSql,N,P,pzTail)] and its variants -** if the zSql input text contains more than one SQL statement -** and pzTail is not NULL, then *pzTail is made to point to the -** first byte past the end of the first SQL statement in zSql. -** What does *pzTail point to if there is one statement? -** -** {F13016} A successful call to [sqlite3_prepare_v2(db,zSql,N,ppStmt,...)] -** or one of its variants writes into *ppStmt a pointer to a new -** [prepared statement] or a pointer to NULL if zSql contains -** nothing other than whitespace or comments. -** -** {F13019} The [sqlite3_prepare_v2()] interface and its variants return -** [SQLITE_OK] or an appropriate [error code] upon failure. -** -** {F13021} Before [sqlite3_prepare(db,zSql,nByte,ppStmt,pzTail)] or its -** variants returns an error (any value other than [SQLITE_OK]), -** they first set *ppStmt to NULL. */ int sqlite3_prepare( sqlite3 *db, /* Database handle */ @@ -2750,232 +1736,117 @@ int sqlite3_prepare16_v2( /* ** CAPIREF: Retrieving Statement SQL {F13100} ** -** This interface can be used to retrieve a saved copy of the original -** SQL text used to create a [prepared statement] if that statement was -** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()]. +** {F13101} If the compiled SQL statement passed as an argument was +** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()], +** then this function returns a pointer to a zero-terminated string +** containing a copy of the original SQL statement. {F13102} The +** pointer is valid until the statement +** is deleted using sqlite3_finalize(). +** {F13103} The string returned by sqlite3_sql() is always UTF8 even +** if a UTF16 string was originally entered using [sqlite3_prepare16_v2()] +** or the equivalent. ** -** INVARIANTS: -** -** {F13101} If the [prepared statement] passed as the argument to -** [sqlite3_sql()] was compiled using either [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()], then [sqlite3_sql()] returns -** a pointer to a zero-terminated string containing a UTF-8 rendering -** of the original SQL statement. -** -** {F13102} If the [prepared statement] passed as the argument to -** [sqlite3_sql()] was compiled using either [sqlite3_prepare()] or -** [sqlite3_prepare16()], then [sqlite3_sql()] returns a NULL pointer. -** -** {F13103} The string returned by [sqlite3_sql(S)] is valid until the -** [prepared statement] S is deleted using [sqlite3_finalize(S)]. +** {F13104} If the statement was compiled using either of the legacy +** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this +** function returns NULL. */ const char *sqlite3_sql(sqlite3_stmt *pStmt); /* -** CAPI3REF: Dynamically Typed Value Object {F15000} -** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value} +** CAPI3REF: Dynamically Typed Value Object {F15000} ** -** SQLite uses the sqlite3_value object to represent all values -** that can be stored in a database table. SQLite uses dynamic typing -** for the values it stores. Values stored in sqlite3_value objects -** can be integers, floating point values, strings, BLOBs, or NULL. -** -** An sqlite3_value object may be either "protected" or "unprotected". -** Some interfaces require a protected sqlite3_value. Other interfaces -** will accept either a protected or an unprotected sqlite3_value. -** Every interface that accepts sqlite3_value arguments specifies -** whether or not it requires a protected sqlite3_value. -** -** The terms "protected" and "unprotected" refer to whether or not -** a mutex is held. A internal mutex is held for a protected -** sqlite3_value object but no mutex is held for an unprotected -** sqlite3_value object. If SQLite is compiled to be single-threaded -** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0) -** or if SQLite is run in one of reduced mutex modes -** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD] -** then there is no distinction between protected and unprotected -** sqlite3_value objects and they can be used interchangeably. However, -** for maximum code portability it is recommended that applications -** still make the distinction between between protected and unprotected -** sqlite3_value objects even when not strictly required. -** -** The sqlite3_value objects that are passed as parameters into the -** implementation of [application-defined SQL functions] are protected. -** The sqlite3_value object returned by -** [sqlite3_column_value()] is unprotected. -** Unprotected sqlite3_value objects may only be used with -** [sqlite3_result_value()] and [sqlite3_bind_value()]. -** The [sqlite3_value_blob | sqlite3_value_type()] family of -** interfaces require protected sqlite3_value objects. +** {F15001} SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. {END} +** SQLite uses dynamic typing for the values it stores. +** {F15002} Values stored in sqlite3_value objects can be +** be integers, floating point values, strings, BLOBs, or NULL. */ typedef struct Mem sqlite3_value; /* -** CAPI3REF: SQL Function Context Object {F16001} +** CAPI3REF: SQL Function Context Object {F16001} ** ** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to an sqlite3_context object -** is always first parameter to [application-defined SQL functions]. -** The application-defined SQL function implementation will pass this -** pointer through into calls to [sqlite3_result_int | sqlite3_result()], -** [sqlite3_aggregate_context()], [sqlite3_user_data()], -** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()], -** and/or [sqlite3_set_auxdata()]. +** sqlite3_context object. {F16002} A pointer to an sqlite3_context +** object is always first parameter to application-defined SQL functions. */ typedef struct sqlite3_context sqlite3_context; /* -** CAPI3REF: Binding Values To Prepared Statements {F13500} -** KEYWORDS: {host parameter} {host parameters} {host parameter name} -** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding} +** CAPI3REF: Binding Values To Prepared Statements {F13500} ** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** literals may be replaced by a parameter in one of these forms: +** {F13501} In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: ** **
          **
        • ? **
        • ?NNN -**
        • :VVV -**
        • @VVV +**
        • :AAA +**
        • @AAA **
        • $VVV **
        ** ** In the parameter forms shown above NNN is an integer literal, -** and VVV is an alpha-numeric parameter name. The values of these -** parameters (also called "host parameter names" or "SQL parameters") +** AAA is an alphanumeric identifier and VVV is a variable name according +** to the syntax rules of the TCL programming language. {END} +** The values of these parameters (also called "host parameter names") ** can be set using the sqlite3_bind_*() routines defined here. ** -** The first argument to the sqlite3_bind_*() routines is always -** a pointer to the [sqlite3_stmt] object returned from -** [sqlite3_prepare_v2()] or its variants. -** -** The second argument is the index of the SQL parameter to be set. -** The leftmost SQL parameter has an index of 1. When the same named -** SQL parameter is used more than once, second and subsequent -** occurrences have the same index as the first occurrence. -** The index for named parameters can be looked up using the -** [sqlite3_bind_parameter_index()] API if desired. The index +** {F13502} The first argument to the sqlite3_bind_*() routines always +** is a pointer to the [sqlite3_stmt] object returned from +** [sqlite3_prepare_v2()] or its variants. {F13503} The second +** argument is the index of the parameter to be set. {F13504} The +** first parameter has an index of 1. {F13505} When the same named +** parameter is used more than once, second and subsequent +** occurrences have the same index as the first occurrence. +** {F13506} The index for named parameters can be looked up using the +** [sqlite3_bind_parameter_name()] API if desired. {F13507} The index ** for "?NNN" parameters is the value of NNN. -** The NNN value must be between 1 and the [sqlite3_limit()] -** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999). +** {F13508} The NNN value must be between 1 and the compile-time +** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). {END} +** See limits.html for additional information. ** -** The third argument is the value to bind to the parameter. +** {F13509} The third argument is the value to bind to the parameter. {END} ** -** In those routines that have a fourth argument, its value is the -** number of bytes in the parameter. To be clear: the value is the -** number of bytes in the value, not the number of characters. +** {F13510} In those +** routines that have a fourth argument, its value is the number of bytes +** in the parameter. To be clear: the value is the number of bytes in the +** string, not the number of characters. {F13511} The number +** of bytes does not include the zero-terminator at the end of strings. +** {F13512} ** If the fourth parameter is negative, the length of the string is -** the number of bytes up to the first zero terminator. +** number of bytes up to the first zero terminator. {END} ** +** {F13513} ** The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or -** string after SQLite has finished with it. If the fifth argument is -** the special value [SQLITE_STATIC], then SQLite assumes that the +** text after SQLite has finished with it. {F13514} If the fifth argument is +** the special value [SQLITE_STATIC], then the library assumes that the ** information is in static, unmanaged space and does not need to be freed. -** If the fifth argument has the value [SQLITE_TRANSIENT], then +** {F13515} If the fifth argument has the value [SQLITE_TRANSIENT], then ** SQLite makes its own private copy of the data immediately, before -** the sqlite3_bind_*() routine returns. +** the sqlite3_bind_*() routine returns. {END} ** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that -** is filled with zeroes. A zeroblob uses a fixed amount of memory -** (just an integer to hold its size) while it is being processed. -** Zeroblobs are intended to serve as placeholders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | incremental BLOB I/O] routines. -** A negative value for the zeroblob results in a zero-length BLOB. +** {F13520} The sqlite3_bind_zeroblob() routine binds a BLOB of length N that +** is filled with zeros. {F13521} A zeroblob uses a fixed amount of memory +** (just an integer to hold it size) while it is being processed. {END} +** Zeroblobs are intended to serve as place-holders for BLOBs whose +** content is later written using +** [sqlite3_blob_open | increment BLOB I/O] routines. {F13522} A negative +** value for the zeroblob results in a zero-length BLOB. {END} ** -** The sqlite3_bind_*() routines must be called after +** {F13530} The sqlite3_bind_*() routines must be called after ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. +** before [sqlite3_step()]. {F13531} ** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. +** {F13532} Unbound parameters are interpreted as NULL. {END} ** -** These routines return [SQLITE_OK] on success or an error code if -** anything goes wrong. [SQLITE_RANGE] is returned if the parameter -** index is out of range. [SQLITE_NOMEM] is returned if malloc() fails. -** [SQLITE_MISUSE] might be returned if these routines are called on a +** {F13540} These routines return [SQLITE_OK] on success or an error code if +** anything goes wrong. {F13541} [SQLITE_RANGE] is returned if the parameter +** index is out of range. {F13542} [SQLITE_NOMEM] is returned if malloc fails. +** {F13543} [SQLITE_MISUSE] is returned if these routines are called on a ** virtual machine that is the wrong state or which has already been finalized. -** Detection of misuse is unreliable. Applications should not depend -** on SQLITE_MISUSE returns. SQLITE_MISUSE is intended to indicate a -** a logic error in the application. Future versions of SQLite might -** panic rather than return SQLITE_MISUSE. -** -** See also: [sqlite3_bind_parameter_count()], -** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13506} The [SQL statement compiler] recognizes tokens of the forms -** "?", "?NNN", "$VVV", ":VVV", and "@VVV" as SQL parameters, -** where NNN is any sequence of one or more digits -** and where VVV is any sequence of one or more alphanumeric -** characters or "::" optionally followed by a string containing -** no spaces and contained within parentheses. -** -** {F13509} The initial value of an SQL parameter is NULL. -** -** {F13512} The index of an "?" SQL parameter is one larger than the -** largest index of SQL parameter to the left, or 1 if -** the "?" is the leftmost SQL parameter. -** -** {F13515} The index of an "?NNN" SQL parameter is the integer NNN. -** -** {F13518} The index of an ":VVV", "$VVV", or "@VVV" SQL parameter is -** the same as the index of leftmost occurrences of the same -** parameter, or one more than the largest index over all -** parameters to the left if this is the first occurrence -** of this parameter, or 1 if this is the leftmost parameter. -** -** {F13521} The [SQL statement compiler] fails with an [SQLITE_RANGE] -** error if the index of an SQL parameter is less than 1 -** or greater than the compile-time SQLITE_MAX_VARIABLE_NUMBER -** parameter. -** -** {F13524} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,V,...)] -** associate the value V with all SQL parameters having an -** index of N in the [prepared statement] S. -** -** {F13527} Calls to [sqlite3_bind_text | sqlite3_bind(S,N,...)] -** override prior calls with the same values of S and N. -** -** {F13530} Bindings established by [sqlite3_bind_text | sqlite3_bind(S,...)] -** persist across calls to [sqlite3_reset(S)]. -** -** {F13533} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds the first L -** bytes of the BLOB or string pointed to by V, when L -** is non-negative. -** -** {F13536} In calls to [sqlite3_bind_text(S,N,V,L,D)] or -** [sqlite3_bind_text16(S,N,V,L,D)] SQLite binds characters -** from V through the first zero character when L is negative. -** -** {F13539} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] when D is the special -** constant [SQLITE_STATIC], SQLite assumes that the value V -** is held in static unmanaged space that will not change -** during the lifetime of the binding. -** -** {F13542} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] when D is the special -** constant [SQLITE_TRANSIENT], the routine makes a -** private copy of the value V before it returns. -** -** {F13545} In calls to [sqlite3_bind_blob(S,N,V,L,D)], -** [sqlite3_bind_text(S,N,V,L,D)], or -** [sqlite3_bind_text16(S,N,V,L,D)] when D is a pointer to -** a function, SQLite invokes that function to destroy the -** value V after it has finished using the value V. -** -** {F13548} In calls to [sqlite3_bind_zeroblob(S,N,V,L)] the value bound -** is a BLOB of L bytes, or a zero-length BLOB if L is negative. -** -** {F13551} In calls to [sqlite3_bind_value(S,N,V)] the V argument may -** be either a [protected sqlite3_value] object or an -** [unprotected sqlite3_value] object. */ int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); int sqlite3_bind_double(sqlite3_stmt*, int, double); @@ -2988,171 +1859,98 @@ int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*); int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n); /* -** CAPI3REF: Number Of SQL Parameters {F13600} +** CAPI3REF: Number Of Host Parameters {F13600} ** -** This routine can be used to find the number of [SQL parameters] -** in a [prepared statement]. SQL parameters are tokens of the -** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as -** placeholders for values that are [sqlite3_bind_blob | bound] -** to the parameters at a later time. +** {F13601} Return the largest host parameter index in the precompiled +** statement given as the argument. {F13602} When the host parameters +** are of the forms like ":AAA", "$VVV", "@AAA", or "?", +** then they are assigned sequential increasing numbers beginning +** with one, so the value returned is the number of parameters. +** {F13603} However +** if the same host parameter name is used multiple times, each occurrance +** is given the same number, so the value returned in that case is the number +** of unique host parameter names. {F13604} If host parameters of the +** form "?NNN" are used (where NNN is an integer) then there might be +** gaps in the numbering and the value returned by this interface is +** the index of the host parameter with the largest index value. {END} ** -** This routine actually returns the index of the largest (rightmost) -** parameter. For all forms except ?NNN, this will correspond to the -** number of unique parameters. If parameters of the ?NNN are used, -** there may be gaps in the list. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_name()], and -** [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13601} The [sqlite3_bind_parameter_count(S)] interface returns -** the largest index of all SQL parameters in the -** [prepared statement] S, or 0 if S contains no SQL parameters. +** {U13605} The prepared statement must not be [sqlite3_finalize | finalized] +** prior to this routine returning. Otherwise the results are undefined +** and probably undesirable. */ int sqlite3_bind_parameter_count(sqlite3_stmt*); /* ** CAPI3REF: Name Of A Host Parameter {F13620} ** -** This routine returns a pointer to the name of the n-th -** [SQL parameter] in a [prepared statement]. -** SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" -** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" -** respectively. -** In other words, the initial ":" or "$" or "@" or "?" -** is included as part of the name. -** Parameters of the form "?" without a following integer have no name -** and are also referred to as "anonymous parameters". +** {F13621} This routine returns a pointer to the name of the n-th +** parameter in a [sqlite3_stmt | prepared statement]. {F13622} +** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** which is the string ":AAA" or "@AAA" or "$VVV". +** In other words, the initial ":" or "$" or "@" +** is included as part of the name. {F13626} +** Parameters of the form "?" or "?NNN" have no name. ** -** The first host parameter has an index of 1, not 0. +** {F13623} The first host parameter has an index of 1, not 0. ** -** If the value n is out of range or if the n-th parameter is -** nameless, then NULL is returned. The returned string is -** always in UTF-8 encoding even if the named parameter was +** {F13624} If the value n is out of range or if the n-th parameter is +** nameless, then NULL is returned. {F13625} The returned string is +** always in the UTF-8 encoding even if the named parameter was ** originally specified as UTF-16 in [sqlite3_prepare16()] or ** [sqlite3_prepare16_v2()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13621} The [sqlite3_bind_parameter_name(S,N)] interface returns -** a UTF-8 rendering of the name of the SQL parameter in -** the [prepared statement] S having index N, or -** NULL if there is no SQL parameter with index N or if the -** parameter with index N is an anonymous parameter "?". */ const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* ** CAPI3REF: Index Of A Parameter With A Given Name {F13640} ** -** Return the index of an SQL parameter given its name. The -** index value returned is suitable for use as the second -** parameter to [sqlite3_bind_blob|sqlite3_bind()]. A zero -** is returned if no matching parameter is found. The parameter -** name must be given in UTF-8 even if the original statement -** was prepared from UTF-16 text using [sqlite3_prepare16_v2()]. -** -** See also: [sqlite3_bind_blob|sqlite3_bind()], -** [sqlite3_bind_parameter_count()], and -** [sqlite3_bind_parameter_index()]. -** -** INVARIANTS: -** -** {F13641} The [sqlite3_bind_parameter_index(S,N)] interface returns -** the index of SQL parameter in the [prepared statement] -** S whose name matches the UTF-8 string N, or 0 if there is -** no match. +** {F13641} This routine returns the index of a host parameter with the +** given name. {F13642} The name must match exactly. {F13643} +** If no parameter with the given name is found, return 0. +** {F13644} Parameter names must be UTF8. */ int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* ** CAPI3REF: Reset All Bindings On A Prepared Statement {F13660} ** -** Contrary to the intuition of many, [sqlite3_reset()] does not reset -** the [sqlite3_bind_blob | bindings] on a [prepared statement]. -** Use this routine to reset all host parameters to NULL. -** -** INVARIANTS: -** -** {F13661} The [sqlite3_clear_bindings(S)] interface resets all SQL -** parameter bindings in the [prepared statement] S back to NULL. +** {F13661} Contrary to the intuition of many, [sqlite3_reset()] does not +** reset the [sqlite3_bind_blob | bindings] on a +** [sqlite3_stmt | prepared statement]. {F13662} Use this routine to +** reset all host parameters to NULL. */ int sqlite3_clear_bindings(sqlite3_stmt*); /* ** CAPI3REF: Number Of Columns In A Result Set {F13710} ** -** Return the number of columns in the result set returned by the -** [prepared statement]. This routine returns 0 if pStmt is an SQL -** statement that does not return data (for example an [UPDATE]). -** -** INVARIANTS: -** -** {F13711} The [sqlite3_column_count(S)] interface returns the number of -** columns in the result set generated by the [prepared statement] S, -** or 0 if S does not generate a result set. +** {F13711} Return the number of columns in the result set returned by the +** [sqlite3_stmt | compiled SQL statement]. {F13712} This routine returns 0 +** if pStmt is an SQL statement that does not return data (for +** example an UPDATE). */ int sqlite3_column_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Column Names In A Result Set {F13720} ** -** These routines return the name assigned to a particular column -** in the result set of a [SELECT] statement. The sqlite3_column_name() -** interface returns a pointer to a zero-terminated UTF-8 string +** {F13721} These routines return the name assigned to a particular column +** in the result set of a SELECT statement. {F13722} The sqlite3_column_name() +** interface returns a pointer to a zero-terminated UTF8 string ** and sqlite3_column_name16() returns a pointer to a zero-terminated -** UTF-16 string. The first parameter is the [prepared statement] -** that implements the [SELECT] statement. The second parameter is the -** column number. The leftmost column is number 0. +** UTF16 string. {F13723} The first parameter is the +** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** The second parameter is the column number. The left-most column is +** number 0. ** -** The returned string pointer is valid until either the [prepared statement] -** is destroyed by [sqlite3_finalize()] or until the next call to -** sqlite3_column_name() or sqlite3_column_name16() on the same column. +** {F13724} The returned string pointer is valid until either the +** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** or until the next call sqlite3_column_name() or sqlite3_column_name16() +** on the same column. ** -** If sqlite3_malloc() fails during the processing of either routine +** {F13725} If sqlite3_malloc() fails during the processing of either routine ** (for example during a conversion from UTF-8 to UTF-16) then a ** NULL pointer is returned. -** -** The name of a result column is the value of the "AS" clause for -** that column, if there is an AS clause. If there is no AS clause -** then the name of the column is unspecified and may change from -** one release of SQLite to the next. -** -** INVARIANTS: -** -** {F13721} A successful invocation of the [sqlite3_column_name(S,N)] -** interface returns the name of the Nth column (where 0 is -** the leftmost column) for the result set of the -** [prepared statement] S as a zero-terminated UTF-8 string. -** -** {F13723} A successful invocation of the [sqlite3_column_name16(S,N)] -** interface returns the name of the Nth column (where 0 is -** the leftmost column) for the result set of the -** [prepared statement] S as a zero-terminated UTF-16 string -** in the native byte order. -** -** {F13724} The [sqlite3_column_name()] and [sqlite3_column_name16()] -** interfaces return a NULL pointer if they are unable to -** allocate memory to hold their normal return strings. -** -** {F13725} If the N parameter to [sqlite3_column_name(S,N)] or -** [sqlite3_column_name16(S,N)] is out of range, then the -** interfaces return a NULL pointer. -** -** {F13726} The strings returned by [sqlite3_column_name(S,N)] and -** [sqlite3_column_name16(S,N)] are valid until the next -** call to either routine with the same S and N parameters -** or until [sqlite3_finalize(S)] is called. -** -** {F13727} When a result column of a [SELECT] statement contains -** an AS clause, the name of that column is the identifier -** to the right of the AS keyword. */ const char *sqlite3_column_name(sqlite3_stmt*, int N); const void *sqlite3_column_name16(sqlite3_stmt*, int N); @@ -3160,91 +1958,41 @@ const void *sqlite3_column_name16(sqlite3_stmt*, int N); /* ** CAPI3REF: Source Of Data In A Query Result {F13740} ** -** These routines provide a means to determine what column of what -** table in which database a result of a [SELECT] statement comes from. -** The name of the database or table or column can be returned as -** either a UTF-8 or UTF-16 string. The _database_ routines return +** {F13741} These routines provide a means to determine what column of what +** table in which database a result of a SELECT statement comes from. +** {F13742} The name of the database or table or column can be returned as +** either a UTF8 or UTF16 string. {F13743} The _database_ routines return ** the database name, the _table_ routines return the table name, and -** the origin_ routines return the column name. -** The returned string is valid until the [prepared statement] is destroyed -** using [sqlite3_finalize()] or until the same information is requested +** the origin_ routines return the column name. {F13744} +** The returned string is valid until +** the [sqlite3_stmt | prepared statement] is destroyed using +** [sqlite3_finalize()] or until the same information is requested ** again in a different encoding. ** -** The names returned are the original un-aliased names of the +** {F13745} The names returned are the original un-aliased names of the ** database, table, and column. ** -** The first argument to the following calls is a [prepared statement]. -** These functions return information about the Nth column returned by +** {F13746} The first argument to the following calls is a +** [sqlite3_stmt | compiled SQL statement]. +** {F13747} These functions return information about the Nth column returned by ** the statement, where N is the second function argument. ** -** If the Nth column returned by the statement is an expression or -** subquery and is not a column value, then all of these functions return -** NULL. These routine might also return NULL if a memory allocation error -** occurs. Otherwise, they return the name of the attached database, table -** and column that query result column was extracted from. +** {F13748} If the Nth column returned by the statement is an expression +** or subquery and is not a column value, then all of these functions +** return NULL. {F13749} Otherwise, they return the +** name of the attached database, table and column that query result +** column was extracted from. ** -** As with all other SQLite APIs, those postfixed with "16" return +** {F13750} As with all other SQLite APIs, those postfixed with "16" return ** UTF-16 encoded strings, the other functions return UTF-8. {END} ** -** These APIs are only available if the library was compiled with the -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined. +** These APIs are only available if the library was compiled with the +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. ** -** {A13751} +** {U13751} ** If two or more threads call one or more of these routines against the same ** prepared statement and column at the same time then the results are ** undefined. -** -** INVARIANTS: -** -** {F13741} The [sqlite3_column_database_name(S,N)] interface returns either -** the UTF-8 zero-terminated name of the database from which the -** Nth result column of the [prepared statement] S is extracted, -** or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13742} The [sqlite3_column_database_name16(S,N)] interface returns either -** the UTF-16 native byte order zero-terminated name of the database -** from which the Nth result column of the [prepared statement] S is -** extracted, or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13743} The [sqlite3_column_table_name(S,N)] interface returns either -** the UTF-8 zero-terminated name of the table from which the -** Nth result column of the [prepared statement] S is extracted, -** or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13744} The [sqlite3_column_table_name16(S,N)] interface returns either -** the UTF-16 native byte order zero-terminated name of the table -** from which the Nth result column of the [prepared statement] S is -** extracted, or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13745} The [sqlite3_column_origin_name(S,N)] interface returns either -** the UTF-8 zero-terminated name of the table column from which the -** Nth result column of the [prepared statement] S is extracted, -** or NULL if the Nth column of S is a general expression -** or if unable to allocate memory to store the name. -** -** {F13746} The [sqlite3_column_origin_name16(S,N)] interface returns either -** the UTF-16 native byte order zero-terminated name of the table -** column from which the Nth result column of the -** [prepared statement] S is extracted, or NULL if the Nth column -** of S is a general expression or if unable to allocate memory -** to store the name. -** -** {F13748} The return values from -** [sqlite3_column_database_name | column metadata interfaces] -** are valid for the lifetime of the [prepared statement] -** or until the encoding is changed by another metadata -** interface call for the same prepared statement and column. -** -** LIMITATIONS: -** -** {A13751} If two or more threads call one or more -** [sqlite3_column_database_name | column metadata interfaces] -** for the same [prepared statement] and result column -** at the same time then the results are undefined. */ const char *sqlite3_column_database_name(sqlite3_stmt*,int); const void *sqlite3_column_database_name16(sqlite3_stmt*,int); @@ -3256,24 +2004,24 @@ const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* ** CAPI3REF: Declared Datatype Of A Query Result {F13760} ** -** The first parameter is a [prepared statement]. -** If this statement is a [SELECT] statement and the Nth column of the -** returned result set of that [SELECT] is a table column (not an +** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** {F13761} If this statement is a SELECT statement and the Nth column of the +** returned result set of that SELECT is a table column (not an ** expression or subquery) then the declared type of the table -** column is returned. If the Nth column of the result set is an +** column is returned. {F13762} If the Nth column of the result set is an ** expression or subquery, then a NULL pointer is returned. -** The returned string is always UTF-8 encoded. {END} -** -** For example, given the database schema: +** {F13763} The returned string is always UTF-8 encoded. {END} +** For example, in the database schema: ** ** CREATE TABLE t1(c1 VARIANT); ** -** and the following statement to be compiled: +** And the following statement compiled: ** ** SELECT c1 + 1, c1 FROM t1; ** -** this routine would return the string "VARIANT" for the second result -** column (i==1), and a NULL pointer for the first result column (i==0). +** Then this routine would return the string "VARIANT" for the second +** result column (i==1), and a NULL pointer for the first result column +** (i==0). ** ** SQLite uses dynamic run-time typing. So just because a column ** is declared to contain a particular type does not mean that the @@ -3281,55 +2029,36 @@ const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); ** strongly typed, but the typing is dynamic not static. Type ** is associated with individual values, not with the containers ** used to hold those values. -** -** INVARIANTS: -** -** {F13761} A successful call to [sqlite3_column_decltype(S,N)] returns a -** zero-terminated UTF-8 string containing the declared datatype -** of the table column that appears as the Nth column (numbered -** from 0) of the result set to the [prepared statement] S. -** -** {F13762} A successful call to [sqlite3_column_decltype16(S,N)] -** returns a zero-terminated UTF-16 native byte order string -** containing the declared datatype of the table column that appears -** as the Nth column (numbered from 0) of the result set to the -** [prepared statement] S. -** -** {F13763} If N is less than 0 or N is greater than or equal to -** the number of columns in the [prepared statement] S, -** or if the Nth column of S is an expression or subquery rather -** than a table column, or if a memory allocation failure -** occurs during encoding conversions, then -** calls to [sqlite3_column_decltype(S,N)] or -** [sqlite3_column_decltype16(S,N)] return NULL. */ -const char *sqlite3_column_decltype(sqlite3_stmt*,int); +const char *sqlite3_column_decltype(sqlite3_stmt *, int i); const void *sqlite3_column_decltype16(sqlite3_stmt*,int); -/* -** CAPI3REF: Evaluate An SQL Statement {F13200} +/* +** CAPI3REF: Evaluate An SQL Statement {F13200} ** -** After a [prepared statement] has been prepared using either -** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy -** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function -** must be called one or more times to evaluate the statement. +** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** to either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or to one of +** the legacy interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], +** then this function must be called one or more times to evaluate the +** statement. ** -** The details of the behavior of the sqlite3_step() interface depend +** The details of the behavior of this sqlite3_step() interface depend ** on whether the statement was prepared using the newer "v2" interface ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the ** new "v2" interface is recommended for new applications but the legacy ** interface will continue to be supported. ** -** In the legacy interface, the return value will be either [SQLITE_BUSY], +** In the lagacy interface, the return value will be either [SQLITE_BUSY], ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE]. -** With the "v2" interface, any of the other [result codes] or -** [extended result codes] might be returned as well. +** With the "v2" interface, any of the other [SQLITE_OK | result code] +** or [SQLITE_IOERR_READ | extended result code] might be returned as +** well. ** ** [SQLITE_BUSY] means that the database engine was unable to acquire the -** database locks it needs to do its job. If the statement is a [COMMIT] +** database locks it needs to do its job. If the statement is a COMMIT ** or occurs outside of an explicit transaction, then you can retry the -** statement. If the statement is not a [COMMIT] and occurs within a +** statement. If the statement is not a COMMIT and occurs within a ** explicit transaction then you should rollback the transaction before ** continuing. ** @@ -3338,91 +2067,64 @@ const void *sqlite3_column_decltype16(sqlite3_stmt*,int); ** machine without first calling [sqlite3_reset()] to reset the virtual ** machine back to its initial state. ** -** If the SQL statement being executed returns any data, then [SQLITE_ROW] -** is returned each time a new row of data is ready for processing by the -** caller. The values may be accessed using the [column access functions]. +** If the SQL statement being executed returns any data, then +** [SQLITE_ROW] is returned each time a new row of data is ready +** for processing by the caller. The values may be accessed using +** the [sqlite3_column_int | column access functions]. ** sqlite3_step() is called again to retrieve the next row of data. -** +** ** [SQLITE_ERROR] means that a run-time error (such as a constraint ** violation) has occurred. sqlite3_step() should not be called again on ** the VM. More information may be found by calling [sqlite3_errmsg()]. -** With the legacy interface, a more specific error code (for example, +** With the legacy interface, a more specific error code (example: ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth) ** can be obtained by calling [sqlite3_reset()] on the -** [prepared statement]. In the "v2" interface, +** [sqlite3_stmt | prepared statement]. In the "v2" interface, ** the more specific error code is returned directly by sqlite3_step(). ** ** [SQLITE_MISUSE] means that the this routine was called inappropriately. -** Perhaps it was called on a [prepared statement] that has -** already been [sqlite3_finalize | finalized] or on one that had +** Perhaps it was called on a [sqlite3_stmt | prepared statement] that has +** already been [sqlite3_finalize | finalized] or on one that had ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could ** be the case that the same database connection is being used by two or ** more threads at the same moment in time. ** -** Goofy Interface Alert: In the legacy interface, the sqlite3_step() -** API always returns a generic error code, [SQLITE_ERROR], following any -** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call -** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the -** specific [error codes] that better describes the error. +** Goofy Interface Alert: +** In the legacy interface, +** the sqlite3_step() API always returns a generic error code, +** [SQLITE_ERROR], following any error other than [SQLITE_BUSY] +** and [SQLITE_MISUSE]. You must call [sqlite3_reset()] or +** [sqlite3_finalize()] in order to find one of the specific +** [SQLITE_ERROR | result codes] that better describes the error. ** We admit that this is a goofy design. The problem has been fixed ** with the "v2" interface. If you prepare all of your SQL statements ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead -** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces, -** then the more specific [error codes] are returned directly +** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the +** more specific [SQLITE_ERROR | result codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. -** -** INVARIANTS: -** -** {F13202} If the [prepared statement] S is ready to be run, then -** [sqlite3_step(S)] advances that prepared statement until -** completion or until it is ready to return another row of the -** result set, or until an [sqlite3_interrupt | interrupt] -** or a run-time error occurs. -** -** {F15304} When a call to [sqlite3_step(S)] causes the [prepared statement] -** S to run to completion, the function returns [SQLITE_DONE]. -** -** {F15306} When a call to [sqlite3_step(S)] stops because it is ready to -** return another row of the result set, it returns [SQLITE_ROW]. -** -** {F15308} If a call to [sqlite3_step(S)] encounters an -** [sqlite3_interrupt | interrupt] or a run-time error, -** it returns an appropriate error code that is not one of -** [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE]. -** -** {F15310} If an [sqlite3_interrupt | interrupt] or a run-time error -** occurs during a call to [sqlite3_step(S)] -** for a [prepared statement] S created using -** legacy interfaces [sqlite3_prepare()] or -** [sqlite3_prepare16()], then the function returns either -** [SQLITE_ERROR], [SQLITE_BUSY], or [SQLITE_MISUSE]. */ int sqlite3_step(sqlite3_stmt*); /* ** CAPI3REF: Number of columns in a result set {F13770} ** -** Returns the number of values in the current row of the result set. +** Return the number of values in the current row of the result set. ** -** INVARIANTS: -** -** {F13771} After a call to [sqlite3_step(S)] that returns [SQLITE_ROW], -** the [sqlite3_data_count(S)] routine will return the same value -** as the [sqlite3_column_count(S)] function. -** -** {F13772} After [sqlite3_step(S)] has returned any value other than -** [SQLITE_ROW] or before [sqlite3_step(S)] has been called on the -** [prepared statement] for the first time since it was -** [sqlite3_prepare | prepared] or [sqlite3_reset | reset], -** the [sqlite3_data_count(S)] routine returns zero. +** {F13771} After a call to [sqlite3_step()] that returns [SQLITE_ROW], +** this routine +** will return the same value as the [sqlite3_column_count()] function. +** {F13772} +** After [sqlite3_step()] has returned an [SQLITE_DONE], [SQLITE_BUSY], or +** a [SQLITE_ERROR | error code], or before [sqlite3_step()] has been +** called on the [sqlite3_stmt | prepared statement] for the first time, +** this routine returns zero. */ int sqlite3_data_count(sqlite3_stmt *pStmt); /* ** CAPI3REF: Fundamental Datatypes {F10265} -** KEYWORDS: SQLITE_TEXT ** -** {F10266} Every value in SQLite has one of five fundamental datatypes: +** {F10266}Every value in SQLite has one of five fundamental datatypes: ** **
          **
        • 64-bit signed integer @@ -3436,7 +2138,7 @@ int sqlite3_data_count(sqlite3_stmt *pStmt); ** ** Note that the SQLITE_TEXT constant was also used in SQLite version 2 ** for a completely different meaning. Software that links against both -** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not +** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT not ** SQLITE_TEXT. */ #define SQLITE_INTEGER 1 @@ -3451,31 +2153,31 @@ int sqlite3_data_count(sqlite3_stmt *pStmt); #define SQLITE3_TEXT 3 /* -** CAPI3REF: Result Values From A Query {F13800} -** KEYWORDS: {column access functions} +** CAPI3REF: Results Values From A Query {F13800} ** -** These routines form the "result set query" interface. +** These routines return information about +** a single column of the current result row of a query. In every +** case the first argument is a pointer to the +** [sqlite3_stmt | SQL statement] that is being +** evaluated (the [sqlite3_stmt*] that was returned from +** [sqlite3_prepare_v2()] or one of its variants) and +** the second argument is the index of the column for which information +** should be returned. The left-most column of the result set +** has an index of 0. ** -** These routines return information about a single column of the current -** result row of a query. In every case the first argument is a pointer -** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*] -** that was returned from [sqlite3_prepare_v2()] or one of its variants) -** and the second argument is the index of the column for which information -** should be returned. The leftmost column of the result set has the index 0. -** -** If the SQL statement does not currently point to a valid row, or if the -** column index is out of range, the result is undefined. +** If the SQL statement is not currently point to a valid row, or if the +** the column index is out of range, the result is undefined. ** These routines may only be called when the most recent call to ** [sqlite3_step()] has returned [SQLITE_ROW] and neither -** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently. +** [sqlite3_reset()] nor [sqlite3_finalize()] has been call subsequently. ** If any of these routines are called after [sqlite3_reset()] or ** [sqlite3_finalize()] or after [sqlite3_step()] has returned ** something other than [SQLITE_ROW], the results are undefined. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()] ** are called from a different thread while any of these routines -** are pending, then the results are undefined. +** are pending, then the results are undefined. ** -** The sqlite3_column_type() routine returns the +** The sqlite3_column_type() routine returns ** [SQLITE_INTEGER | datatype code] for the initial data type ** of the result column. The returned value is one of [SQLITE_INTEGER], ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value @@ -3485,7 +2187,7 @@ int sqlite3_data_count(sqlite3_stmt *pStmt); ** versions of SQLite may change the behavior of sqlite3_column_type() ** following a type conversion. ** -** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() +** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() ** routine returns the number of bytes in that BLOB or string. ** If the result is a UTF-16 string, then sqlite3_column_bytes() converts ** the string to UTF-8 and then returns the number of bytes. @@ -3497,27 +2199,19 @@ int sqlite3_data_count(sqlite3_stmt *pStmt); ** bytes in the string, not the number of characters. ** ** Strings returned by sqlite3_column_text() and sqlite3_column_text16(), -** even empty strings, are always zero terminated. The return -** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary +** even zero-length strings, are always zero terminated. The return +** value from sqlite3_column_blob() for a zero-length blob is an arbitrary ** pointer, possibly even a NULL pointer. ** ** The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes() -** but leaves the result in UTF-16 in native byte order instead of UTF-8. +** but leaves the result in UTF-16 instead of UTF-8. ** The zero terminator is not included in this count. ** -** The object returned by [sqlite3_column_value()] is an -** [unprotected sqlite3_value] object. An unprotected sqlite3_value object -** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()]. -** If the [unprotected sqlite3_value] object returned by -** [sqlite3_column_value()] is used in any other way, including calls -** to routines like [sqlite3_value_int()], [sqlite3_value_text()], -** or [sqlite3_value_bytes()], then the behavior is undefined. -** ** These routines attempt to convert the value where appropriate. For ** example, if the internal representation is FLOAT and a text result -** is requested, [sqlite3_snprintf()] is used internally to perform the -** conversion automatically. The following table details the conversions -** that are applied: +** is requested, [sqlite3_snprintf()] is used internally to do the conversion +** automatically. The following table details the conversions that +** are applied: ** **
          ** @@ -3529,7 +2223,7 @@ int sqlite3_data_count(sqlite3_stmt *pStmt); **
          NULL BLOB Result is NULL pointer **
          INTEGER FLOAT Convert from integer to float **
          INTEGER TEXT ASCII rendering of the integer -**
          INTEGER BLOB Same as INTEGER->TEXT +**
          INTEGER BLOB Same as for INTEGER->TEXT **
          FLOAT INTEGER Convert from float to integer **
          FLOAT TEXT ASCII rendering of the float **
          FLOAT BLOB Same as FLOAT->TEXT @@ -3544,56 +2238,57 @@ int sqlite3_data_count(sqlite3_stmt *pStmt); ** ** The table above makes reference to standard C library functions atoi() ** and atof(). SQLite does not really use these functions. It has its -** own equivalent internal routines. The atoi() and atof() names are +** on equavalent internal routines. The atoi() and atof() names are ** used in the table for brevity and because they are familiar to most ** C programmers. ** ** Note that when type conversions occur, pointers returned by prior ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or -** sqlite3_column_text16() may be invalidated. +** sqlite3_column_text16() may be invalidated. ** Type conversions and pointer invalidations might occur ** in the following cases: ** **
            -**
          • The initial content is a BLOB and sqlite3_column_text() or -** sqlite3_column_text16() is called. A zero-terminator might -** need to be added to the string.
          • -**
          • The initial content is UTF-8 text and sqlite3_column_bytes16() or -** sqlite3_column_text16() is called. The content must be converted -** to UTF-16.
          • -**
          • The initial content is UTF-16 text and sqlite3_column_bytes() or -** sqlite3_column_text() is called. The content must be converted -** to UTF-8.
          • +**
          • The initial content is a BLOB and sqlite3_column_text() +** or sqlite3_column_text16() is called. A zero-terminator might +** need to be added to the string.

          • +** +**
          • The initial content is UTF-8 text and sqlite3_column_bytes16() or +** sqlite3_column_text16() is called. The content must be converted +** to UTF-16.

          • +** +**
          • The initial content is UTF-16 text and sqlite3_column_bytes() or +** sqlite3_column_text() is called. The content must be converted +** to UTF-8.

          • **
          ** ** Conversions between UTF-16be and UTF-16le are always done in place and do ** not invalidate a prior pointer, though of course the content of the buffer ** that the prior pointer points to will have been modified. Other kinds -** of conversion are done in place when it is possible, but sometimes they -** are not possible and in those cases prior pointers are invalidated. +** of conversion are done in place when it is possible, but sometime it is +** not possible and in those cases prior pointers are invalidated. ** ** The safest and easiest to remember policy is to invoke these routines ** in one of the following ways: ** -**
            +**
              **
            • sqlite3_column_text() followed by sqlite3_column_bytes()
            • **
            • sqlite3_column_blob() followed by sqlite3_column_bytes()
            • **
            • sqlite3_column_text16() followed by sqlite3_column_bytes16()
            • -**
            +**
          ** -** In other words, you should call sqlite3_column_text(), -** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result -** into the desired format, then invoke sqlite3_column_bytes() or -** sqlite3_column_bytes16() to find the size of the result. Do not mix calls -** to sqlite3_column_text() or sqlite3_column_blob() with calls to -** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16() -** with calls to sqlite3_column_bytes(). +** In other words, you should call sqlite3_column_text(), sqlite3_column_blob(), +** or sqlite3_column_text16() first to force the result into the desired +** format, then invoke sqlite3_column_bytes() or sqlite3_column_bytes16() to +** find the size of the result. Do not mix call to sqlite3_column_text() or +** sqlite3_column_blob() with calls to sqlite3_column_bytes16(). And do not +** mix calls to sqlite3_column_text16() with calls to sqlite3_column_bytes(). ** ** The pointers returned are valid until a type conversion occurs as ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or ** [sqlite3_finalize()] is called. The memory space used to hold strings -** and BLOBs is freed automatically. Do not pass the pointers returned -** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into +** and blobs is freed automatically. Do not pass the pointers returned +** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into ** [sqlite3_free()]. ** ** If a memory allocation error occurs during the evaluation of any @@ -3601,61 +2296,6 @@ int sqlite3_data_count(sqlite3_stmt *pStmt); ** is either the integer 0, the floating point number 0.0, or a NULL ** pointer. Subsequent calls to [sqlite3_errcode()] will return ** [SQLITE_NOMEM]. -** -** INVARIANTS: -** -** {F13803} The [sqlite3_column_blob(S,N)] interface converts the -** Nth column in the current row of the result set for -** the [prepared statement] S into a BLOB and then returns a -** pointer to the converted value. -** -** {F13806} The [sqlite3_column_bytes(S,N)] interface returns the -** number of bytes in the BLOB or string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_column_blob(S,N)] or -** [sqlite3_column_text(S,N)]. -** -** {F13809} The [sqlite3_column_bytes16(S,N)] interface returns the -** number of bytes in the string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_column_text16(S,N)]. -** -** {F13812} The [sqlite3_column_double(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a floating point value and -** returns a copy of that value. -** -** {F13815} The [sqlite3_column_int(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a 64-bit signed integer and -** returns the lower 32 bits of that integer. -** -** {F13818} The [sqlite3_column_int64(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a 64-bit signed integer and -** returns a copy of that integer. -** -** {F13821} The [sqlite3_column_text(S,N)] interface converts the -** Nth column in the current row of the result set for -** the [prepared statement] S into a zero-terminated UTF-8 -** string and returns a pointer to that string. -** -** {F13824} The [sqlite3_column_text16(S,N)] interface converts the -** Nth column in the current row of the result set for the -** [prepared statement] S into a zero-terminated 2-byte -** aligned UTF-16 native byte order string and returns -** a pointer to that string. -** -** {F13827} The [sqlite3_column_type(S,N)] interface returns -** one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT], -** [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for -** the Nth column in the current row of the result set for -** the [prepared statement] S. -** -** {F13830} The [sqlite3_column_value(S,N)] interface returns a -** pointer to an [unprotected sqlite3_value] object for the -** Nth column in the current row of the result set for -** the [prepared statement] S. */ const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); int sqlite3_column_bytes(sqlite3_stmt*, int iCol); @@ -3671,86 +2311,62 @@ sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* ** CAPI3REF: Destroy A Prepared Statement Object {F13300} ** -** The sqlite3_finalize() function is called to delete a [prepared statement]. -** If the statement was executed successfully or not executed at all, then -** SQLITE_OK is returned. If execution of the statement failed then an -** [error code] or [extended error code] is returned. +** The sqlite3_finalize() function is called to delete a +** [sqlite3_stmt | compiled SQL statement]. If the statement was +** executed successfully, or not executed at all, then SQLITE_OK is returned. +** If execution of the statement failed then an +** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** is returned. ** ** This routine can be called at any point during the execution of the -** [prepared statement]. If the virtual machine has not +** [sqlite3_stmt | virtual machine]. If the virtual machine has not ** completed execution when this routine is called, that is like -** encountering an error or an [sqlite3_interrupt | interrupt]. -** Incomplete updates may be rolled back and transactions canceled, -** depending on the circumstances, and the -** [error code] returned will be [SQLITE_ABORT]. -** -** INVARIANTS: -** -** {F11302} The [sqlite3_finalize(S)] interface destroys the -** [prepared statement] S and releases all -** memory and file resources held by that object. -** -** {F11304} If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S returned an error, -** then [sqlite3_finalize(S)] returns that same error. +** encountering an error or an interrupt. (See [sqlite3_interrupt()].) +** Incomplete updates may be rolled back and transactions cancelled, +** depending on the circumstances, and the +** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT]. */ int sqlite3_finalize(sqlite3_stmt *pStmt); /* ** CAPI3REF: Reset A Prepared Statement Object {F13330} ** -** The sqlite3_reset() function is called to reset a [prepared statement] -** object back to its initial state, ready to be re-executed. +** The sqlite3_reset() function is called to reset a +** [sqlite3_stmt | compiled SQL statement] object. +** back to its initial state, ready to be re-executed. ** Any SQL statement variables that had values bound to them using ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values. ** Use [sqlite3_clear_bindings()] to reset the bindings. -** -** {F11332} The [sqlite3_reset(S)] interface resets the [prepared statement] S -** back to the beginning of its program. -** -** {F11334} If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE], -** or if [sqlite3_step(S)] has never before been called on S, -** then [sqlite3_reset(S)] returns [SQLITE_OK]. -** -** {F11336} If the most recent call to [sqlite3_step(S)] for the -** [prepared statement] S indicated an error, then -** [sqlite3_reset(S)] returns an appropriate [error code]. -** -** {F11338} The [sqlite3_reset(S)] interface does not change the values -** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S. */ int sqlite3_reset(sqlite3_stmt *pStmt); /* ** CAPI3REF: Create Or Redefine SQL Functions {F16100} -** KEYWORDS: {function creation routines} -** KEYWORDS: {application-defined SQL function} -** KEYWORDS: {application-defined SQL functions} ** -** These two functions (collectively known as "function creation routines") -** are used to add SQL functions or aggregates or to redefine the behavior -** of existing SQL functions or aggregates. The only difference between the -** two is that the second parameter, the name of the (scalar) function or -** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16 -** for sqlite3_create_function16(). +** The following two functions are used to add SQL functions or aggregates +** or to redefine the behavior of existing SQL functions or aggregates. The +** difference only between the two is that the second parameter, the +** name of the (scalar) function or aggregate, is encoded in UTF-8 for +** sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). ** -** The first parameter is the [database connection] to which the SQL -** function is to be added. If a single program uses more than one database -** connection internally, then SQL functions must be added individually to -** each database connection. +** The first argument is the [sqlite3 | database handle] that holds the +** SQL function or aggregate is to be added or redefined. If a single +** program uses more than one database handle internally, then SQL +** functions or aggregates must be added individually to each database +** handle with which they will be used. ** -** The second parameter is the name of the SQL function to be created or -** redefined. The length of the name is limited to 255 bytes, exclusive of -** the zero-terminator. Note that the name length limit is in bytes, not +** The second parameter is the name of the SQL function to be created +** or redefined. +** The length of the name is limited to 255 bytes, exclusive of the +** zero-terminator. Note that the name length limit is in bytes, not ** characters. Any attempt to create a function with a longer name -** will result in [SQLITE_ERROR] being returned. +** will result in an SQLITE_ERROR error. ** ** The third parameter is the number of arguments that the SQL function or ** aggregate takes. If this parameter is negative, then the SQL function or ** aggregate may take any number of arguments. ** -** The fourth parameter, eTextRep, specifies what +** The fourth parameter, eTextRep, specifies what ** [SQLITE_UTF8 | text encoding] this SQL function prefers for ** its parameters. Any SQL function implementation should be able to work ** work with UTF-8, UTF-16le, or UTF-16be. But some implementations may be @@ -3759,107 +2375,45 @@ int sqlite3_reset(sqlite3_stmt *pStmt); ** times with the same function but with different values of eTextRep. ** When multiple implementations of the same function are available, SQLite ** will pick the one that involves the least amount of data conversion. -** If there is only a single implementation which does not care what text -** encoding is used, then the fourth argument should be [SQLITE_ANY]. +** If there is only a single implementation which does not care what +** text encoding is used, then the fourth argument should be +** [SQLITE_ANY]. ** -** The fifth parameter is an arbitrary pointer. The implementation of the -** function can gain access to this pointer using [sqlite3_user_data()]. +** The fifth parameter is an arbitrary pointer. The implementation +** of the function can gain access to this pointer using +** [sqlite3_user_data()]. ** ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are -** pointers to C-language functions that implement the SQL function or -** aggregate. A scalar SQL function requires an implementation of the xFunc -** callback only, NULL pointers should be passed as the xStep and xFinal -** parameters. An aggregate SQL function requires an implementation of xStep -** and xFinal and NULL should be passed for xFunc. To delete an existing -** SQL function or aggregate, pass NULL for all three function callbacks. +** pointers to C-language functions that implement the SQL +** function or aggregate. A scalar SQL function requires an implementation of +** the xFunc callback only, NULL pointers should be passed as the xStep +** and xFinal parameters. An aggregate SQL function requires an implementation +** of xStep and xFinal and NULL should be passed for xFunc. To delete an +** existing SQL function or aggregate, pass NULL for all three function +** callback. ** ** It is permitted to register multiple implementations of the same ** functions with the same name but with either differing numbers of -** arguments or differing preferred text encodings. SQLite will use +** arguments or differing perferred text encodings. SQLite will use ** the implementation most closely matches the way in which the ** SQL function is used. -** -** INVARIANTS: -** -** {F16103} The [sqlite3_create_function16()] interface behaves exactly -** like [sqlite3_create_function()] in every way except that it -** interprets the zFunctionName argument as zero-terminated UTF-16 -** native byte order instead of as zero-terminated UTF-8. -** -** {F16106} A successful invocation of -** the [sqlite3_create_function(D,X,N,E,...)] interface registers -** or replaces callback functions in the [database connection] D -** used to implement the SQL function named X with N parameters -** and having a preferred text encoding of E. -** -** {F16109} A successful call to [sqlite3_create_function(D,X,N,E,P,F,S,L)] -** replaces the P, F, S, and L values from any prior calls with -** the same D, X, N, and E values. -** -** {F16112} The [sqlite3_create_function(D,X,...)] interface fails with -** a return code of [SQLITE_ERROR] if the SQL function name X is -** longer than 255 bytes exclusive of the zero terminator. -** -** {F16118} Either F must be NULL and S and L are non-NULL or else F -** is non-NULL and S and L are NULL, otherwise -** [sqlite3_create_function(D,X,N,E,P,F,S,L)] returns [SQLITE_ERROR]. -** -** {F16121} The [sqlite3_create_function(D,...)] interface fails with an -** error code of [SQLITE_BUSY] if there exist [prepared statements] -** associated with the [database connection] D. -** -** {F16124} The [sqlite3_create_function(D,X,N,...)] interface fails with an -** error code of [SQLITE_ERROR] if parameter N (specifying the number -** of arguments to the SQL function being registered) is less -** than -1 or greater than 127. -** -** {F16127} When N is non-negative, the [sqlite3_create_function(D,X,N,...)] -** interface causes callbacks to be invoked for the SQL function -** named X when the number of arguments to the SQL function is -** exactly N. -** -** {F16130} When N is -1, the [sqlite3_create_function(D,X,N,...)] -** interface causes callbacks to be invoked for the SQL function -** named X with any number of arguments. -** -** {F16133} When calls to [sqlite3_create_function(D,X,N,...)] -** specify multiple implementations of the same function X -** and when one implementation has N>=0 and the other has N=(-1) -** the implementation with a non-zero N is preferred. -** -** {F16136} When calls to [sqlite3_create_function(D,X,N,E,...)] -** specify multiple implementations of the same function X with -** the same number of arguments N but with different -** encodings E, then the implementation where E matches the -** database encoding is preferred. -** -** {F16139} For an aggregate SQL function created using -** [sqlite3_create_function(D,X,N,E,P,0,S,L)] the finalizer -** function L will always be invoked exactly once if the -** step function S is called one or more times. -** -** {F16142} When SQLite invokes either the xFunc or xStep function of -** an application-defined SQL function or aggregate created -** by [sqlite3_create_function()] or [sqlite3_create_function16()], -** then the array of [sqlite3_value] objects passed as the -** third parameter are always [protected sqlite3_value] objects. */ int sqlite3_create_function( - sqlite3 *db, + sqlite3 *, const char *zFunctionName, int nArg, int eTextRep, - void *pApp, + void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); int sqlite3_create_function16( - sqlite3 *db, + sqlite3*, const void *zFunctionName, int nArg, int eTextRep, - void *pApp, + void*, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) @@ -3905,101 +2459,40 @@ int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); ** to [sqlite3_create_function()] and [sqlite3_create_function16()] ** define callbacks that implement the SQL functions and aggregates. ** The 4th parameter to these callbacks is an array of pointers to -** [protected sqlite3_value] objects. There is one [sqlite3_value] object for +** [sqlite3_value] objects. There is one [sqlite3_value] object for ** each parameter to the SQL function. These routines are used to ** extract values from the [sqlite3_value] objects. ** -** These routines work only with [protected sqlite3_value] objects. -** Any attempt to use these routines on an [unprotected sqlite3_value] -** object results in undefined behavior. +** These routines work just like the corresponding +** [sqlite3_column_blob | sqlite3_column_* routines] except that +** these routines take a single [sqlite3_value*] pointer instead +** of an [sqlite3_stmt*] pointer and an integer column number. ** -** These routines work just like the corresponding [column access functions] -** except that these routines take a single [protected sqlite3_value] object -** pointer instead of a [sqlite3_stmt*] pointer and an integer column number. -** -** The sqlite3_value_text16() interface extracts a UTF-16 string +** The sqlite3_value_text16() interface extracts a UTF16 string ** in the native byte-order of the host machine. The ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces -** extract UTF-16 strings as big-endian and little-endian respectively. +** extract UTF16 strings as big-endian and little-endian respectively. ** ** The sqlite3_value_numeric_type() interface attempts to apply ** numeric affinity to the value. This means that an attempt is ** made to convert the value to an integer or floating point. If ** such a conversion is possible without loss of information (in other -** words, if the value is a string that looks like a number) -** then the conversion is performed. Otherwise no conversion occurs. -** The [SQLITE_INTEGER | datatype] after conversion is returned. +** words if the value is a string that looks like a number) +** then the conversion is done. Otherwise no conversion occurs. The +** [SQLITE_INTEGER | datatype] after conversion is returned. ** -** Please pay particular attention to the fact that the pointer returned -** from [sqlite3_value_blob()], [sqlite3_value_text()], or +** Please pay particular attention to the fact that the pointer that +** is returned from [sqlite3_value_blob()], [sqlite3_value_text()], or ** [sqlite3_value_text16()] can be invalidated by a subsequent call to ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()], -** or [sqlite3_value_text16()]. +** or [sqlite3_value_text16()]. ** ** These routines must be called from the same thread as -** the SQL function that supplied the [sqlite3_value*] parameters. +** the SQL function that supplied the sqlite3_value* parameters. +** Or, if the sqlite3_value* argument comes from the [sqlite3_column_value()] +** interface, then these routines should be called from the same thread +** that ran [sqlite3_column_value()]. ** -** INVARIANTS: -** -** {F15103} The [sqlite3_value_blob(V)] interface converts the -** [protected sqlite3_value] object V into a BLOB and then -** returns a pointer to the converted value. -** -** {F15106} The [sqlite3_value_bytes(V)] interface returns the -** number of bytes in the BLOB or string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_value_blob(V)] or -** [sqlite3_value_text(V)]. -** -** {F15109} The [sqlite3_value_bytes16(V)] interface returns the -** number of bytes in the string (exclusive of the -** zero terminator on the string) that was returned by the -** most recent call to [sqlite3_value_text16(V)], -** [sqlite3_value_text16be(V)], or [sqlite3_value_text16le(V)]. -** -** {F15112} The [sqlite3_value_double(V)] interface converts the -** [protected sqlite3_value] object V into a floating point value and -** returns a copy of that value. -** -** {F15115} The [sqlite3_value_int(V)] interface converts the -** [protected sqlite3_value] object V into a 64-bit signed integer and -** returns the lower 32 bits of that integer. -** -** {F15118} The [sqlite3_value_int64(V)] interface converts the -** [protected sqlite3_value] object V into a 64-bit signed integer and -** returns a copy of that integer. -** -** {F15121} The [sqlite3_value_text(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated UTF-8 -** string and returns a pointer to that string. -** -** {F15124} The [sqlite3_value_text16(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated 2-byte -** aligned UTF-16 native byte order -** string and returns a pointer to that string. -** -** {F15127} The [sqlite3_value_text16be(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated 2-byte -** aligned UTF-16 big-endian -** string and returns a pointer to that string. -** -** {F15130} The [sqlite3_value_text16le(V)] interface converts the -** [protected sqlite3_value] object V into a zero-terminated 2-byte -** aligned UTF-16 little-endian -** string and returns a pointer to that string. -** -** {F15133} The [sqlite3_value_type(V)] interface returns -** one of [SQLITE_NULL], [SQLITE_INTEGER], [SQLITE_FLOAT], -** [SQLITE_TEXT], or [SQLITE_BLOB] as appropriate for -** the [sqlite3_value] object V. -** -** {F15136} The [sqlite3_value_numeric_type(V)] interface converts -** the [protected sqlite3_value] object V into either an integer or -** a floating point value if it can do so without loss of -** information, and returns one of [SQLITE_NULL], -** [SQLITE_INTEGER], [SQLITE_FLOAT], [SQLITE_TEXT], or -** [SQLITE_BLOB] as appropriate for the -** [protected sqlite3_value] object V after the conversion attempt. */ const void *sqlite3_value_blob(sqlite3_value*); int sqlite3_value_bytes(sqlite3_value*); @@ -4018,153 +2511,81 @@ int sqlite3_value_numeric_type(sqlite3_value*); ** CAPI3REF: Obtain Aggregate Function Context {F16210} ** ** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. +** a structure for storing their state. +** {F16211} The first time the sqlite3_aggregate_context() routine is +** is called for a particular aggregate, SQLite allocates nBytes of memory +** zeros that memory, and returns a pointer to it. +** {F16212} On second and subsequent calls to sqlite3_aggregate_context() +** for the same aggregate function index, the same buffer is returned. {END} +** The implementation +** of the aggregate can use the returned buffer to accumulate data. ** -** The first time the sqlite3_aggregate_context() routine is called for a -** particular aggregate, SQLite allocates nBytes of memory, zeroes out that -** memory, and returns a pointer to it. On second and subsequent calls to -** sqlite3_aggregate_context() for the same aggregate function index, -** the same buffer is returned. The implementation of the aggregate can use -** the returned buffer to accumulate data. +** {F16213} SQLite automatically frees the allocated buffer when the aggregate +** query concludes. {END} ** -** SQLite automatically frees the allocated buffer when the aggregate -** query concludes. -** -** The first parameter should be a copy of the -** [sqlite3_context | SQL function context] that is the first parameter -** to the callback routine that implements the aggregate function. +** The first parameter should be a copy of the +** [sqlite3_context | SQL function context] that is the first +** parameter to the callback routine that implements the aggregate +** function. ** ** This routine must be called from the same thread in which ** the aggregate SQL function is running. -** -** INVARIANTS: -** -** {F16211} The first invocation of [sqlite3_aggregate_context(C,N)] for -** a particular instance of an aggregate function (for a particular -** context C) causes SQLite to allocate N bytes of memory, -** zero that memory, and return a pointer to the allocated memory. -** -** {F16213} If a memory allocation error occurs during -** [sqlite3_aggregate_context(C,N)] then the function returns 0. -** -** {F16215} Second and subsequent invocations of -** [sqlite3_aggregate_context(C,N)] for the same context pointer C -** ignore the N parameter and return a pointer to the same -** block of memory returned by the first invocation. -** -** {F16217} The memory allocated by [sqlite3_aggregate_context(C,N)] is -** automatically freed on the next call to [sqlite3_reset()] -** or [sqlite3_finalize()] for the [prepared statement] containing -** the aggregate function associated with context C. */ void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* ** CAPI3REF: User Data For Functions {F16240} ** -** The sqlite3_user_data() interface returns a copy of +** {F16241} The sqlite3_user_data() interface returns a copy of ** the pointer that was the pUserData parameter (the 5th parameter) -** of the [sqlite3_create_function()] +** of the the [sqlite3_create_function()] ** and [sqlite3_create_function16()] routines that originally ** registered the application defined function. {END} ** -** This routine must be called from the same thread in which +** {U16243} This routine must be called from the same thread in which ** the application-defined function is running. -** -** INVARIANTS: -** -** {F16243} The [sqlite3_user_data(C)] interface returns a copy of the -** P pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)] -** or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that -** registered the SQL function associated with [sqlite3_context] C. */ void *sqlite3_user_data(sqlite3_context*); -/* -** CAPI3REF: Database Connection For Functions {F16250} -** -** The sqlite3_context_db_handle() interface returns a copy of -** the pointer to the [database connection] (the 1st parameter) -** of the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines that originally -** registered the application defined function. -** -** INVARIANTS: -** -** {F16253} The [sqlite3_context_db_handle(C)] interface returns a copy of the -** D pointer from the [sqlite3_create_function(D,X,N,E,P,F,S,L)] -** or [sqlite3_create_function16(D,X,N,E,P,F,S,L)] call that -** registered the SQL function associated with [sqlite3_context] C. -*/ -sqlite3 *sqlite3_context_db_handle(sqlite3_context*); - /* ** CAPI3REF: Function Auxiliary Data {F16270} ** ** The following two functions may be used by scalar SQL functions to -** associate metadata with argument values. If the same value is passed to +** associate meta-data with argument values. If the same value is passed to ** multiple invocations of the same SQL function during query execution, under -** some circumstances the associated metadata may be preserved. This may +** some circumstances the associated meta-data may be preserved. This may ** be used, for example, to add a regular-expression matching scalar ** function. The compiled version of the regular expression is stored as -** metadata associated with the SQL value passed as the regular expression +** meta-data associated with the SQL value passed as the regular expression ** pattern. The compiled regular expression can be reused on multiple ** invocations of the same function so that the original pattern string ** does not need to be recompiled on each invocation. ** -** The sqlite3_get_auxdata() interface returns a pointer to the metadata +** {F16271} +** The sqlite3_get_auxdata() interface returns a pointer to the meta-data ** associated by the sqlite3_set_auxdata() function with the Nth argument -** value to the application-defined function. If no metadata has been ever -** been set for the Nth argument of the function, or if the corresponding -** function parameter has changed since the meta-data was set, -** then sqlite3_get_auxdata() returns a NULL pointer. +** value to the application-defined function. +** {F16272} If no meta-data has been ever been set for the Nth +** argument of the function, or if the cooresponding function parameter +** has changed since the meta-data was set, then sqlite3_get_auxdata() +** returns a NULL pointer. ** -** The sqlite3_set_auxdata() interface saves the metadata -** pointed to by its 3rd parameter as the metadata for the N-th -** argument of the application-defined function. Subsequent +** {F16275} The sqlite3_set_auxdata() interface saves the meta-data +** pointed to by its 3rd parameter as the meta-data for the N-th +** argument of the application-defined function. {END} Subsequent ** calls to sqlite3_get_auxdata() might return this data, if it has -** not been destroyed. -** If it is not NULL, SQLite will invoke the destructor +** not been destroyed. +** {F16277} If it is not NULL, SQLite will invoke the destructor ** function given by the 4th parameter to sqlite3_set_auxdata() on -** the metadata when the corresponding function parameter changes -** or when the SQL statement completes, whichever comes first. +** the meta-data when the corresponding function parameter changes +** or when the SQL statement completes, whichever comes first. {END} ** -** SQLite is free to call the destructor and drop metadata on any -** parameter of any function at any time. The only guarantee is that -** the destructor will be called before the metadata is dropped. -** -** In practice, metadata is preserved between function calls for +** In practice, meta-data is preserved between function calls for ** expressions that are constant at compile time. This includes literal ** values and SQL variables. ** ** These routines must be called from the same thread in which ** the SQL function is running. -** -** INVARIANTS: -** -** {F16272} The [sqlite3_get_auxdata(C,N)] interface returns a pointer -** to metadata associated with the Nth parameter of the SQL function -** whose context is C, or NULL if there is no metadata associated -** with that parameter. -** -** {F16274} The [sqlite3_set_auxdata(C,N,P,D)] interface assigns a metadata -** pointer P to the Nth parameter of the SQL function with context C. -** -** {F16276} SQLite will invoke the destructor D with a single argument -** which is the metadata pointer P following a call to -** [sqlite3_set_auxdata(C,N,P,D)] when SQLite ceases to hold -** the metadata. -** -** {F16277} SQLite ceases to hold metadata for an SQL function parameter -** when the value of that parameter changes. -** -** {F16278} When [sqlite3_set_auxdata(C,N,P,D)] is invoked, the destructor -** is called for any prior metadata associated with the same function -** context C and parameter N. -** -** {F16279} SQLite will call destructors for any metadata it is holding -** in a particular [prepared statement] S when either -** [sqlite3_reset(S)] or [sqlite3_finalize(S)] is called. */ void *sqlite3_get_auxdata(sqlite3_context*, int N); void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); @@ -4173,10 +2594,10 @@ void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*)); /* ** CAPI3REF: Constants Defining Special Destructor Behavior {F10280} ** -** These are special values for the destructor that is passed in as the +** These are special value for the destructor that is passed in as the ** final argument to routines like [sqlite3_result_blob()]. If the destructor ** argument is SQLITE_STATIC, it means that the content pointer is constant -** and will never change. It does not need to be destroyed. The +** and will never change. It does not need to be destroyed. The ** SQLITE_TRANSIENT value means that the content will likely change in ** the near future and that SQLite should make its own private copy of ** the content before returning. @@ -4196,197 +2617,97 @@ typedef void (*sqlite3_destructor_type)(void*); ** [sqlite3_create_function()] and [sqlite3_create_function16()] ** for additional information. ** -** These functions work very much like the [parameter binding] family of -** functions used to bind values to host parameters in prepared statements. -** Refer to the [SQL parameter] documentation for additional information. +** These functions work very much like the +** [sqlite3_bind_blob | sqlite3_bind_*] family of functions used +** to bind values to host parameters in prepared statements. +** Refer to the +** [sqlite3_bind_blob | sqlite3_bind_* documentation] for +** additional information. ** -** The sqlite3_result_blob() interface sets the result from -** an application-defined function to be the BLOB whose content is pointed +** {F16402} The sqlite3_result_blob() interface sets the result from +** an application defined function to be the BLOB whose content is pointed ** to by the second parameter and which is N bytes long where N is the -** third parameter. -** -** The sqlite3_result_zeroblob() interfaces set the result of -** the application-defined function to be a BLOB containing all zero +** third parameter. +** {F16403} The sqlite3_result_zeroblob() inerfaces set the result of +** the application defined function to be a BLOB containing all zero ** bytes and N bytes in size, where N is the value of the 2nd parameter. ** -** The sqlite3_result_double() interface sets the result from -** an application-defined function to be a floating point value specified +** {F16407} The sqlite3_result_double() interface sets the result from +** an application defined function to be a floating point value specified ** by its 2nd argument. ** -** The sqlite3_result_error() and sqlite3_result_error16() functions +** {F16409} The sqlite3_result_error() and sqlite3_result_error16() functions ** cause the implemented SQL function to throw an exception. -** SQLite uses the string pointed to by the +** {F16411} SQLite uses the string pointed to by the ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16() -** as the text of an error message. SQLite interprets the error -** message string from sqlite3_result_error() as UTF-8. SQLite -** interprets the string from sqlite3_result_error16() as UTF-16 in native -** byte order. If the third parameter to sqlite3_result_error() +** as the text of an error message. {F16412} SQLite interprets the error +** message string from sqlite3_result_error() as UTF8. {F16413} SQLite +** interprets the string from sqlite3_result_error16() as UTF16 in native +** byte order. {F16414} If the third parameter to sqlite3_result_error() ** or sqlite3_result_error16() is negative then SQLite takes as the error ** message all text up through the first zero character. -** If the third parameter to sqlite3_result_error() or +** {F16415} If the third parameter to sqlite3_result_error() or ** sqlite3_result_error16() is non-negative then SQLite takes that many ** bytes (not characters) from the 2nd parameter as the error message. -** The sqlite3_result_error() and sqlite3_result_error16() -** routines make a private copy of the error message text before -** they return. Hence, the calling function can deallocate or +** {F16417} The sqlite3_result_error() and sqlite3_result_error16() +** routines make a copy private copy of the error message text before +** they return. {END} Hence, the calling function can deallocate or ** modify the text after they return without harm. -** The sqlite3_result_error_code() function changes the error code -** returned by SQLite as a result of an error in a function. By default, -** the error code is SQLITE_ERROR. A subsequent call to sqlite3_result_error() -** or sqlite3_result_error16() resets the error code to SQLITE_ERROR. ** -** The sqlite3_result_toobig() interface causes SQLite to throw an error -** indicating that a string or BLOB is to long to represent. +** {F16421} The sqlite3_result_toobig() interface causes SQLite +** to throw an error indicating that a string or BLOB is to long +** to represent. {F16422} The sqlite3_result_nomem() interface +** causes SQLite to throw an exception indicating that the a +** memory allocation failed. ** -** The sqlite3_result_nomem() interface causes SQLite to throw an error -** indicating that a memory allocation failed. -** -** The sqlite3_result_int() interface sets the return value +** {F16431} The sqlite3_result_int() interface sets the return value ** of the application-defined function to be the 32-bit signed integer ** value given in the 2nd argument. -** The sqlite3_result_int64() interface sets the return value +** {F16432} The sqlite3_result_int64() interface sets the return value ** of the application-defined function to be the 64-bit signed integer ** value given in the 2nd argument. ** -** The sqlite3_result_null() interface sets the return value +** {F16437} The sqlite3_result_null() interface sets the return value ** of the application-defined function to be NULL. ** -** The sqlite3_result_text(), sqlite3_result_text16(), +** {F16441} The sqlite3_result_text(), sqlite3_result_text16(), ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces ** set the return value of the application-defined function to be ** a text string which is represented as UTF-8, UTF-16 native byte order, ** UTF-16 little endian, or UTF-16 big endian, respectively. -** SQLite takes the text result from the application from +** {F16442} SQLite takes the text result from the application from ** the 2nd parameter of the sqlite3_result_text* interfaces. -** If the 3rd parameter to the sqlite3_result_text* interfaces -** is negative, then SQLite takes result text from the 2nd parameter +** {F16444} If the 3rd parameter to the sqlite3_result_text* interfaces +** is negative, then SQLite takes result text from the 2nd parameter ** through the first zero character. -** If the 3rd parameter to the sqlite3_result_text* interfaces +** {F16447} If the 3rd parameter to the sqlite3_result_text* interfaces ** is non-negative, then as many bytes (not characters) of the text ** pointed to by the 2nd parameter are taken as the application-defined ** function result. -** If the 4th parameter to the sqlite3_result_text* interfaces +** {F16451} If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that -** function as the destructor on the text or BLOB result when it has +** function as the destructor on the text or blob result when it has ** finished using that result. -** If the 4th parameter to the sqlite3_result_text* interfaces or -** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite -** assumes that the text or BLOB result is in constant space and does not -** copy the it or call a destructor when it has finished using that result. -** If the 4th parameter to the sqlite3_result_text* interfaces +** {F16453} If the 4th parameter to the sqlite3_result_text* interfaces +** or sqlite3_result_blob is the special constant SQLITE_STATIC, then +** SQLite assumes that the text or blob result is constant space and +** does not copy the space or call a destructor when it has +** finished using that result. +** {F16454} If the 4th parameter to the sqlite3_result_text* interfaces ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT ** then SQLite makes a copy of the result into space obtained from ** from [sqlite3_malloc()] before it returns. ** -** The sqlite3_result_value() interface sets the result of -** the application-defined function to be a copy the -** [unprotected sqlite3_value] object specified by the 2nd parameter. The +** {F16461} The sqlite3_result_value() interface sets the result of +** the application-defined function to be a copy the [sqlite3_value] +** object specified by the 2nd parameter. {F16463} The ** sqlite3_result_value() interface makes a copy of the [sqlite3_value] -** so that the [sqlite3_value] specified in the parameter may change or +** so that [sqlite3_value] specified in the parameter may change or ** be deallocated after sqlite3_result_value() returns without harm. -** A [protected sqlite3_value] object may always be used where an -** [unprotected sqlite3_value] object is required, so either -** kind of [sqlite3_value] object can be used with this interface. ** -** If these routines are called from within the different thread -** than the one containing the application-defined function that received +** {U16491} These routines are called from within the different thread +** than the one containing the application-defined function that recieved ** the [sqlite3_context] pointer, the results are undefined. -** -** INVARIANTS: -** -** {F16403} The default return value from any SQL function is NULL. -** -** {F16406} The [sqlite3_result_blob(C,V,N,D)] interface changes the -** return value of function C to be a BLOB that is N bytes -** in length and with content pointed to by V. -** -** {F16409} The [sqlite3_result_double(C,V)] interface changes the -** return value of function C to be the floating point value V. -** -** {F16412} The [sqlite3_result_error(C,V,N)] interface changes the return -** value of function C to be an exception with error code -** [SQLITE_ERROR] and a UTF-8 error message copied from V up to the -** first zero byte or until N bytes are read if N is positive. -** -** {F16415} The [sqlite3_result_error16(C,V,N)] interface changes the return -** value of function C to be an exception with error code -** [SQLITE_ERROR] and a UTF-16 native byte order error message -** copied from V up to the first zero terminator or until N bytes -** are read if N is positive. -** -** {F16418} The [sqlite3_result_error_toobig(C)] interface changes the return -** value of the function C to be an exception with error code -** [SQLITE_TOOBIG] and an appropriate error message. -** -** {F16421} The [sqlite3_result_error_nomem(C)] interface changes the return -** value of the function C to be an exception with error code -** [SQLITE_NOMEM] and an appropriate error message. -** -** {F16424} The [sqlite3_result_error_code(C,E)] interface changes the return -** value of the function C to be an exception with error code E. -** The error message text is unchanged. -** -** {F16427} The [sqlite3_result_int(C,V)] interface changes the -** return value of function C to be the 32-bit integer value V. -** -** {F16430} The [sqlite3_result_int64(C,V)] interface changes the -** return value of function C to be the 64-bit integer value V. -** -** {F16433} The [sqlite3_result_null(C)] interface changes the -** return value of function C to be NULL. -** -** {F16436} The [sqlite3_result_text(C,V,N,D)] interface changes the -** return value of function C to be the UTF-8 string -** V up to the first zero if N is negative -** or the first N bytes of V if N is non-negative. -** -** {F16439} The [sqlite3_result_text16(C,V,N,D)] interface changes the -** return value of function C to be the UTF-16 native byte order -** string V up to the first zero if N is negative -** or the first N bytes of V if N is non-negative. -** -** {F16442} The [sqlite3_result_text16be(C,V,N,D)] interface changes the -** return value of function C to be the UTF-16 big-endian -** string V up to the first zero if N is negative -** or the first N bytes or V if N is non-negative. -** -** {F16445} The [sqlite3_result_text16le(C,V,N,D)] interface changes the -** return value of function C to be the UTF-16 little-endian -** string V up to the first zero if N is negative -** or the first N bytes of V if N is non-negative. -** -** {F16448} The [sqlite3_result_value(C,V)] interface changes the -** return value of function C to be the [unprotected sqlite3_value] -** object V. -** -** {F16451} The [sqlite3_result_zeroblob(C,N)] interface changes the -** return value of function C to be an N-byte BLOB of all zeros. -** -** {F16454} The [sqlite3_result_error()] and [sqlite3_result_error16()] -** interfaces make a copy of their error message strings before -** returning. -** -** {F16457} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)], -** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)], -** [sqlite3_result_text16be(C,V,N,D)], or -** [sqlite3_result_text16le(C,V,N,D)] is the constant [SQLITE_STATIC] -** then no destructor is ever called on the pointer V and SQLite -** assumes that V is immutable. -** -** {F16460} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)], -** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)], -** [sqlite3_result_text16be(C,V,N,D)], or -** [sqlite3_result_text16le(C,V,N,D)] is the constant -** [SQLITE_TRANSIENT] then the interfaces makes a copy of the -** content of V and retains the copy. -** -** {F16463} If the D destructor parameter to [sqlite3_result_blob(C,V,N,D)], -** [sqlite3_result_text(C,V,N,D)], [sqlite3_result_text16(C,V,N,D)], -** [sqlite3_result_text16be(C,V,N,D)], or -** [sqlite3_result_text16le(C,V,N,D)] is some value other than -** the constants [SQLITE_STATIC] and [SQLITE_TRANSIENT] then -** SQLite will invoke the destructor D with V as its only argument -** when it has finished with the V value. */ void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); void sqlite3_result_double(sqlite3_context*, double); @@ -4394,7 +2715,6 @@ void sqlite3_result_error(sqlite3_context*, const char*, int); void sqlite3_result_error16(sqlite3_context*, const void*, int); void sqlite3_result_error_toobig(sqlite3_context*); void sqlite3_result_error_nomem(sqlite3_context*); -void sqlite3_result_error_code(sqlite3_context*, int); void sqlite3_result_int(sqlite3_context*, int); void sqlite3_result_int64(sqlite3_context*, sqlite3_int64); void sqlite3_result_null(sqlite3_context*); @@ -4408,93 +2728,52 @@ void sqlite3_result_zeroblob(sqlite3_context*, int n); /* ** CAPI3REF: Define New Collating Sequences {F16600} ** +** {F16601} ** These functions are used to add new collation sequences to the -** [database connection] specified as the first argument. +** [sqlite3*] handle specified as the first argument. ** +** {F16602} ** The name of the new collation sequence is specified as a UTF-8 string ** for sqlite3_create_collation() and sqlite3_create_collation_v2() -** and a UTF-16 string for sqlite3_create_collation16(). In all cases +** and a UTF-16 string for sqlite3_create_collation16(). {F16603} In all cases ** the name is passed as the second function argument. ** +** {F16604} ** The third argument may be one of the constants [SQLITE_UTF8], ** [SQLITE_UTF16LE] or [SQLITE_UTF16BE], indicating that the user-supplied ** routine expects to be passed pointers to strings encoded using UTF-8, -** UTF-16 little-endian, or UTF-16 big-endian, respectively. The +** UTF-16 little-endian or UTF-16 big-endian respectively. {F16605} The ** third argument might also be [SQLITE_UTF16_ALIGNED] to indicate that ** the routine expects pointers to 16-bit word aligned strings -** of UTF-16 in the native byte order of the host computer. +** of UTF16 in the native byte order of the host computer. ** +** {F16607} ** A pointer to the user supplied routine must be passed as the fifth -** argument. If it is NULL, this is the same as deleting the collation +** argument. {F16609} If it is NULL, this is the same as deleting the collation ** sequence (so that SQLite cannot call it anymore). -** Each time the application supplied function is invoked, it is passed -** as its first parameter a copy of the void* passed as the fourth argument -** to sqlite3_create_collation() or sqlite3_create_collation16(). +** {F16611} Each time the application +** supplied function is invoked, it is passed a copy of the void* passed as +** the fourth argument to sqlite3_create_collation() or +** sqlite3_create_collation16() as its first parameter. ** +** {F16612} ** The remaining arguments to the application-supplied routine are two strings, -** each represented by a (length, data) pair and encoded in the encoding +** each represented by a [length, data] pair and encoded in the encoding ** that was passed as the third argument when the collation sequence was -** registered. {END} The application defined collation routine should -** return negative, zero or positive if the first string is less than, -** equal to, or greater than the second string. i.e. (STRING1 - STRING2). +** registered. {END} The application defined collation routine should +** return negative, zero or positive if +** the first string is less than, equal to, or greater than the second +** string. i.e. (STRING1 - STRING2). ** +** {F16615} ** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** except that it takes an extra argument which is a destructor for -** the collation. The destructor is called when the collation is +** excapt that it takes an extra argument which is a destructor for +** the collation. {F16617} The destructor is called when the collation is ** destroyed and is passed a copy of the fourth parameter void* pointer ** of the sqlite3_create_collation_v2(). -** Collations are destroyed when they are overridden by later calls to the -** collation creation functions or when the [database connection] is closed -** using [sqlite3_close()]. -** -** INVARIANTS: -** -** {F16603} A successful call to the -** [sqlite3_create_collation_v2(B,X,E,P,F,D)] interface -** registers function F as the comparison function used to -** implement collation X on the [database connection] B for -** databases having encoding E. -** -** {F16604} SQLite understands the X parameter to -** [sqlite3_create_collation_v2(B,X,E,P,F,D)] as a zero-terminated -** UTF-8 string in which case is ignored for ASCII characters and -** is significant for non-ASCII characters. -** -** {F16606} Successive calls to [sqlite3_create_collation_v2(B,X,E,P,F,D)] -** with the same values for B, X, and E, override prior values -** of P, F, and D. -** -** {F16609} If the destructor D in [sqlite3_create_collation_v2(B,X,E,P,F,D)] -** is not NULL then it is called with argument P when the -** collating function is dropped by SQLite. -** -** {F16612} A collating function is dropped when it is overloaded. -** -** {F16615} A collating function is dropped when the database connection -** is closed using [sqlite3_close()]. -** -** {F16618} The pointer P in [sqlite3_create_collation_v2(B,X,E,P,F,D)] -** is passed through as the first parameter to the comparison -** function F for all subsequent invocations of F. -** -** {F16621} A call to [sqlite3_create_collation(B,X,E,P,F)] is exactly -** the same as a call to [sqlite3_create_collation_v2()] with -** the same parameters and a NULL destructor. -** -** {F16624} Following a [sqlite3_create_collation_v2(B,X,E,P,F,D)], -** SQLite uses the comparison function F for all text comparison -** operations on the [database connection] B on text values that -** use the collating sequence named X. -** -** {F16627} The [sqlite3_create_collation16(B,X,E,P,F)] works the same -** as [sqlite3_create_collation(B,X,E,P,F)] except that the -** collation name X is understood as UTF-16 in native byte order -** instead of UTF-8. -** -** {F16630} When multiple comparison functions are available for the same -** collating sequence, SQLite chooses the one whose text encoding -** requires the least amount of conversion from the default -** text encoding of the database. +** {F16618} Collations are destroyed when +** they are overridden by later calls to the collation creation functions +** or when the [sqlite3*] database handle is closed using [sqlite3_close()]. */ int sqlite3_create_collation( sqlite3*, @@ -4513,7 +2792,7 @@ int sqlite3_create_collation_v2( ); int sqlite3_create_collation16( sqlite3*, - const void *zName, + const char *zName, int eTextRep, void*, int(*xCompare)(void*,int,const void*,int,const void*) @@ -4522,47 +2801,31 @@ int sqlite3_create_collation16( /* ** CAPI3REF: Collation Needed Callbacks {F16700} ** +** {F16701} ** To avoid having to register all collation sequences before a database ** can be used, a single callback function may be registered with the -** [database connection] to be called whenever an undefined collation -** sequence is required. +** database handle to be called whenever an undefined collation sequence is +** required. ** +** {F16702} ** If the function is registered using the sqlite3_collation_needed() API, ** then it is passed the names of undefined collation sequences as strings -** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, -** the names are passed as UTF-16 in machine native byte order. -** A call to either function replaces any existing callback. +** encoded in UTF-8. {F16703} If sqlite3_collation_needed16() is used, the names +** are passed as UTF-16 in machine native byte order. {F16704} A call to either +** function replaces any existing callback. ** -** When the callback is invoked, the first argument passed is a copy +** {F16705} When the callback is invoked, the first argument passed is a copy ** of the second argument to sqlite3_collation_needed() or -** sqlite3_collation_needed16(). The second argument is the database -** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE], -** or [SQLITE_UTF16LE], indicating the most desirable form of the collation -** sequence function required. The fourth parameter is the name of the -** required collation sequence. +** sqlite3_collation_needed16(). {F16706} The second argument is the database +** handle. {F16707} The third argument is one of [SQLITE_UTF8], +** [SQLITE_UTF16BE], or [SQLITE_UTF16LE], indicating the most +** desirable form of the collation sequence function required. +** {F16708} The fourth parameter is the name of the +** required collation sequence. {END} ** ** The callback function should register the desired collation using ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or ** [sqlite3_create_collation_v2()]. -** -** INVARIANTS: -** -** {F16702} A successful call to [sqlite3_collation_needed(D,P,F)] -** or [sqlite3_collation_needed16(D,P,F)] causes -** the [database connection] D to invoke callback F with first -** parameter P whenever it needs a comparison function for a -** collating sequence that it does not know about. -** -** {F16704} Each successful call to [sqlite3_collation_needed()] or -** [sqlite3_collation_needed16()] overrides the callback registered -** on the same [database connection] by prior calls to either -** interface. -** -** {F16706} The name of the requested collating function passed in the -** 4th parameter to the callback is in UTF-8 if the callback -** was registered using [sqlite3_collation_needed()] and -** is in UTF-16 native byte order if the callback was -** registered using [sqlite3_collation_needed16()]. */ int sqlite3_collation_needed( sqlite3*, @@ -4601,42 +2864,32 @@ int sqlite3_rekey( ); /* -** CAPI3REF: Suspend Execution For A Short Time {F10530} +** CAPI3REF: Suspend Execution For A Short Time {F10530} ** -** The sqlite3_sleep() function causes the current thread to suspend execution +** {F10531} The sqlite3_sleep() function +** causes the current thread to suspend execution ** for at least a number of milliseconds specified in its parameter. ** -** If the operating system does not support sleep requests with -** millisecond time resolution, then the time will be rounded up to -** the nearest second. The number of milliseconds of sleep actually +** {F10532} If the operating system does not support sleep requests with +** millisecond time resolution, then the time will be rounded up to +** the nearest second. {F10533} The number of milliseconds of sleep actually ** requested from the operating system is returned. ** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -** -** INVARIANTS: -** -** {F10533} The [sqlite3_sleep(M)] interface invokes the xSleep -** method of the default [sqlite3_vfs|VFS] in order to -** suspend execution of the current thread for at least -** M milliseconds. -** -** {F10536} The [sqlite3_sleep(M)] interface returns the number of -** milliseconds of sleep actually requested of the operating -** system, which might be larger than the parameter M. +** {F10534} SQLite implements this interface by calling the xSleep() +** method of the default [sqlite3_vfs] object. {END} */ int sqlite3_sleep(int); /* -** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} +** CAPI3REF: Name Of The Folder Holding Temporary Files {F10310} ** ** If this global variable is made to point to a string which is -** the name of a folder (a.k.a. directory), then all temporary files +** the name of a folder (a.ka. directory), then all temporary files ** created by SQLite will be placed in that directory. If this variable -** is a NULL pointer, then SQLite performs a search for an appropriate -** temporary file directory. +** is NULL pointer, then SQLite does a search for an appropriate temporary +** file directory. ** -** It is not safe to modify this variable once a [database connection] +** It is not safe to modify this variable once a database connection ** has been opened. It is intended that this variable be set once ** as part of process initialization and before any SQLite interface ** routines have been call and remain unchanged thereafter. @@ -4644,155 +2897,71 @@ int sqlite3_sleep(int); SQLITE_EXTERN char *sqlite3_temp_directory; /* -** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} -** KEYWORDS: {autocommit mode} +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} ** -** The sqlite3_get_autocommit() interface returns non-zero or +** {F12931} The sqlite3_get_autocommit() interfaces returns non-zero or ** zero if the given database connection is or is not in autocommit mode, -** respectively. Autocommit mode is on by default. -** Autocommit mode is disabled by a [BEGIN] statement. -** Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK]. +** respectively. {F12932} Autocommit mode is on +** by default. {F12933} Autocommit mode is disabled by a BEGIN statement. +** {F12934} Autocommit mode is reenabled by a COMMIT or ROLLBACK. {END} ** ** If certain kinds of errors occur on a statement within a multi-statement -** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR], +** transactions (errors including [SQLITE_FULL], [SQLITE_IOERR], ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the -** transaction might be rolled back automatically. The only way to -** find out whether SQLite automatically rolled back the transaction after -** an error is to use this function. +** transaction might be rolled back automatically. {F12935} The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. {END} ** -** INVARIANTS: -** -** {F12931} The [sqlite3_get_autocommit(D)] interface returns non-zero or -** zero if the [database connection] D is or is not in autocommit -** mode, respectively. -** -** {F12932} Autocommit mode is on by default. -** -** {F12933} Autocommit mode is disabled by a successful [BEGIN] statement. -** -** {F12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK] -** statement. -** -** LIMITATIONS: -** -** {A12936} If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. {END} */ int sqlite3_get_autocommit(sqlite3*); /* -** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} ** -** The sqlite3_db_handle interface returns the [database connection] handle -** to which a [prepared statement] belongs. The database handle returned by -** sqlite3_db_handle is the same database handle that was the first argument -** to the [sqlite3_prepare_v2()] call (or its variants) that was used to -** create the statement in the first place. -** -** INVARIANTS: -** -** {F13123} The [sqlite3_db_handle(S)] interface returns a pointer -** to the [database connection] associated with the -** [prepared statement] S. +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [sqlite3_stmt | prepared statement] belongs. +** {F13122} the database handle returned by sqlite3_db_handle +** is the same database handle that was +** the first argument to the [sqlite3_prepare_v2()] or its variants +** that was used to create the statement in the first place. */ sqlite3 *sqlite3_db_handle(sqlite3_stmt*); -/* -** CAPI3REF: Find the next prepared statement {F13140} -** -** This interface returns a pointer to the next [prepared statement] after -** pStmt associated with the [database connection] pDb. If pStmt is NULL -** then this interface returns a pointer to the first prepared statement -** associated with the database connection pDb. If no prepared statement -** satisfies the conditions of this routine, it returns NULL. -** -** INVARIANTS: -** -** {F13143} If D is a [database connection] that holds one or more -** unfinalized [prepared statements] and S is a NULL pointer, -** then [sqlite3_next_stmt(D, S)] routine shall return a pointer -** to one of the prepared statements associated with D. -** -** {F13146} If D is a [database connection] that holds no unfinalized -** [prepared statements] and S is a NULL pointer, then -** [sqlite3_next_stmt(D, S)] routine shall return a NULL pointer. -** -** {F13149} If S is a [prepared statement] in the [database connection] D -** and S is not the last prepared statement in D, then -** [sqlite3_next_stmt(D, S)] routine shall return a pointer -** to the next prepared statement in D after S. -** -** {F13152} If S is the last [prepared statement] in the -** [database connection] D then the [sqlite3_next_stmt(D, S)] -** routine shall return a NULL pointer. -*/ -sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); /* ** CAPI3REF: Commit And Rollback Notification Callbacks {F12950} ** -** The sqlite3_commit_hook() interface registers a callback +** {F12951} The sqlite3_commit_hook() interface registers a callback ** function to be invoked whenever a transaction is committed. -** Any callback set by a previous call to sqlite3_commit_hook() +** {F12952} Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. -** The sqlite3_rollback_hook() interface registers a callback +** {F12953} The sqlite3_rollback_hook() interface registers a callback ** function to be invoked whenever a transaction is committed. -** Any callback set by a previous call to sqlite3_commit_hook() +** {F12954} Any callback set by a previous call to sqlite3_commit_hook() ** for the same database connection is overridden. -** The pArg argument is passed through to the callback. -** If the callback on a commit hook function returns non-zero, -** then the commit is converted into a rollback. +** {F12956} The pArg argument is passed through +** to the callback. {F12957} If the callback on a commit hook function +** returns non-zero, then the commit is converted into a rollback. ** -** If another function was previously registered, its +** {F12958} If another function was previously registered, its ** pArg value is returned. Otherwise NULL is returned. ** -** Registering a NULL function disables the callback. +** {F12959} Registering a NULL function disables the callback. ** -** For the purposes of this API, a transaction is said to have been +** {F12961} For the purposes of this API, a transaction is said to have been ** rolled back if an explicit "ROLLBACK" statement is executed, or ** an error or constraint causes an implicit rollback to occur. -** The rollback callback is not invoked if a transaction is +** {F12962} The rollback callback is not invoked if a transaction is ** automatically rolled back because the database connection is closed. -** The rollback callback is not invoked if a transaction is +** {F12964} The rollback callback is not invoked if a transaction is ** rolled back because a commit callback returned non-zero. -** Check on this +** Check on this {END} ** -** INVARIANTS: -** -** {F12951} The [sqlite3_commit_hook(D,F,P)] interface registers the -** callback function F to be invoked with argument P whenever -** a transaction commits on the [database connection] D. -** -** {F12952} The [sqlite3_commit_hook(D,F,P)] interface returns the P argument -** from the previous call with the same [database connection] D, -** or NULL on the first call for a particular database connection D. -** -** {F12953} Each call to [sqlite3_commit_hook()] overwrites the callback -** registered by prior calls. -** -** {F12954} If the F argument to [sqlite3_commit_hook(D,F,P)] is NULL -** then the commit hook callback is canceled and no callback -** is invoked when a transaction commits. -** -** {F12955} If the commit callback returns non-zero then the commit is -** converted into a rollback. -** -** {F12961} The [sqlite3_rollback_hook(D,F,P)] interface registers the -** callback function F to be invoked with argument P whenever -** a transaction rolls back on the [database connection] D. -** -** {F12962} The [sqlite3_rollback_hook(D,F,P)] interface returns the P -** argument from the previous call with the same -** [database connection] D, or NULL on the first call -** for a particular database connection D. -** -** {F12963} Each call to [sqlite3_rollback_hook()] overwrites the callback -** registered by prior calls. -** -** {F12964} If the F argument to [sqlite3_rollback_hook(D,F,P)] is NULL -** then the rollback hook callback is canceled and no callback -** is invoked when a transaction rolls back. +** These are experimental interfaces and are subject to change. */ void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); @@ -4800,60 +2969,32 @@ void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*); /* ** CAPI3REF: Data Change Notification Callbacks {F12970} ** -** The sqlite3_update_hook() interface registers a callback function -** with the [database connection] identified by the first argument -** to be invoked whenever a row is updated, inserted or deleted. -** Any callback set by a previous call to this function -** for the same database connection is overridden. +** {F12971} The sqlite3_update_hook() interface +** registers a callback function with the database connection identified by the +** first argument to be invoked whenever a row is updated, inserted or deleted. +** {F12972} Any callback set by a previous call to this function for the same +** database connection is overridden. ** -** The second argument is a pointer to the function to invoke when a -** row is updated, inserted or deleted. -** The first argument to the callback is a copy of the third argument -** to sqlite3_update_hook(). -** The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE], -** or [SQLITE_UPDATE], depending on the operation that caused the callback -** to be invoked. -** The third and fourth arguments to the callback contain pointers to the -** database and table name containing the affected row. -** The final callback parameter is the rowid of the row. In the case of -** an update, this is the rowid after the update takes place. +** {F12974} The second argument is a pointer to the function to invoke when a +** row is updated, inserted or deleted. +** {F12976} The first argument to the callback is +** a copy of the third argument to sqlite3_update_hook(). +** {F12977} The second callback +** argument is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], +** depending on the operation that caused the callback to be invoked. +** {F12978} The third and +** fourth arguments to the callback contain pointers to the database and +** table name containing the affected row. +** {F12979} The final callback parameter is +** the rowid of the row. +** {F12981} In the case of an update, this is the rowid after +** the update takes place. ** -** The update hook is not invoked when internal system tables are +** {F12983} The update hook is not invoked when internal system tables are ** modified (i.e. sqlite_master and sqlite_sequence). ** -** If another function was previously registered, its pArg value -** is returned. Otherwise NULL is returned. -** -** INVARIANTS: -** -** {F12971} The [sqlite3_update_hook(D,F,P)] interface causes the callback -** function F to be invoked with first parameter P whenever -** a table row is modified, inserted, or deleted on -** the [database connection] D. -** -** {F12973} The [sqlite3_update_hook(D,F,P)] interface returns the value -** of P for the previous call on the same [database connection] D, -** or NULL for the first call. -** -** {F12975} If the update hook callback F in [sqlite3_update_hook(D,F,P)] -** is NULL then the no update callbacks are made. -** -** {F12977} Each call to [sqlite3_update_hook(D,F,P)] overrides prior calls -** to the same interface on the same [database connection] D. -** -** {F12979} The update hook callback is not invoked when internal system -** tables such as sqlite_master and sqlite_sequence are modified. -** -** {F12981} The second parameter to the update callback -** is one of [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], -** depending on the operation that caused the callback to be invoked. -** -** {F12983} The third and fourth arguments to the callback contain pointers -** to zero-terminated UTF-8 strings which are the names of the -** database and table that is being updated. - -** {F12985} The final callback parameter is the rowid of the row after -** the change occurs. +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. */ void *sqlite3_update_hook( sqlite3*, @@ -4862,177 +3003,135 @@ void *sqlite3_update_hook( ); /* -** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} -** KEYWORDS: {shared cache} {shared cache mode} +** CAPI3REF: Enable Or Disable Shared Pager Cache {F10330} ** +** {F10331} ** This routine enables or disables the sharing of the database cache -** and schema data structures between [database connection | connections] -** to the same database. Sharing is enabled if the argument is true -** and disabled if the argument is false. +** and schema data structures between connections to the same database. +** {F10332} +** Sharing is enabled if the argument is true and disabled if the argument +** is false. ** -** Cache sharing is enabled and disabled for an entire process. {END} -** This is a change as of SQLite version 3.5.0. In prior versions of SQLite, -** sharing was enabled or disabled for each thread separately. +** {F10333} Cache sharing is enabled and disabled +** for an entire process. {END} This is a change as of SQLite version 3.5.0. +** In prior versions of SQLite, sharing was +** enabled or disabled for each thread separately. ** +** {F10334} ** The cache sharing mode set by this interface effects all subsequent ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()]. -** Existing database connections continue use the sharing mode -** that was in effect at the time they were opened. +** {F10335} Existing database connections continue use the sharing mode +** that was in effect at the time they were opened. {END} ** -** Virtual tables cannot be used with a shared cache. When shared +** Virtual tables cannot be used with a shared cache. {F10336} When shared ** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. +** virtual tables will always return an error. {END} ** -** This routine returns [SQLITE_OK] if shared cache was enabled or disabled -** successfully. An [error code] is returned otherwise. +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [SQLITE_ERROR | error code] +** is returned otherwise. {END} ** -** Shared cache is disabled by default. But this might change in +** {F10339} Shared cache is disabled by default. {END} But this might change in ** future releases of SQLite. Applications that care about shared ** cache setting should set it explicitly. -** -** INVARIANTS: -** -** {F10331} A successful invocation of [sqlite3_enable_shared_cache(B)] -** will enable or disable shared cache mode for any subsequently -** created [database connection] in the same process. -** -** {F10336} When shared cache is enabled, the [sqlite3_create_module()] -** interface will always return an error. -** -** {F10337} The [sqlite3_enable_shared_cache(B)] interface returns -** [SQLITE_OK] if shared cache was enabled or disabled successfully. -** -** {F10339} Shared cache is disabled by default. */ int sqlite3_enable_shared_cache(int); /* -** CAPI3REF: Attempt To Free Heap Memory {F17340} +** CAPI3REF: Attempt To Free Heap Memory {F17340} ** -** The sqlite3_release_memory() interface attempts to free N bytes -** of heap memory by deallocating non-essential memory allocations -** held by the database library. {END} Memory used to cache database -** pages to improve performance is an example of non-essential memory. -** sqlite3_release_memory() returns the number of bytes actually freed, -** which might be more or less than the amount requested. -** -** INVARIANTS: -** -** {F17341} The [sqlite3_release_memory(N)] interface attempts to -** free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library. -** -** {F16342} The [sqlite3_release_memory(N)] returns the number -** of bytes actually freed, which might be more or less -** than the amount requested. +** {F17341} The sqlite3_release_memory() interface attempts to +** free N bytes of heap memory by deallocating non-essential memory +** allocations held by the database labrary. {END} Memory used +** to cache database pages to improve performance is an example of +** non-essential memory. {F16342} sqlite3_release_memory() returns +** the number of bytes actually freed, which might be more or less +** than the amount requested. */ int sqlite3_release_memory(int); /* -** CAPI3REF: Impose A Limit On Heap Size {F17350} +** CAPI3REF: Impose A Limit On Heap Size {F17350} ** -** The sqlite3_soft_heap_limit() interface places a "soft" limit -** on the amount of heap memory that may be allocated by SQLite. -** If an internal allocation is requested that would exceed the -** soft heap limit, [sqlite3_release_memory()] is invoked one or -** more times to free up some space before the allocation is performed. +** {F16351} The sqlite3_soft_heap_limit() interface +** places a "soft" limit on the amount of heap memory that may be allocated +** by SQLite. {F16352} If an internal allocation is requested +** that would exceed the soft heap limit, [sqlite3_release_memory()] is +** invoked one or more times to free up some space before the allocation +** is made. {END} ** -** The limit is called "soft", because if [sqlite3_release_memory()] -** cannot free sufficient memory to prevent the limit from being exceeded, +** {F16353} The limit is called "soft", because if +** [sqlite3_release_memory()] cannot +** free sufficient memory to prevent the limit from being exceeded, ** the memory is allocated anyway and the current operation proceeds. ** +** {F16354} ** A negative or zero value for N means that there is no soft heap limit and ** [sqlite3_release_memory()] will only be called when memory is exhausted. -** The default value for the soft heap limit is zero. +** {F16355} The default value for the soft heap limit is zero. ** -** SQLite makes a best effort to honor the soft heap limit. -** But if the soft heap limit cannot be honored, execution will -** continue without error or notification. This is why the limit is +** SQLite makes a best effort to honor the soft heap limit. +** {F16356} But if the soft heap limit cannot honored, execution will +** continue without error or notification. {END} This is why the limit is ** called a "soft" limit. It is advisory only. ** ** Prior to SQLite version 3.5.0, this routine only constrained the memory ** allocated by a single thread - the same thread in which this routine ** runs. Beginning with SQLite version 3.5.0, the soft heap limit is -** applied to all threads. The value specified for the soft heap limit -** is an upper bound on the total memory allocation for all threads. In +** applied to all threads. {F16357} The value specified for the soft heap limit +** is an upper bound on the total memory allocation for all threads. {END} In ** version 3.5.0 there is no mechanism for limiting the heap usage for ** individual threads. -** -** INVARIANTS: -** -** {F16351} The [sqlite3_soft_heap_limit(N)] interface places a soft limit -** of N bytes on the amount of heap memory that may be allocated -** using [sqlite3_malloc()] or [sqlite3_realloc()] at any point -** in time. -** -** {F16352} If a call to [sqlite3_malloc()] or [sqlite3_realloc()] would -** cause the total amount of allocated memory to exceed the -** soft heap limit, then [sqlite3_release_memory()] is invoked -** in an attempt to reduce the memory usage prior to proceeding -** with the memory allocation attempt. -** -** {F16353} Calls to [sqlite3_malloc()] or [sqlite3_realloc()] that trigger -** attempts to reduce memory usage through the soft heap limit -** mechanism continue even if the attempt to reduce memory -** usage is unsuccessful. -** -** {F16354} A negative or zero value for N in a call to -** [sqlite3_soft_heap_limit(N)] means that there is no soft -** heap limit and [sqlite3_release_memory()] will only be -** called when memory is completely exhausted. -** -** {F16355} The default value for the soft heap limit is zero. -** -** {F16358} Each call to [sqlite3_soft_heap_limit(N)] overrides the -** values set by all prior calls. */ void sqlite3_soft_heap_limit(int); /* -** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} +** CAPI3REF: Extract Metadata About A Column Of A Table {F12850} ** -** This routine returns metadata about a specific column of a specific -** database table accessible using the [database connection] handle -** passed as the first function argument. +** This routine +** returns meta-data about a specific column of a specific database +** table accessible using the connection handle passed as the first function +** argument. ** -** The column is identified by the second, third and fourth parameters to +** The column is identified by the second, third and fourth parameters to ** this function. The second parameter is either the name of the database ** (i.e. "main", "temp" or an attached database) containing the specified ** table or NULL. If it is NULL, then all attached databases are searched -** for the table using the same algorithm used by the database engine to +** for the table using the same algorithm as the database engine uses to ** resolve unqualified table references. ** -** The third and fourth parameters to this function are the table and column -** name of the desired column, respectively. Neither of these parameters +** The third and fourth parameters to this function are the table and column +** name of the desired column, respectively. Neither of these parameters ** may be NULL. ** -** Metadata is returned by writing to the memory locations passed as the 5th -** and subsequent parameters to this function. Any of these arguments may be -** NULL, in which case the corresponding element of metadata is omitted. +** Meta information is returned by writing to the memory locations passed as +** the 5th and subsequent parameters to this function. Any of these +** arguments may be NULL, in which case the corresponding element of meta +** information is ommitted. ** -**
          -** -**
          Parameter Output
          Type
          Description +**
          +** Parameter     Output Type      Description
          +** -----------------------------------
           **
          -** 
          5th const char* Data type -**
          6th const char* Name of default collation sequence -**
          7th int True if column has a NOT NULL constraint -**
          8th int True if column is part of the PRIMARY KEY -**
          9th int True if column is AUTOINCREMENT -**
          -**
          +** 5th const char* Data type +** 6th const char* Name of the default collation sequence +** 7th int True if the column has a NOT NULL constraint +** 8th int True if the column is part of the PRIMARY KEY +** 9th int True if the column is AUTOINCREMENT +** ** -** The memory pointed to by the character pointers returned for the -** declaration type and collation sequence is valid only until the next -** call to any SQLite API function. ** -** If the specified table is actually a view, an [error code] is returned. +** The memory pointed to by the character pointers returned for the +** declaration type and collation sequence is valid only until the next +** call to any sqlite API function. ** -** If the specified column is "rowid", "oid" or "_rowid_" and an -** INTEGER PRIMARY KEY column has been explicitly declared, then the output +** If the specified table is actually a view, then an error is returned. +** +** If the specified column is "rowid", "oid" or "_rowid_" and an +** INTEGER PRIMARY KEY column has been explicitly declared, then the output ** parameters are set for the explicitly declared column. If there is no -** explicitly declared INTEGER PRIMARY KEY column, then the output -** parameters are set as follows: +** explicitly declared IPK column, then the output parameters are set as +** follows: ** **
           **     data type: "INTEGER"
          @@ -5044,11 +3143,11 @@ void sqlite3_soft_heap_limit(int);
           **
           ** This function may load one or more schemas from database files. If an
           ** error occurs during this process, or if the requested table or column
          -** cannot be found, an [error code] is returned and an error message left
          -** in the [database connection] (to be retrieved using sqlite3_errmsg()).
          +** cannot be found, an SQLITE error code is returned and an error message
          +** left in the database handle (to be retrieved using sqlite3_errmsg()).
           **
           ** This API is only available if the library was compiled with the
          -** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
          +** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined.
           */
           int sqlite3_table_column_metadata(
             sqlite3 *db,                /* Connection handle */
          @@ -5065,28 +3164,25 @@ int sqlite3_table_column_metadata(
           /*
           ** CAPI3REF: Load An Extension {F12600}
           **
          -** This interface loads an SQLite extension library from the named file.
          +** {F12601} The sqlite3_load_extension() interface
          +** attempts to load an SQLite extension library contained in the file
          +** zFile. {F12602} The entry point is zProc. {F12603} zProc may be 0
          +** in which case the name of the entry point defaults
          +** to "sqlite3_extension_init".
           **
          -** {F12601} The sqlite3_load_extension() interface attempts to load an
          -**          SQLite extension library contained in the file zFile.
          +** {F12604} The sqlite3_load_extension() interface shall
          +** return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
           **
          -** {F12602} The entry point is zProc.
          +** {F12605}
          +** If an error occurs and pzErrMsg is not 0, then the
          +** sqlite3_load_extension() interface shall attempt to fill *pzErrMsg with 
          +** error message text stored in memory obtained from [sqlite3_malloc()].
          +** {END}  The calling function should free this memory
          +** by calling [sqlite3_free()].
           **
          -** {F12603} zProc may be 0, in which case the name of the entry point
          -**          defaults to "sqlite3_extension_init".
          -**
          -** {F12604} The sqlite3_load_extension() interface shall return
          -**          [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
          -**
          -** {F12605} If an error occurs and pzErrMsg is not 0, then the
          -**          [sqlite3_load_extension()] interface shall attempt to
          -**          fill *pzErrMsg with error message text stored in memory
          -**          obtained from [sqlite3_malloc()]. {END}  The calling function
          -**          should free this memory by calling [sqlite3_free()].
          -**
          -** {F12606} Extension loading must be enabled using
          -**          [sqlite3_enable_load_extension()] prior to calling this API,
          -**          otherwise an error will be returned.
          +** {F12606}
          +** Extension loading must be enabled using [sqlite3_enable_load_extension()]
          +** prior to calling this API or an error will be returned.
           */
           int sqlite3_load_extension(
             sqlite3 *db,          /* Load the extension into this database connection */
          @@ -5096,64 +3192,65 @@ int sqlite3_load_extension(
           );
           
           /*
          -** CAPI3REF: Enable Or Disable Extension Loading {F12620}
          +** CAPI3REF:  Enable Or Disable Extension Loading {F12620}
           **
           ** So as not to open security holes in older applications that are
           ** unprepared to deal with extension loading, and as a means of disabling
          -** extension loading while evaluating user-entered SQL, the following API
          -** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
          +** extension loading while evaluating user-entered SQL, the following
          +** API is provided to turn the [sqlite3_load_extension()] mechanism on and
          +** off.  {F12622} It is off by default. {END} See ticket #1863.
           **
          -** Extension loading is off by default. See ticket #1863.
          -**
          -** {F12621} Call the sqlite3_enable_load_extension() routine with onoff==1
          -**          to turn extension loading on and call it with onoff==0 to turn
          -**          it back off again.
          -**
          -** {F12622} Extension loading is off by default.
          +** {F12621} Call the sqlite3_enable_load_extension() routine
          +** with onoff==1 to turn extension loading on
          +** and call it with onoff==0 to turn it back off again. {END}
           */
           int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
           
           /*
           ** CAPI3REF: Make Arrangements To Automatically Load An Extension {F12640}
           **
          +** {F12641} This function
          +** registers an extension entry point that is automatically invoked
          +** whenever a new database connection is opened using
          +** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. {END}
          +**
           ** This API can be invoked at program startup in order to register
           ** one or more statically linked extensions that will be available
          -** to all new [database connections]. {END}
          +** to all new database connections.
           **
          -** This routine stores a pointer to the extension in an array that is
          -** obtained from [sqlite3_malloc()].  If you run a memory leak checker
          -** on your program and it reports a leak because of this array, invoke
          -** [sqlite3_reset_auto_extension()] prior to shutdown to free the memory.
          -**
          -** {F12641} This function registers an extension entry point that is
          -**          automatically invoked whenever a new [database connection]
          -**          is opened using [sqlite3_open()], [sqlite3_open16()],
          -**          or [sqlite3_open_v2()].
          -**
          -** {F12642} Duplicate extensions are detected so calling this routine
          -**          multiple times with the same extension is harmless.
          +** {F12642} Duplicate extensions are detected so calling this routine multiple
          +** times with the same extension is harmless.
           **
           ** {F12643} This routine stores a pointer to the extension in an array
          -**          that is obtained from [sqlite3_malloc()].
          +** that is obtained from sqlite_malloc(). {END} If you run a memory leak
          +** checker on your program and it reports a leak because of this
          +** array, then invoke [sqlite3_reset_auto_extension()] prior
          +** to shutdown to free the memory.
           **
          -** {F12644} Automatic extensions apply across all threads.
          +** {F12644} Automatic extensions apply across all threads. {END}
          +**
          +** This interface is experimental and is subject to change or
          +** removal in future releases of SQLite.
           */
           int sqlite3_auto_extension(void *xEntryPoint);
           
          +
           /*
           ** CAPI3REF: Reset Automatic Extension Loading {F12660}
           **
          -** This function disables all previously registered automatic
          -** extensions. {END}  It undoes the effect of all prior
          -** [sqlite3_auto_extension()] calls.
          -**
           ** {F12661} This function disables all previously registered
          -**          automatic extensions.
          +** automatic extensions. {END}  This
          +** routine undoes the effect of all prior [sqlite3_automatic_extension()]
          +** calls.
           **
          -** {F12662} This function disables automatic extensions in all threads.
          +** {F12662} This call disabled automatic extensions in all threads. {END}
          +**
          +** This interface is experimental and is subject to change or
          +** removal in future releases of SQLite.
           */
           void sqlite3_reset_auto_extension(void);
           
          +
           /*
           ****** EXPERIMENTAL - subject to change without notice **************
           **
          @@ -5161,7 +3258,7 @@ void sqlite3_reset_auto_extension(void);
           ** to be experimental.  The interface might change in incompatible ways.
           ** If this is a problem for you, do not use the interface at this time.
           **
          -** When the virtual-table mechanism stabilizes, we will declare the
          +** When the virtual-table mechanism stablizes, we will declare the
           ** interface fixed, support it indefinitely, and remove this comment.
           */
           
          @@ -5174,15 +3271,9 @@ typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
           typedef struct sqlite3_module sqlite3_module;
           
           /*
          -** CAPI3REF: Virtual Table Object {F18000}
          -** KEYWORDS: sqlite3_module
          -**
           ** A module is a class of virtual tables.  Each module is defined
           ** by an instance of the following structure.  This structure consists
           ** mostly of methods for the module.
          -**
          -** This interface is experimental and is subject to change or
          -** removal in future releases of SQLite.
           */
           struct sqlite3_module {
             int iVersion;
          @@ -5216,21 +3307,20 @@ struct sqlite3_module {
           };
           
           /*
          -** CAPI3REF: Virtual Table Indexing Information {F18100}
          -** KEYWORDS: sqlite3_index_info
          -**
           ** The sqlite3_index_info structure and its substructures is used to
           ** pass information into and receive the reply from the xBestIndex
           ** method of an sqlite3_module.  The fields under **Inputs** are the
           ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
           ** results into the **Outputs** fields.
           **
          -** The aConstraint[] array records WHERE clause constraints of the form:
          +** The aConstraint[] array records WHERE clause constraints of the
          +** form:
           **
          -** 
          column OP expr
          +** column OP expr ** -** where OP is =, <, <=, >, or >=. The particular operator is -** stored in aConstraint[].op. The index of the column is stored in +** Where OP is =, <, <=, >, or >=. +** The particular operator is stored +** in aConstraint[].op. The index of the column is stored in ** aConstraint[].iColumn. aConstraint[].usable is TRUE if the ** expr on the right-hand side can be evaluated (and thus the constraint ** is usable) and false if it cannot. @@ -5262,9 +3352,6 @@ struct sqlite3_module { ** particular lookup. A full scan of a table with N entries should have ** a cost of N. A binary search of a table of N entries should have a ** cost of approximately log(N). -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ struct sqlite3_index_info { /* Inputs */ @@ -5300,15 +3387,10 @@ struct sqlite3_index_info { #define SQLITE_INDEX_CONSTRAINT_MATCH 64 /* -** CAPI3REF: Register A Virtual Table Implementation {F18200} -** -** This routine is used to register a new module name with a -** [database connection]. Module names must be registered before -** creating new virtual tables on the module, or before using -** preexisting virtual tables of the module. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. +** This routine is used to register a new module name with an SQLite +** connection. Module names must be registered before creating new +** virtual tables on the module, or before using preexisting virtual +** tables of the module. */ int sqlite3_create_module( sqlite3 *db, /* SQLite connection to register module with */ @@ -5318,9 +3400,7 @@ int sqlite3_create_module( ); /* -** CAPI3REF: Register A Virtual Table Implementation {F18210} -** -** This routine is identical to the [sqlite3_create_module()] method above, +** This routine is identical to the sqlite3_create_module() method above, ** except that it allows a destructor function to be specified. It is ** even more experimental than the rest of the virtual tables API. */ @@ -5333,27 +3413,21 @@ int sqlite3_create_module_v2( ); /* -** CAPI3REF: Virtual Table Instance Object {F18010} -** KEYWORDS: sqlite3_vtab -** ** Every module implementation uses a subclass of the following structure ** to describe a particular instance of the module. Each subclass will -** be tailored to the specific needs of the module implementation. -** The purpose of this superclass is to define certain fields that are -** common to all module implementations. +** be tailored to the specific needs of the module implementation. The +** purpose of this superclass is to define certain fields that are common +** to all module implementations. ** ** Virtual tables methods can set an error message by assigning a -** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should -** take care that any prior string is freed by a call to [sqlite3_free()] +** string obtained from sqlite3_mprintf() to zErrMsg. The method should +** take care that any prior string is freed by a call to sqlite3_free() ** prior to assigning a new string to zErrMsg. After the error message ** is delivered up to the client application, the string will be automatically ** freed by sqlite3_free() and the zErrMsg field will be zeroed. Note ** that sqlite3_mprintf() and sqlite3_free() are used on the zErrMsg field ** since virtual tables are commonly implemented in loadable extensions which ** do not have access to sqlite3MPrintf() or sqlite3Free(). -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ struct sqlite3_vtab { const sqlite3_module *pModule; /* The module for this virtual table */ @@ -5362,11 +3436,7 @@ struct sqlite3_vtab { /* Virtual table implementations will typically add additional fields */ }; -/* -** CAPI3REF: Virtual Table Cursor Object {F18020} -** KEYWORDS: sqlite3_vtab_cursor -** -** Every module implementation uses a subclass of the following structure +/* Every module implementation uses a subclass of the following structure ** to describe cursors that point into the virtual table and are used ** to loop through the virtual table. Cursors are created using the ** xOpen method of the module. Each module implementation will define @@ -5374,9 +3444,6 @@ struct sqlite3_vtab { ** ** This superclass exists in order to define fields of the cursor that ** are common to all implementations. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ struct sqlite3_vtab_cursor { sqlite3_vtab *pVtab; /* Virtual table of this cursor */ @@ -5384,20 +3451,13 @@ struct sqlite3_vtab_cursor { }; /* -** CAPI3REF: Declare The Schema Of A Virtual Table {F18280} -** ** The xCreate and xConnect methods of a module use the following API ** to declare the format (the names and datatypes of the columns) of ** the virtual tables they implement. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. */ int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); /* -** CAPI3REF: Overload A Function For A Virtual Table {F18300} -** ** Virtual tables can provide alternative implementations of functions ** using the xFindFunction method. But global versions of those functions ** must exist in order to be overloaded. @@ -5407,7 +3467,7 @@ int sqlite3_declare_vtab(sqlite3*, const char *zCreateTable); ** before this API is called, a new function is created. The implementation ** of the new function always causes an exception to be thrown. So ** the new function is not good for anything by itself. Its only -** purpose is to be a placeholder function that can be overloaded +** purpose is to be a place-holder function that can be overloaded ** by virtual tables. ** ** This API should be considered part of the virtual table interface, @@ -5429,82 +3489,40 @@ int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); /* ** CAPI3REF: A Handle To An Open BLOB {F17800} -** KEYWORDS: {BLOB handle} {BLOB handles} ** -** An instance of this object represents an open BLOB on which -** [sqlite3_blob_open | incremental BLOB I/O] can be performed. -** Objects of this type are created by [sqlite3_blob_open()] -** and destroyed by [sqlite3_blob_close()]. +** An instance of the following opaque structure is used to +** represent an blob-handle. A blob-handle is created by +** [sqlite3_blob_open()] and destroyed by [sqlite3_blob_close()]. ** The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces -** can be used to read or write small subsections of the BLOB. -** The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes. +** can be used to read or write small subsections of the blob. +** The [sqlite3_blob_bytes()] interface returns the size of the +** blob in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* ** CAPI3REF: Open A BLOB For Incremental I/O {F17810} ** -** This interfaces opens a [BLOB handle | handle] to the BLOB located -** in row iRow, column zColumn, table zTable in database zDb; -** in other words, the same BLOB that would be selected by: +** {F17811} This interfaces opens a handle to the blob located +** in row iRow,, column zColumn, table zTable in database zDb; +** in other words, the same blob that would be selected by: ** **
           **     SELECT zColumn FROM zDb.zTable WHERE rowid = iRow;
           ** 
          {END} ** -** If the flags parameter is non-zero, the the BLOB is opened for read -** and write access. If it is zero, the BLOB is opened for read access. +** {F17812} If the flags parameter is non-zero, the blob is opened for +** read and write access. If it is zero, the blob is opened for read +** access. {END} ** -** Note that the database name is not the filename that contains -** the database but rather the symbolic name of the database that -** is assigned when the database is connected using [ATTACH]. -** For the main database file, the database name is "main". -** For TEMP tables, the database name is "temp". -** -** On success, [SQLITE_OK] is returned and the new [BLOB handle] is written -** to *ppBlob. Otherwise an [error code] is returned and any value written -** to *ppBlob should not be used by the caller. -** This function sets the [database connection] error code and message +** {F17813} On success, [SQLITE_OK] is returned and the new +** [sqlite3_blob | blob handle] is written to *ppBlob. +** {F17814} Otherwise an error code is returned and +** any value written to *ppBlob should not be used by the caller. +** {F17815} This function sets the database-handle error code and message ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -** -** If the row that a BLOB handle points to is modified by an -** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects -** then the BLOB handle is marked as "expired". -** This is true if any column of the row is changed, even a column -** other than the one the BLOB handle is open on. -** Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for -** a expired BLOB handle fail with an return code of [SQLITE_ABORT]. -** Changes written into a BLOB prior to the BLOB expiring are not -** rollback by the expiration of the BLOB. Such changes will eventually -** commit if the transaction continues to completion. -** -** INVARIANTS: -** -** {F17813} A successful invocation of the [sqlite3_blob_open(D,B,T,C,R,F,P)] -** interface shall open an [sqlite3_blob] object P on the BLOB -** in column C of the table T in the database B on -** the [database connection] D. -** -** {F17814} A successful invocation of [sqlite3_blob_open(D,...)] shall start -** a new transaction on the [database connection] D if that -** connection is not already in a transaction. -** -** {F17816} The [sqlite3_blob_open(D,B,T,C,R,F,P)] interface shall open -** the BLOB for read and write access if and only if the F -** parameter is non-zero. -** -** {F17819} The [sqlite3_blob_open()] interface shall return [SQLITE_OK] on -** success and an appropriate [error code] on failure. -** -** {F17821} If an error occurs during evaluation of [sqlite3_blob_open(D,...)] -** then subsequent calls to [sqlite3_errcode(D)], -** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return -** information appropriate for that error. -** -** {F17824} If any column in the row that a [sqlite3_blob] has open is -** changed by a separate [UPDATE] or [DELETE] statement or by -** an [ON CONFLICT] side effect, then the [sqlite3_blob] shall -** be marked as invalid. +** We should go through and mark all interfaces that behave this +** way with a similar statement */ int sqlite3_blob_open( sqlite3*, @@ -5517,228 +3535,104 @@ int sqlite3_blob_open( ); /* -** CAPI3REF: Close A BLOB Handle {F17830} +** CAPI3REF: Close A BLOB Handle {F17830} ** -** Closes an open [BLOB handle]. +** Close an open [sqlite3_blob | blob handle]. ** -** Closing a BLOB shall cause the current transaction to commit +** {F17831} Closing a BLOB shall cause the current transaction to commit ** if there are no other BLOBs, no pending prepared statements, and the -** database connection is in [autocommit mode]. -** If any writes were made to the BLOB, they might be held in cache +** database connection is in autocommit mode. +** {F17832} If any writes were made to the BLOB, they might be held in cache ** until the close operation if they will fit. {END} -** ** Closing the BLOB often forces the changes ** out to disk and so if any I/O errors occur, they will likely occur ** at the time when the BLOB is closed. {F17833} Any errors that occur during ** closing are reported as a non-zero return value. ** -** The BLOB is closed unconditionally. Even if this routine returns +** {F17839} The BLOB is closed unconditionally. Even if this routine returns ** an error code, the BLOB is still closed. -** -** INVARIANTS: -** -** {F17833} The [sqlite3_blob_close(P)] interface closes an [sqlite3_blob] -** object P previously opened using [sqlite3_blob_open()]. -** -** {F17836} Closing an [sqlite3_blob] object using -** [sqlite3_blob_close()] shall cause the current transaction to -** commit if there are no other open [sqlite3_blob] objects -** or [prepared statements] on the same [database connection] and -** the database connection is in [autocommit mode]. -** -** {F17839} The [sqlite3_blob_close(P)] interfaces shall close the -** [sqlite3_blob] object P unconditionally, even if -** [sqlite3_blob_close(P)] returns something other than [SQLITE_OK]. */ int sqlite3_blob_close(sqlite3_blob *); /* -** CAPI3REF: Return The Size Of An Open BLOB {F17840} +** CAPI3REF: Return The Size Of An Open BLOB {F17805} ** -** Returns the size in bytes of the BLOB accessible via the open -** []BLOB handle] in its only argument. -** -** INVARIANTS: -** -** {F17843} The [sqlite3_blob_bytes(P)] interface returns the size -** in bytes of the BLOB that the [sqlite3_blob] object P -** refers to. +** {F16806} Return the size in bytes of the blob accessible via the open +** [sqlite3_blob | blob-handle] passed as an argument. */ int sqlite3_blob_bytes(sqlite3_blob *); /* -** CAPI3REF: Read Data From A BLOB Incrementally {F17850} +** CAPI3REF: Read Data From A BLOB Incrementally {F17850} ** -** This function is used to read data from an open [BLOB handle] into a -** caller-supplied buffer. N bytes of data are copied into buffer Z -** from the open BLOB, starting at offset iOffset. +** This function is used to read data from an open +** [sqlite3_blob | blob-handle] into a caller supplied buffer. +** {F17851} n bytes of data are copied into buffer +** z from the open blob, starting at offset iOffset. ** -** If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is read. If N or iOffset is -** less than zero, [SQLITE_ERROR] is returned and no data is read. +** {F17852} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is read. {F17853} If n is +** less than zero [SQLITE_ERROR] is returned and no data is read. ** -** An attempt to read from an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. -** -** On success, SQLITE_OK is returned. -** Otherwise, an [error code] or an [extended error code] is returned. -** -** INVARIANTS: -** -** {F17853} A successful invocation of [sqlite3_blob_read(P,Z,N,X)] -** shall reads N bytes of data out of the BLOB referenced by -** [BLOB handle] P beginning at offset X and store those bytes -** into buffer Z. -** -** {F17856} In [sqlite3_blob_read(P,Z,N,X)] if the size of the BLOB -** is less than N+X bytes, then the function shall leave the -** Z buffer unchanged and return [SQLITE_ERROR]. -** -** {F17859} In [sqlite3_blob_read(P,Z,N,X)] if X or N is less than zero -** then the function shall leave the Z buffer unchanged -** and return [SQLITE_ERROR]. -** -** {F17862} The [sqlite3_blob_read(P,Z,N,X)] interface shall return [SQLITE_OK] -** if N bytes are successfully read into buffer Z. -** -** {F17863} If the [BLOB handle] P is expired and X and N are within bounds -** then [sqlite3_blob_read(P,Z,N,X)] shall leave the Z buffer -** unchanged and return [SQLITE_ABORT]. -** -** {F17865} If the requested read could not be completed, -** the [sqlite3_blob_read(P,Z,N,X)] interface shall return an -** appropriate [error code] or [extended error code]. -** -** {F17868} If an error occurs during evaluation of [sqlite3_blob_read(P,...)] -** then subsequent calls to [sqlite3_errcode(D)], -** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return -** information appropriate for that error, where D is the -** [database connection] that was used to open the [BLOB handle] P. +** {F17854} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. */ -int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); +int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); /* -** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} +** CAPI3REF: Write Data Into A BLOB Incrementally {F17870} ** -** This function is used to write data into an open [BLOB handle] from a -** caller-supplied buffer. N bytes of data are copied from the buffer Z -** into the open BLOB, starting at offset iOffset. +** This function is used to write data into an open +** [sqlite3_blob | blob-handle] from a user supplied buffer. +** {F17871} n bytes of data are copied from the buffer +** pointed to by z into the open blob, starting at offset iOffset. ** -** If the [BLOB handle] passed as the first argument was not opened for -** writing (the flags parameter to [sqlite3_blob_open()] was zero), -** this function returns [SQLITE_READONLY]. +** {F17872} If the [sqlite3_blob | blob-handle] passed as the first argument +** was not opened for writing (the flags parameter to [sqlite3_blob_open()] +*** was zero), this function returns [SQLITE_READONLY]. ** -** This function may only modify the contents of the BLOB; it is -** not possible to increase the size of a BLOB using this API. -** If offset iOffset is less than N bytes from the end of the BLOB, -** [SQLITE_ERROR] is returned and no data is written. If N is +** {F17873} This function may only modify the contents of the blob; it is +** not possible to increase the size of a blob using this API. +** {F17874} If offset iOffset is less than n bytes from the end of the blob, +** [SQLITE_ERROR] is returned and no data is written. {F17875} If n is ** less than zero [SQLITE_ERROR] is returned and no data is written. ** -** An attempt to write to an expired [BLOB handle] fails with an -** error code of [SQLITE_ABORT]. Writes to the BLOB that occurred -** before the [BLOB handle] expired are not rolled back by the -** expiration of the handle, though of course those changes might -** have been overwritten by the statement that expired the BLOB handle -** or by other independent statements. -** -** On success, SQLITE_OK is returned. -** Otherwise, an [error code] or an [extended error code] is returned. -** -** INVARIANTS: -** -** {F17873} A successful invocation of [sqlite3_blob_write(P,Z,N,X)] -** shall write N bytes of data from buffer Z into the BLOB -** referenced by [BLOB handle] P beginning at offset X into -** the BLOB. -** -** {F17874} In the absence of other overridding changes, the changes -** written to a BLOB by [sqlite3_blob_write()] shall -** remain in effect after the associated [BLOB handle] expires. -** -** {F17875} If the [BLOB handle] P was opened for reading only then -** an invocation of [sqlite3_blob_write(P,Z,N,X)] shall leave -** the referenced BLOB unchanged and return [SQLITE_READONLY]. -** -** {F17876} If the size of the BLOB referenced by [BLOB handle] P is -** less than N+X bytes then [sqlite3_blob_write(P,Z,N,X)] shall -** leave the BLOB unchanged and return [SQLITE_ERROR]. -** -** {F17877} If the [BLOB handle] P is expired and X and N are within bounds -** then [sqlite3_blob_read(P,Z,N,X)] shall leave the BLOB -** unchanged and return [SQLITE_ABORT]. -** -** {F17879} If X or N are less than zero then [sqlite3_blob_write(P,Z,N,X)] -** shall leave the BLOB referenced by [BLOB handle] P unchanged -** and return [SQLITE_ERROR]. -** -** {F17882} The [sqlite3_blob_write(P,Z,N,X)] interface shall return -** [SQLITE_OK] if N bytes where successfully written into the BLOB. -** -** {F17885} If the requested write could not be completed, -** the [sqlite3_blob_write(P,Z,N,X)] interface shall return an -** appropriate [error code] or [extended error code]. -** -** {F17888} If an error occurs during evaluation of [sqlite3_blob_write(D,...)] -** then subsequent calls to [sqlite3_errcode(D)], -** [sqlite3_errmsg(D)], and [sqlite3_errmsg16(D)] shall return -** information appropriate for that error. +** {F17876} On success, SQLITE_OK is returned. Otherwise, an +** [SQLITE_ERROR | SQLite error code] or an +** [SQLITE_IOERR_READ | extended error code] is returned. */ int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); /* -** CAPI3REF: Virtual File System Objects {F11200} +** CAPI3REF: Virtual File System Objects {F11200} ** ** A virtual filesystem (VFS) is an [sqlite3_vfs] object ** that SQLite uses to interact -** with the underlying operating system. Most SQLite builds come with a +** with the underlying operating system. Most builds come with a ** single default VFS that is appropriate for the host computer. ** New VFSes can be registered and existing VFSes can be unregistered. ** The following interfaces are provided. ** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its name. -** Names are case sensitive. -** Names are zero-terminated UTF-8 strings. -** If there is no match, a NULL pointer is returned. -** If zVfsName is NULL then the default VFS is returned. +** {F11201} The sqlite3_vfs_find() interface returns a pointer to +** a VFS given its name. {F11202} Names are case sensitive. +** {F11203} Names are zero-terminated UTF-8 strings. +** {F11204} If there is no match, a NULL +** pointer is returned. {F11205} If zVfsName is NULL then the default +** VFS is returned. {END} ** -** New VFSes are registered with sqlite3_vfs_register(). -** Each new VFS becomes the default VFS if the makeDflt flag is set. -** The same VFS can be registered multiple times without injury. -** To make an existing VFS into the default VFS, register it again -** with the makeDflt flag set. If two different VFSes with the -** same name are registered, the behavior is undefined. If a +** {F11210} New VFSes are registered with sqlite3_vfs_register(). +** {F11211} Each new VFS becomes the default VFS if the makeDflt flag is set. +** {F11212} The same VFS can be registered multiple times without injury. +** {F11213} To make an existing VFS into the default VFS, register it again +** with the makeDflt flag set. {U11214} If two different VFSes with the +** same name are registered, the behavior is undefined. {U11215} If a ** VFS is registered with a name that is NULL or an empty string, ** then the behavior is undefined. -** -** Unregister a VFS with the sqlite3_vfs_unregister() interface. -** If the default VFS is unregistered, another VFS is chosen as +** +** {F11220} Unregister a VFS with the sqlite3_vfs_unregister() interface. +** {F11221} If the default VFS is unregistered, another VFS is chosen as ** the default. The choice for the new VFS is arbitrary. -** -** INVARIANTS: -** -** {F11203} The [sqlite3_vfs_find(N)] interface returns a pointer to the -** registered [sqlite3_vfs] object whose name exactly matches -** the zero-terminated UTF-8 string N, or it returns NULL if -** there is no match. -** -** {F11206} If the N parameter to [sqlite3_vfs_find(N)] is NULL then -** the function returns a pointer to the default [sqlite3_vfs] -** object if there is one, or NULL if there is no default -** [sqlite3_vfs] object. -** -** {F11209} The [sqlite3_vfs_register(P,F)] interface registers the -** well-formed [sqlite3_vfs] object P using the name given -** by the zName field of the object. -** -** {F11212} Using the [sqlite3_vfs_register(P,F)] interface to register -** the same [sqlite3_vfs] object multiple times is a harmless no-op. -** -** {F11215} The [sqlite3_vfs_register(P,F)] interface makes the [sqlite3_vfs] -** object P the default [sqlite3_vfs] object if F is non-zero. -** -** {F11218} The [sqlite3_vfs_unregister(P)] interface unregisters the -** [sqlite3_vfs] object P so that it is no longer returned by -** subsequent calls to [sqlite3_vfs_find()]. */ sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); @@ -5748,11 +3642,11 @@ int sqlite3_vfs_unregister(sqlite3_vfs*); ** CAPI3REF: Mutexes {F17000} ** ** The SQLite core uses these routines for thread -** synchronization. Though they are intended for internal +** synchronization. Though they are intended for internal ** use by SQLite, code that links against SQLite is ** permitted to use any of these routines. ** -** The SQLite source code contains multiple implementations +** The SQLite source code contains multiple implementations ** of these mutex routines. An appropriate implementation ** is selected automatically at compile-time. The following ** implementations are available in the SQLite core: @@ -5764,19 +3658,20 @@ int sqlite3_vfs_unregister(sqlite3_vfs*); **
        • SQLITE_MUTEX_NOOP ** ** -** The SQLITE_MUTEX_NOOP implementation is a set of routines -** that does no real locking and is appropriate for use in +** The SQLITE_MUTEX_NOOP implementation is a set of routines +** that does no real locking and is appropriate for use in ** a single-threaded application. The SQLITE_MUTEX_OS2, ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations -** are appropriate for use on OS/2, Unix, and Windows. -** +** are appropriate for use on os/2, unix, and windows. +** ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex -** implementation is included with the library. In this case the -** application must supply a custom mutex implementation using the -** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function -** before calling sqlite3_initialize() or any other public sqlite3_ -** function that calls sqlite3_initialize(). +** implementation is included with the library. The +** mutex interface routines defined here become external +** references in the SQLite library for which implementations +** must be provided by the application. This facility allows an +** application that links against SQLite to provide its own mutex +** implementation without having to modify the SQLite core. ** ** {F17011} The sqlite3_mutex_alloc() routine allocates a new ** mutex and returns a pointer to it. {F17012} If it returns NULL @@ -5792,8 +3687,7 @@ int sqlite3_vfs_unregister(sqlite3_vfs*); **
        • SQLITE_MUTEX_STATIC_MEM2 **
        • SQLITE_MUTEX_STATIC_PRNG **
        • SQLITE_MUTEX_STATIC_LRU -**
        • SQLITE_MUTEX_STATIC_LRU2 -** +** {END} ** ** {F17015} The first two constants cause sqlite3_mutex_alloc() to create ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE @@ -5815,45 +3709,41 @@ int sqlite3_vfs_unregister(sqlite3_vfs*); ** ** {F17018} Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc() -** returns a different mutex on every call. {F17034} But for the static +** returns a different mutex on every call. {F17034} But for the static ** mutex types, the same mutex is returned on every call that has -** the same type number. +** the same type number. {END} ** ** {F17019} The sqlite3_mutex_free() routine deallocates a previously ** allocated dynamic mutex. {F17020} SQLite is careful to deallocate every -** dynamic mutex that it allocates. {A17021} The dynamic mutexes must not be in -** use when they are deallocated. {A17022} Attempting to deallocate a static +** dynamic mutex that it allocates. {U17021} The dynamic mutexes must not be in +** use when they are deallocated. {U17022} Attempting to deallocate a static ** mutex results in undefined behavior. {F17023} SQLite never deallocates ** a static mutex. {END} ** ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt ** to enter a mutex. {F17024} If another thread is already within the mutex, ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns [SQLITE_OK] +** SQLITE_BUSY. {F17025} The sqlite3_mutex_try() interface returns SQLITE_OK ** upon successful entry. {F17026} Mutexes created using ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread. ** {F17027} In such cases the, ** mutex must be exited an equal number of times before another thread -** can enter. {A17028} If the same thread tries to enter any other +** can enter. {U17028} If the same thread tries to enter any other ** kind of mutex more than once, the behavior is undefined. ** {F17029} SQLite will never exhibit -** such behavior in its own use of mutexes. +** such behavior in its own use of mutexes. {END} ** -** Some systems (for example, Windows 95) do not support the operation -** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() -** will always return SQLITE_BUSY. {F17030} The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. +** Some systems (ex: windows95) do not the operation implemented by +** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will +** always return SQLITE_BUSY. {F17030} The SQLite core only ever uses +** sqlite3_mutex_try() as an optimization so this is acceptable behavior. {END} ** ** {F17031} The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. {A17032} The behavior +** previously entered by the same thread. {U17032} The behavior ** is undefined if the mutex is not currently entered by the ** calling thread or is not currently allocated. {F17033} SQLite will ** never do either. {END} ** -** If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or -** sqlite3_mutex_leave() is a NULL pointer, then all three routines -** behave as no-ops. -** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ sqlite3_mutex *sqlite3_mutex_alloc(int); @@ -5863,87 +3753,26 @@ int sqlite3_mutex_try(sqlite3_mutex*); void sqlite3_mutex_leave(sqlite3_mutex*); /* -** CAPI3REF: Mutex Methods Object {F17120} -** -** An instance of this structure defines the low-level routines -** used to allocate and use mutexes. -** -** Usually, the default mutex implementations provided by SQLite are -** sufficient, however the user has the option of substituting a custom -** implementation for specialized deployments or systems for which SQLite -** does not provide a suitable implementation. In this case, the user -** creates and populates an instance of this structure to pass -** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option. -** Additionally, an instance of this structure can be used as an -** output variable when querying the system for the current mutex -** implementation, using the [SQLITE_CONFIG_GETMUTEX] option. -** -** The xMutexInit method defined by this structure is invoked as -** part of system initialization by the sqlite3_initialize() function. -** {F17001} The xMutexInit routine shall be called by SQLite once for each -** effective call to [sqlite3_initialize()]. -** -** The xMutexEnd method defined by this structure is invoked as -** part of system shutdown by the sqlite3_shutdown() function. The -** implementation of this method is expected to release all outstanding -** resources obtained by the mutex methods implementation, especially -** those obtained by the xMutexInit method. {F17003} The xMutexEnd() -** interface shall be invoked once for each call to [sqlite3_shutdown()]. -** -** The remaining seven methods defined by this structure (xMutexAlloc, -** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and -** xMutexNotheld) implement the following interfaces (respectively): -** -**
            -**
          • [sqlite3_mutex_alloc()]
          • -**
          • [sqlite3_mutex_free()]
          • -**
          • [sqlite3_mutex_enter()]
          • -**
          • [sqlite3_mutex_try()]
          • -**
          • [sqlite3_mutex_leave()]
          • -**
          • [sqlite3_mutex_held()]
          • -**
          • [sqlite3_mutex_notheld()]
          • -**
          -** -** The only difference is that the public sqlite3_XXX functions enumerated -** above silently ignore any invocations that pass a NULL pointer instead -** of a valid mutex handle. The implementations of the methods defined -** by this structure are not required to handle this case, the results -** of passing a NULL pointer instead of a valid mutex handle are undefined -** (i.e. it is acceptable to provide an implementation that segfaults if -** it is passed a NULL pointer). -*/ -typedef struct sqlite3_mutex_methods sqlite3_mutex_methods; -struct sqlite3_mutex_methods { - int (*xMutexInit)(void); - int (*xMutexEnd)(void); - sqlite3_mutex *(*xMutexAlloc)(int); - void (*xMutexFree)(sqlite3_mutex *); - void (*xMutexEnter)(sqlite3_mutex *); - int (*xMutexTry)(sqlite3_mutex *); - void (*xMutexLeave)(sqlite3_mutex *); - int (*xMutexHeld)(sqlite3_mutex *); - int (*xMutexNotheld)(sqlite3_mutex *); -}; - -/* -** CAPI3REF: Mutex Verification Routines {F17080} +** CAPI3REF: Mutex Verifcation Routines {F17080} ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines ** are intended for use inside assert() statements. {F17081} The SQLite core ** never uses these routines except inside an assert() and applications ** are advised to follow the lead of the core. {F17082} The core only ** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. {A17087} External mutex implementations +** with the SQLITE_DEBUG flag. {U17087} External mutex implementations ** are only required to provide these routines if SQLITE_DEBUG is ** defined and if NDEBUG is not defined. ** ** {F17083} These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. +** is held or not held, respectively, by the calling thread. {END} ** ** {X17084} The implementation is not required to provided versions of these -** routines that actually work. If the implementation does not provide working -** versions of these routines, it should at least provide stubs that always -** return true so that one does not get spurious assertion failures. +** routines that actually work. +** If the implementation does not provide working +** versions of these routines, it should at least provide stubs +** that always return true so that one does not get spurious +** assertion failures. {END} ** ** {F17085} If the argument to sqlite3_mutex_held() is a NULL pointer then ** the routine should return 1. {END} This seems counter-intuitive since @@ -5951,7 +3780,7 @@ struct sqlite3_mutex_methods { ** the reason the mutex does not exist is because the build is not ** using mutexes. And we do not want the assert() containing the ** call to sqlite3_mutex_held() to fail, so a non-zero return is -** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() +** the appropriate thing to do. {F17086} The sqlite3_mutex_notheld() ** interface should also return 1 when given a NULL pointer. */ int sqlite3_mutex_held(sqlite3_mutex*); @@ -5961,7 +3790,7 @@ int sqlite3_mutex_notheld(sqlite3_mutex*); ** CAPI3REF: Mutex Types {F17001} ** ** {F17002} The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. +** which is one of these integer constants. {END} */ #define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 @@ -5970,7 +3799,6 @@ int sqlite3_mutex_notheld(sqlite3_mutex*); #define SQLITE_MUTEX_STATIC_MEM2 4 /* sqlite3_release_memory() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ -#define SQLITE_MUTEX_STATIC_LRU2 7 /* lru page list */ /* ** CAPI3REF: Low-Level Control Of Database Files {F11300} @@ -5989,8 +3817,8 @@ int sqlite3_mutex_notheld(sqlite3_mutex*); ** {F11306} If the second parameter (zDbName) does not match the name of any ** open database file, then SQLITE_ERROR is returned. {F11307} This error ** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. {A11308} The underlying xFileControl method might -** also return SQLITE_ERROR. {A11309} There is no way to distinguish between +** or [sqlite3_errmsg()]. {U11308} The underlying xFileControl method might +** also return SQLITE_ERROR. {U11309} There is no way to distinguish between ** an incorrect zDbName and an SQLITE_ERROR return from the underlying ** xFileControl method. {END} ** @@ -5998,133 +3826,6 @@ int sqlite3_mutex_notheld(sqlite3_mutex*); */ int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*); -/* -** CAPI3REF: Testing Interface {F11400} -** -** The sqlite3_test_control() interface is used to read out internal -** state of SQLite and to inject faults into SQLite for testing -** purposes. The first parameter is an operation code that determines -** the number, meaning, and operation of all subsequent parameters. -** -** This interface is not for use by applications. It exists solely -** for verifying the correct operation of the SQLite library. Depending -** on how the SQLite library is compiled, this interface might not exist. -** -** The details of the operation codes, their meanings, the parameters -** they take, and what they do are all subject to change without notice. -** Unlike most of the SQLite API, this function is not guaranteed to -** operate consistently from one release to the next. -*/ -int sqlite3_test_control(int op, ...); - -/* -** CAPI3REF: Testing Interface Operation Codes {F11410} -** -** These constants are the valid operation code parameters used -** as the first argument to [sqlite3_test_control()]. -** -** These parameters and their meanings are subject to change -** without notice. These values are for testing purposes only. -** Applications should not use any of these parameters or the -** [sqlite3_test_control()] interface. -*/ -#define SQLITE_TESTCTRL_PRNG_SAVE 5 -#define SQLITE_TESTCTRL_PRNG_RESTORE 6 -#define SQLITE_TESTCTRL_PRNG_RESET 7 -#define SQLITE_TESTCTRL_BITVEC_TEST 8 -#define SQLITE_TESTCTRL_FAULT_INSTALL 9 -#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 - -/* -** CAPI3REF: SQLite Runtime Status {F17200} -** -** This interface is used to retrieve runtime status information -** about the preformance of SQLite, and optionally to reset various -** highwater marks. The first argument is an integer code for -** the specific parameter to measure. Recognized integer codes -** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...]. -** The current value of the parameter is returned into *pCurrent. -** The highest recorded value is returned in *pHighwater. If the -** resetFlag is true, then the highest record value is reset after -** *pHighwater is written. Some parameters do not record the highest -** value. For those parameters -** nothing is written into *pHighwater and the resetFlag is ignored. -** Other parameters record only the highwater mark and not the current -** value. For these latter parameters nothing is written into *pCurrent. -** -** This routine returns SQLITE_OK on success and a non-zero -** [error code] on failure. -** -** This routine is threadsafe but is not atomic. This routine can -** called while other threads are running the same or different SQLite -** interfaces. However the values returned in *pCurrent and -** *pHighwater reflect the status of SQLite at different points in time -** and it is possible that another thread might change the parameter -** in between the times when *pCurrent and *pHighwater are written. -** -** This interface is experimental and is subject to change or -** removal in future releases of SQLite. -*/ -int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag); - -/* -** CAPI3REF: Status Parameters {F17250} -** -** These integer constants designate various run-time status parameters -** that can be returned by [sqlite3_status()]. -** -**
          -**
          SQLITE_STATUS_MEMORY_USED
          -**
          This parameter is the current amount of memory checked out -** using [sqlite3_malloc()], either directly or indirectly. The -** figure includes calls made to [sqlite3_malloc()] by the application -** and internal memory usage by the SQLite library. Scratch memory -** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache -** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in -** this parameter. The amount returned is the sum of the allocation -** sizes as reported by the xSize method in [sqlite3_mem_methods].
          -** -**
          SQLITE_STATUS_PAGECACHE_USED
          -**
          This parameter returns the number of pages used out of the -** page cache buffer configured using [SQLITE_CONFIG_PAGECACHE]. The -** value returned is in pages, not in bytes.
          -** -**
          SQLITE_STATUS_PAGECACHE_OVERFLOW
          -**
          This parameter returns the number of bytes of page cache -** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE] -** buffer and where forced to overflow to [sqlite3_malloc()].
          -** -**
          SQLITE_STATUS_SCRATCH_USED
          -**
          This parameter returns the number of allocations used out of the -** scratch allocation lookaside buffer configured using -** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not -** in bytes. Since a single thread may only have one allocation -** outstanding at time, this parameter also reports the number of threads -** using scratch memory at the same time.
          -** -**
          SQLITE_STATUS_SCRATCH_OVERFLOW
          -**
          This parameter returns the number of bytes of scratch memory -** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH] -** buffer and where forced to overflow to [sqlite3_malloc()].
          -** -**
          SQLITE_STATUS_MALLOC_SIZE
          -**
          This parameter records the largest memory allocation request -** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their -** internal equivalents). The value of interest is return in the -** *pHighwater parameter to [sqlite3_status()]. The value written -** into the *pCurrent parameter is undefined.
          -**
          -** -** New status parameters may be added from time to time. -*/ -#define SQLITE_STATUS_MEMORY_USED 0 -#define SQLITE_STATUS_PAGECACHE_USED 1 -#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 -#define SQLITE_STATUS_SCRATCH_USED 3 -#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 -#define SQLITE_STATUS_MALLOC_SIZE 5 - - /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support.