Overview
SHA1 Hash: | dbdc16016102dd777b1e19d93dee2b25c08038fb |
---|---|
Date: | 2008-02-02 07:33:03 |
User: | aku |
Comment: | Merged with mainline. |
Timelines: | ancestors | descendants | both | trunk |
Other Links: | files | ZIP archive | manifest |
Tags And Properties
- branch=trunk inherited from [a28c83647d]
- sym-trunk inherited from [a28c83647d]
Changes
[hide diffs]Modified src/db.c from [dc61149835] to [a160182dad].
@@ -929,11 +929,11 @@ }else{ return 0; } } int db_get_int(const char *zName, int dflt){ - int v; + int v = dflt; int rc; if( g.repositoryOpen ){ Stmt q; db_prepare(&q, "SELECT value FROM config WHERE name=%Q", zName); rc = db_step(&q);
Modified src/info.c from [21bbd4bc04] to [abc907adcd].
@@ -762,12 +762,12 @@ "INSERT INTO refs " " SELECT 'f', rid FROM blob WHERE uuid GLOB '%s*'" " UNION ALL" " SELECT 'w', substr(tagname,6) FROM tag" " WHERE tagname='wiki-%q'" - " UNION ALL" - " SELECT 't', tkt_uuid FROM ticket WHERE tkt_uuid GLOB '%s*';", + /*" UNION ALL" + " SELECT 't', tkt_uuid FROM ticket WHERE tkt_uuid GLOB '%s*';"*/, zName, zName, zName ); cnt = db_int(0, "SELECT count(*) FROM refs"); if( cnt==0 ){ style_header("Broken Link");
Modified src/main.mk from [e26748a323] to [a4037f237e].
@@ -212,10 +212,16 @@ awk '{ printf "#define MANIFEST_VERSION \"[%.10s]\"\n", $$1}' $(SRCDIR)/../manifest.uuid >>VERSION.h awk '$$1=="D"{printf "#define MANIFEST_DATE \"%s %s\"\n", substr($$2,1,10),substr($$2,12)}' $(SRCDIR)/../manifest >>VERSION.h $(APPNAME): headers $(OBJ) sqlite3.o $(TCC) -o $(APPNAME) $(OBJ) sqlite3.o $(LIB) + +# This rule prevents make from using its default rules to try build +# an executable named "manifest" out of the file named "manifest.c" +# +$(SRCDIR)/../manifest: + # noop clean: rm -f *.o *_.c $(APPNAME) VERSION.h rm -f translate makeheaders mkindex page_index.h headers rm -f add.h bag.h blob.h branch.h cgi.h checkin.h checkout.h clearsign.h clone.h comformat.h construct.h content.h db.h delta.h deltacmd.h descendents.h diff.h diffcmd.h encode.h file.h http.h info.h login.h main.h manifest.h md5.h merge.h merge3.h name.h pivot.h pqueue.h printf.h rebuild.h rss.h schema.h setup.h sha1.h style.h subscript.h sync.h tag.h timeline.h tkt.h tktconfig.h tktsetup.h undo.h update.h url.h user.h verify.h vfile.h wiki.h wikiformat.h xfer.h zip.h
Modified src/makemake.tcl from [32b8cb3f29] to [b80c78c060].
@@ -129,10 +129,16 @@ substr($$2,1,10),substr($$2,12)}' \ $(SRCDIR)/../manifest >>VERSION.h $(APPNAME): headers $(OBJ) sqlite3.o $(TCC) -o $(APPNAME) $(OBJ) sqlite3.o $(LIB) + +# This rule prevents make from using its default rules to try build +# an executable named "manifest" out of the file named "manifest.c" +# +$(SRCDIR)/../manifest: + # noop clean: rm -f *.o *_.c $(APPNAME) VERSION.h rm -f translate makeheaders mkindex page_index.h headers}
Modified src/setup.c from [89b2ca9e01] to [093a77e546].
@@ -414,11 +414,11 @@ @ Login is required for user "<b>anonymous</b>" but the password @ is displayed on the login screen beside the password entry box @ so anybody who can read should be able to login as anonymous. @ On the other hand, spiders and web-crawlers will typically not @ be able to login. Set the capabilities of the anonymous user - @ to things that you want any human to be able to do, but no any + @ to things that you want any human to be able to do, but not any @ spider. @ </p></li> @ </form> style_footer(); } @@ -528,10 +528,19 @@ @ <hr> entry_attribute("Login expiration time", 6, "cookie-expire", "cex", "8766"); @ <p>The number of hours for which a login is valid. This must be a @ positive number. The default is 8760 hours which is approximately equal @ to a year.</p> + + @ <hr> + entry_attribute("Download packet limit", 10, "max-download", "mxdwn", + "5000000"); + @ <p>Fossil tries to limit out-bound sync, clone, and pull packets + @ to this many bytes, uncompressed. If the client requires more data + @ than this, then the client will issue multiple HTTP requests. + @ Values below 1 million are not recommended. 5 million is a + @ reasonable number.</p> @ <hr> @ <p><input type="submit" name="submit" value="Apply Changes"></p> @ </form> db_end_transaction(0);
Modified src/sqlite3.c from [81b02daa4d] to [269f370571].
@@ -1,8 +1,8 @@ /****************************************************************************** ** This file is an amalgamation of many separate C source files from SQLite -** version 3.5.2. By combining all the individual C code files into this +** version 3.5.5. 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 ** of 5% are more are commonly seen when SQLite is compiled as a single ** translation unit. @@ -9,18 +9,19 @@ ** ** This file is all you need to compile SQLite. To use SQLite in other ** 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 -** 3530 lines past this header comment.) Additional code files may be +** 4800 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 2007-11-25 16:04:31 UTC. -*/ +** This amalgamation was generated on 2008-02-01 15:34:25 UTC. +*/ +#define SQLITE_CORE 1 #define SQLITE_AMALGAMATION 1 #ifndef SQLITE_PRIVATE # define SQLITE_PRIVATE static #endif #ifndef SQLITE_API @@ -38,14 +39,29 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* ** Internal interface definitions for SQLite. ** -** @(#) $Id: sqliteInt.h,v 1.618 2007/11/12 09:50:26 danielk1977 Exp $ +** @(#) $Id: sqliteInt.h,v 1.658 2008/01/30 16:14:23 drh Exp $ */ #ifndef _SQLITEINT_H_ #define _SQLITEINT_H_ + +/* +** 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 + /* ** 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. @@ -87,11 +103,11 @@ ** ************************************************************************* ** ** This file defines various limits of what SQLite can process. ** -** @(#) $Id: sqliteLimit.h,v 1.3 2007/11/05 14:30:23 drh Exp $ +** @(#) $Id: sqliteLimit.h,v 1.6 2007/12/17 16:20:07 drh Exp $ */ /* ** The maximum length of a TEXT or BLOB in bytes. This also ** limits the size of a row in a table or index. @@ -124,14 +140,14 @@ # define SQLITE_MAX_COLUMN 2000 #endif /* ** The maximum length of a single SQL statement in bytes. -** The hard limit here is the same as SQLITE_MAX_LENGTH. +** A value of zero means there is no limit. */ #ifndef SQLITE_MAX_SQL_LENGTH -# define SQLITE_MAX_SQL_LENGTH 1000000 +# 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 @@ -223,11 +239,11 @@ /* ** Ordinarily, if no value is explicitly provided, SQLite creates databases ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain ** device characteristics (sector-size and atomic write() support), ** SQLite may choose a larger value. This constant is the maximum value -** SQLite will choose on it's own. +** SQLite will choose on its own. */ #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192 #endif #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE @@ -325,11 +341,11 @@ ** if it is already defined or if it is unneeded because we are ** not doing a threadsafe build. Ticket #2681. ** ** See also ticket #2741. */ -#if !defined(_XOPEN_SOURCE) && !defined(__MACOS__) && SQLITE_THREADSAFE +#if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE # define _XOPEN_SOURCE 500 /* Needed to enable pthread recursive mutexes */ #endif #if defined(SQLITE_TCL) || defined(TCLSH) # include <tcl.h> @@ -378,11 +394,11 @@ ** 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh Exp $ +** @(#) $Id: sqlite.h.in,v 1.283 2008/01/31 17:21:22 drh Exp $ */ #ifndef _SQLITE3_H_ #define _SQLITE3_H_ #include <stdarg.h> /* Needed for the definition of va_list */ @@ -411,85 +427,103 @@ #ifdef SQLITE_VERSION_NUMBER # undef SQLITE_VERSION_NUMBER #endif /* -** CAPI3REF: Compile-Time Library Version Numbers -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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 +** 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. +** +** The "version" of SQLite is a strong 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 ** there are major feature enhancements that are forwards compatible -** but not backwards compatible. The Z value is incremented with +** but not backwards compatible. The Z value is release number +** and is incremented with ** each release but resets back to 0 when Y is incremented. ** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The function -** is provided for DLL users who can only access functions and not +** +** INVARIANTS: +** +** {F10011} The SQLITE_VERSION #define in the sqlite3.h header file +** evaluates to a string literal that is the SQLite version +** with which the header file is associated. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves 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.5.5" +#define SQLITE_VERSION_NUMBER 3005005 + +/* +** 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 +** [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 ** constants within the DLL. +** +** INVARIANTS: +** +** {F10021} The [sqlite3_libversion_number()] interface returns an integer +** equal to [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. */ 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. +** 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 os false, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite from more than one thread. +** +** There is a measurable performance penalty for enabling mutexes. +** 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. +** +** INVARIANTS: +** +** {F10101} The [sqlite3_threadsafe()] function returns nonzero if +** SQLite was compiled with its mutexes enabled or zero +** if SQLite was compiled with mutexes disabled. */ SQLITE_API int sqlite3_threadsafe(void); /* -** CAPI3REF: Database Connection Handle +** CAPI3REF: Database Connection Handle {F12000} +** KEYWORDS: {database connection} ** ** 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 @@ -500,17 +534,27 @@ */ typedef struct sqlite3 sqlite3; /* -** CAPI3REF: 64-Bit Integer Types -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. +** CAPI3REF: 64-Bit Integer Types {F10200} +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** 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] types specify a +** 64-bit signed integer. +** +** {F10202} The [sqlite_uint64] and [sqlite3_uint64] types specify +** a 64-bit unsigned integer. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; #elif defined(_MSC_VER) || defined(__BORLANDC__) @@ -530,27 +574,47 @@ #ifdef SQLITE_OMIT_FLOATING_POINT # define double sqlite3_int64 #endif /* -** CAPI3REF: Closing A Database Connection -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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. +** CAPI3REF: Closing A Database Connection {F12010} +** +** This routine is the destructor for the [sqlite3] object. +** +** Applications should [sqlite3_finalize | finalize] all +** [prepared statements] and +** [sqlite3_blob_close | close] all [sqlite3_blob | BLOBs] +** associated with the [sqlite3] object prior +** to attempting to close the [sqlite3] object. +** +** <todo>What happens to pending transactions? Are they +** rolled back, or abandoned?</todo> +** +** INVARIANTS: +** +** {F12011} The [sqlite3_close()] interface destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], +** [sqlite3_open16()], or [sqlite3_open_v2()]. +** +** {F12012} The [sqlite3_close()] function releases all memory used by the +** connection and closes all open files. +** +** {F12013} If the database connection contains +** [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. +** +** LIMITATIONS: +** +** {U12015} The parameter to [sqlite3_close()] must be an [sqlite3] object +** pointer previously obtained from [sqlite3_open()] or the +** equivalent, or NULL. +** +** {U12016} The parameter to [sqlite3_close()] must not have been previously +** closed. */ SQLITE_API int sqlite3_close(sqlite3 *); /* ** The type for a callback function. @@ -558,51 +622,102 @@ ** compatibility and is not documented. */ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* -** CAPI3REF: One-Step Query Execution Interface -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** The sqlite3_exec() interface is a convenient way of running +** one or more SQL statements without a lot of C code. The +** 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. +** +** The sqlite3_exec() interface is implemented in terms of +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. +** The sqlite3_exec() routine does nothing that cannot be done +** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. +** The sqlite3_exec() is just a convenient wrapper. +** +** INVARIANTS: +** +** {F12101} The [sqlite3_exec()] interface evaluates zero or more UTF-8 +** encoded, semicolon-separated, SQL statements in the +** zero-terminated string of its 2nd parameter within the +** context of the [sqlite3] object given in the 1st parameter. +** +** {F12104} The return value of [sqlite3_exec()] is SQLITE_OK if all +** SQL statements run successfully. +** +** {F12105} The return value of [sqlite3_exec()] is 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 is +** invoked once for each row of result. +** +** {F12110} If the callback returns a non-zero value then [sqlite3_exec()] +** will aborted the SQL statement it is currently evaluating, +** skip all subsequent SQL statements, and return [SQLITE_ABORT]. +** <todo>What happens to *errmsg here? Does the result code for +** sqlite3_errcode() get set?</todo> +** +** {F12113} The [sqlite3_exec()] routine will pass its 4th parameter through +** as the 1st parameter of the callback. +** +** {F12116} The [sqlite3_exec()] routine sets the 2nd parameter of its +** callback to be the number of columns in the current row of +** result. +** +** {F12119} The [sqlite3_exec()] routine sets 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 sets 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()] never invokes a callback. All query +** results are silently discarded. +** +** {F12128} If an error occurs while parsing or evaluating any of the SQL +** statements handed to [sqlite3_exec()] then [sqlite3_exec()] will +** return an [error code] other than [SQLITE_OK]. +** +** {F12131} If an error occurs while parsing or evaluating any of the SQL +** handed to [sqlite3_exec()] and if the 5th parameter (errmsg) +** to [sqlite3_exec()] is not NULL, then an error message is +** allocated using the equivalent of [sqlite3_mprintf()] and +** *errmsg is made to point to that message. +** +** {F12134} The [sqlite3_exec()] routine does not change the value of +** *errmsg if errmsg is NULL or if there are no errors. +** +** {F12137} The [sqlite3_exec()] function sets the error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** +** LIMITATIONS: +** +** {U12141} The first parameter to [sqlite3_exec()] must be an valid and open +** [database connection]. +** +** {U12142} The database connection must not be closed while +** [sqlite3_exec()] is running. +** +** {U12143} The calling function is should use [sqlite3_free()] to free +** the memory that *errmsg is left pointing at once the error +** message is no longer needed. +** +** {U12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()] +** must remain unchanged while [sqlite3_exec()] is running. */ SQLITE_API int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluted */ int (*callback)(void*,int,char**,char**), /* Callback function */ @@ -609,28 +724,22 @@ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* -** CAPI3REF: Result Codes -** KEYWORDS: SQLITE_OK +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK {error code} {error codes} ** ** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** See also: [SQLITE_IOERR_READ | extended result codes] -** +** here in order to indicates success or failure. +** +** 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 /* NOT USED. Internal logic error in SQLite */ +#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 */ @@ -656,35 +765,44 @@ #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 +** CAPI3REF: Extended Result Codes {F10220} +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result codes} ** ** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at result-codes. However, experience has shown that +** [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 users might like. In an effort to +** 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We expect the number of extended result codes will be expand +** about errors. The extended result codes are enabled or disabled +** for each database connection 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. ** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** ** 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 always contains +** a related primary result code as a prefix. +** +** {F10224} Primary result code names contain a single "_" character. +** +** {F10225} Extended result code names contain two or more "_" characters. +** +** {F10226} The numeric value of an extended result code contains the +** numeric value of its corresponding primary result code it +** 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)) @@ -696,17 +814,16 @@ #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 -** -** Combination of the following 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. -** +** CAPI3REF: Flags For File Open Operations {F10230} +** +** These bit values are intended for use in then +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter 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 @@ -718,14 +835,14 @@ #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* -** CAPI3REF: Device Characteristics +** CAPI3REF: Device Characteristics {F10240} ** ** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following +** 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. ** ** The SQLITE_IOCAP_ATOMIC property means that all writes of @@ -750,13 +867,13 @@ #define SQLITE_IOCAP_ATOMIC64K 0x00000100 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400 /* -** CAPI3REF: File Locking Levels -** -** SQLite uses one of the following integer values as the second +** CAPI3REF: File Locking Levels {F10250} +** +** SQLite uses one of these integer values as the second ** argument to calls it makes to the xLock() and xUnlock() methods ** of an [sqlite3_io_methods] object. */ #define SQLITE_LOCK_NONE 0 #define SQLITE_LOCK_SHARED 1 @@ -763,29 +880,29 @@ #define SQLITE_LOCK_RESERVED 2 #define SQLITE_LOCK_PENDING 3 #define SQLITE_LOCK_EXCLUSIVE 4 /* -** CAPI3REF: Synchronization Type Flags -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. +** CAPI3REF: Synchronization Type Flags {F10260} +** +** 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 ** sync operation only needs to flush data to mass storage. Inode -** information need not be flushed. The SQLITE_SYNC_NORMAL means -** to use normal fsync() semantics. The SQLITE_SYNC_FULL flag means +** information need not be flushed. The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. 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 +** 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 @@ -796,11 +913,11 @@ struct sqlite3_file { const struct sqlite3_io_methods *pMethods; /* Methods for an open file */ }; /* -** CAPI3REF: OS Interface File Virtual Methods Object +** 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. ** @@ -890,28 +1007,28 @@ int (*xDeviceCharacteristics)(sqlite3_file*); /* Additional methods may be added in future releases */ }; /* -** CAPI3REF: Standard File Control Opcodes +** 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. ** ** 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. 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 +** 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 ** deals with pointers to the [sqlite3_mutex] object. @@ -919,11 +1036,11 @@ ** Mutexes are created using [sqlite3_mutex_alloc()]. */ typedef struct sqlite3_mutex sqlite3_mutex; /* -** CAPI3REF: OS Interface Object +** 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". ** @@ -948,24 +1065,25 @@ ** 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. ** -** SQLite will guarantee that the zFilename string passed to +** {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. So the [sqlite3_file] can store a pointer to the +** called. {END} So the [sqlite3_file] can store a pointer to the ** filename if it needs to remember the filename for some reason. ** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. +** {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. ** -** SQLite will also add one of the following flags to the xOpen() +** {F11143} SQLite will also add one of the following flags to the xOpen() ** call, depending on the object being opened: ** ** <ul> ** <li> [SQLITE_OPEN_MAIN_DB] ** <li> [SQLITE_OPEN_MAIN_JOURNAL] @@ -972,11 +1090,11 @@ ** <li> [SQLITE_OPEN_TEMP_DB] ** <li> [SQLITE_OPEN_TEMP_JOURNAL] ** <li> [SQLITE_OPEN_TRANSIENT_DB] ** <li> [SQLITE_OPEN_SUBJOURNAL] ** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> +** </ul> {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 @@ -991,35 +1109,35 @@ ** <ul> ** <li> [SQLITE_OPEN_DELETEONCLOSE] ** <li> [SQLITE_OPEN_EXCLUSIVE] ** </ul> ** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. The -** [SQLITE_OPEN_EXCLUSIVE] flag means the file should be opened +** {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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS] +** 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. The file can be a +** to test to see if a file is at least readable. {END} The file can be a ** directory. ** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact +** {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. If the output buffer is not large enough, SQLITE_CANTOPEN +** 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 endevour to prevent this by setting +** 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. @@ -1055,55 +1173,61 @@ /* New fields may be appended in figure versions. The iVersion ** value will increment whenever this happens. */ }; /* -** CAPI3REF: Flags for the xAccess VFS method -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine +** 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. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. With SQLITE_ACCESS_READ the xAccess method +** 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. Extended result codes are off by default for -** backwards compatibility with older versions of SQLite. +** CAPI3REF: Enable Or Disable Extended Result Codes {F12200} +** +** The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature of SQLite. +** The extended result codes are disabled by default for historical +** compatibility. +** +** INVARIANTS: +** +** {F12201} Each new [database connection] has the +** [extended result codes] feature +** disabled by default. +** +** {F12202} The [sqlite3_extended_result_codes(D,F)] interface will enable +** [extended result codes] for the +** [database connection] D if the F parameter +** is true, or disable them if F is false. */ SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff); /* -** CAPI3REF: Last Insert Rowid -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. If no successful inserts have ever occurred on this database -** connection, zero is returned. +** 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 +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. If +** the table has a column of type INTEGER PRIMARY KEY then that column +** 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 +** shown in the first argument. 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 @@ -1117,145 +1241,246 @@ ** 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. ** -** 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. +** 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 done +** on the same database connection and within the same +** trigger context, or zero if there have +** been no qualifying inserts on that connection. +** +** {F12223} The [sqlite3_last_insert_rowid()] function returns +** same value when called from the same trigger context +** immediately before and after a ROLLBACK. +** +** LIMITATIONS: +** +** {U12232} If separate thread does 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. */ SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); /* -** CAPI3REF: Count The Number Of Rows Modified +** CAPI3REF: Count The Number Of Rows Modified {F12240} ** ** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. Only +** or inserted or deleted by the most recently completed SQL statement +** on the 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 +** triggers are not counted. Use the [sqlite3_total_changes()] function ** to find the total number of changes including changes caused by triggers. ** -** Within the body of a trigger, the sqlite3_changes() interface can be -** called to find the number of +** A "row changes" 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. +** +** So 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 ** changes in the most recently completed INSERT, UPDATE, or DELETE -** statement within the body of the trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use +** statement within the body of the same trigger. +** However, the number returned does not include in changes +** caused by subtriggers since they 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. +** To get an accurate count of the number of rows deleted, use ** "DELETE FROM table WHERE 1" instead. ** -** If another thread makes changes on the same database connection -** while this routine is running then the return value of this routine -** is undefined. +** INVARIANTS: +** +** {F12241} The [sqlite3_changes()] function returns the number of +** row changes caused by the most recent INSERT, UPDATE, +** or DELETE statement on the same database connection and +** within the same trigger context, or zero if there have +** not been any qualifying row changes. +** +** LIMITATIONS: +** +** {U12252} If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and unmeaningful. */ SQLITE_API int sqlite3_changes(sqlite3*); /* -** CAPI3REF: Total Number Of Rows Modified +** CAPI3REF: Total Number Of Rows Modified {F12260} *** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 +** This function returns the number of row changes caused +** by INSERT, UPDATE or DELETE statements since the database handle +** was opened. The count includes all changes from all trigger +** contexts. But 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()]). +** +** 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. ** -** If another thread makes changes on the same database connection -** while this routine is running then the return value of this routine -** is undefined. +** 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. +** +** LIMITATIONS: +** +** {U12264} If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and unmeaningful. */ SQLITE_API int sqlite3_total_changes(sqlite3*); /* -** CAPI3REF: Interrupt A Long-Running Query +** 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 +** return at its earliest opportunity. 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 ** is closed or might close before sqlite3_interrupt() returns. ** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. +** 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. +** 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 +** 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: +** +** {U12279} If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. */ SQLITE_API void sqlite3_interrupt(sqlite3*); /* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} ** ** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. +** 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 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. +** +** These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** INVARIANTS: +** +** {F10511} The sqlite3_complete() and sqlite3_complete16() functions +** return true (non-zero) 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. +** +** LIMITATIONS: +** +** {U10512} The input to sqlite3_complete() must be a zero-terminated +** UTF-8 string. +** +** {U10513} The input to sqlite3_complete16() must be a zero-terminated +** UTF-16 string in native byte order. */ SQLITE_API int sqlite3_complete(const char *sql); SQLITE_API int sqlite3_complete16(const void *sql); /* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** This routine identifies a callback function that might be invoked -** whenever an attempt is made to open a database table +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** 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. ** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [SQLITE_IOERR_BLOCKED]) +** 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 this routine. The second argument to ** the handler is the number of times that the busy handler has -** been invoked for this locking event. If the +** been invoked for this locking event. 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 is made to open the -** database for reading and the cycle repeats. +** 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 return [SQLITE_BUSY] instead. +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. ** 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 @@ -1265,52 +1490,66 @@ ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** The default busy callback is NULL. ** -** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] when -** SQLite is in the middle of a large transaction where all the +** 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 ** 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 ** 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 +** forces an automatic rollback of the changes. See the ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> ** CorruptionFollowingBusyError</a> wiki page for a discussion of why ** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. ** ** There can only be a single busy handler defined for each database ** connection. Setting a new busy handler clears any previous one. ** Note that calling [sqlite3_busy_timeout()] will also set or clear ** the busy handler. ** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. +** INVARIANTS: +** +** {F12311} The [sqlite3_busy_handler()] function replaces the busy handler +** callback in the database connection identified by the 1st +** parameter with a new busy handler identified by the 2nd and 3rd +** parameters. +** +** {F12312} The default busy handler for new database connections is NULL. +** +** {F12314} When two or more database connection share a common cache, +** the busy handler for the database connection currently using +** the cache is invoked when the cache encounters a lock. +** +** {F12316} If a busy handler callback returns zero, then the SQLite +** interface that provoked the locking event will return +** [SQLITE_BUSY]. +** +** {F12318} SQLite will invokes the busy handler with two argument 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: +** +** {U12319} A busy handler should not call close the database connection +** or prepared statement that invoked the busy handler. */ SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); /* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a +** CAPI3REF: Set A Busy Timeout {F12340} +** +** This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a ** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. After +** 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 ** turns off all busy handlers. @@ -1317,34 +1556,68 @@ ** ** 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 overrides 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 is 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 is set that repeatedly calls +** the xSleep() method in the 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** Definition: A <b>result table</b> is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** 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 are give a NULL pointer. All other values are in +** their UTF-8 zero-terminated string representation as returned by +** [sqlite3_column_text()]. +** +** A result table might consists 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: ** ** <blockquote><pre> ** Name | Age ** ----------------------- ** Alice | 43 ** Bob | 28 ** Cindy | 21 ** </pre></blockquote> ** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: +** 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: ** ** <blockquote><pre> ** azResult[0] = "Name"; ** azResult[1] = "Age"; ** azResult[2] = "Alice"; @@ -1353,51 +1626,79 @@ ** azResult[5] = "28"; ** azResult[6] = "Cindy"; ** azResult[7] = "21"; ** </pre></blockquote> ** -** 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). +** 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. ** ** After the calling function has finished using the result, it should -** pass the result data pointer to sqlite3_free_table() in order to +** pass the pointer to the result table 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. -** -** The return value of this routine is the same as from [sqlite3_exec()]. +** [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. +** +** 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 frees the result table under construction, aborts the +** query in process, skips any subsequent queries, sets the +** *resultp output pointer to NULL and returns [SQLITE_NOMEM]. +** +** {F12373} If the ncolumn parameter to [sqlite3_get_table()] is not NULL +** then [sqlite3_get_table()] write the number of columns in the +** result set of the query into *ncolumn if the query is +** successful (if the function returns SQLITE_OK). +** +** {F12374} If the nrow parameter to [sqlite3_get_table()] is not NULL +** then [sqlite3_get_table()] write the number of rows in the +** result set of the query into *nrow if the query is +** successful (if the function returns SQLITE_OK). +** +** {F12376} The [sqlite3_get_table()] function sets its *ncolumn value +** to the number of columns in the result set of the query in the +** sql parameter, or to zero if the query in sql has an empty +** result set. */ SQLITE_API 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 */ + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + char ***pResult, /* Results of the query */ + 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); /* -** CAPI3REF: Formatted String Printing Functions +** CAPI3REF: Formatted String Printing Functions {F17400} ** ** These routines are workalikes of the "printf()" family of functions ** from the standard C library. ** ** 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 +** released by [sqlite3_free()]. 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 ** 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. 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() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer. We admit that @@ -1455,11 +1756,11 @@ ** literal. ** ** 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. So, for example, one could say: +** quotes) in place of the %Q option. {END} So, for example, one could say: ** ** <blockquote><pre> ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); ** sqlite3_exec(db, zSQL, 0, 0, 0); ** sqlite3_free(zSQL); @@ -1468,104 +1769,232 @@ ** 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 ** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. +** 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 writes 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); SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...); /* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) +** 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 +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** 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 +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** 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 +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. 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 +** 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 +** 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() +** 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 +** 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 +** 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 +** 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 +** is not freed. +** +** 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. However, if +** and free() provided by the standard C library. {F17382} However, if ** SQLite is compiled with the following C preprocessor macro ** ** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> ** ** where <i>NNN</i> is an integer, then SQLite create a static ** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. +** 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. ** -** <b>Exception:</b> 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 ** 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 +** 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 +** where K is the lessor 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: +** +** {U17350} The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else a pointer obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that has +** not been released. +** +** {U17351} 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); SQLITE_API void sqlite3_free(void*); /* -** CAPI3REF: Memory Allocator Statistics -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** the memory allocation subsystem included within the SQLite. +** +** 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 highwater 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 highwater 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 highwater mark +** prior to the reset. */ SQLITE_API sqlite3_int64 sqlite3_memory_used(void); SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag); /* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. ** 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 ** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. +** rejected with an error. 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 will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. 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 is constructed to insert 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. ** ** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. +** 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. ** ** 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 @@ -1576,25 +2005,77 @@ ** user-entered SQL is being prepared that disallows everything ** except SELECT statements. ** ** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. +** previous call. Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. ** ** 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 coded 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 the +** any previously installed authorizer. +** +** {F12521} A NULL authorizer means that no authorization +** callback is invoked. +** +** {F12522} The default authorizer is NULL. */ SQLITE_API int sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); /* -** CAPI3REF: Authorizer Return Codes +** 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 @@ -1602,27 +2083,49 @@ */ #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 +** CAPI3REF: Authorizer Action Codes {F12550} ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorizer certain SQL statement actions. 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. ** ** These action code values signify what kind of operation is to be -** authorized. The 3rd and 4th parameters to the authorization callback -** function will be parameters or NULL depending on which of these +** authorized. 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 ** 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. +** +** 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 function] +** 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 */ #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ @@ -1655,96 +2158,165 @@ #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 +** CAPI3REF: Tracing And Profiling Functions {F12280} ** ** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. +** +** 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 triggersubprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger. +** ** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. +** 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. ** ** The sqlite3_profile() API is currently considered experimental and -** is subject to change. +** 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 UTF8 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. */ SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); SQLITE_API void *sqlite3_profile(sqlite3*, void(*xProfile)(void*,const char*,sqlite3_uint64), void*); /* -** CAPI3REF: Query Progress Callbacks -** -** 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 +** CAPI3REF: Query Progress Callbacks {F12910} +** +** 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 ** interface is to keep a GUI updated during a large query. ** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. This feature -** can be used, for example, to implement the "Cancel" button on a -** progress dialog box in a GUI. +** If the progress callback returns non-zero, the opertion 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. <todo>What if N is less than 1?</todo> +** +** {F12913} The progress callback itself is identified by the third +** argument to [sqlite3_progress_handler()]. +** +** {F12914} The fourth argument [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. {END} +** +** {F12916} Every call to [sqlite3_progress_handler()] +** overwrites any previously registere progress handler. +** +** {F12917} If the progress handler callback is NULL then no progress +** handler is invoked. +** +** {F12918} If the progress callback returns a result other than 0, then +** the behavior is a if [sqlite3_interrupt()] had been called. */ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* -** CAPI3REF: Opening A New Database Connection -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded +** 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()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (or created) successfully, -** then [SQLITE_OK] is returned. Otherwise an error code is returned. The +** An [sqlite3*] handle is usually returned in *ppDb, even +** if an error occurs. The only exception is 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 ** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: +** 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 [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 acccepts two additional parameters for additional control +** over the new database connection. The flags parameter can be +** one of: ** ** <ol> ** <li> [SQLITE_OPEN_READONLY] ** <li> [SQLITE_OPEN_READWRITE] ** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] ** </ol> ** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens +** The first value opens the database read-only. +** If the database does not previously exist, an error is returned. +** The second option opens ** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. +** if the file is write protected. In either case the database +** must already exist or an error is returned. The third option +** opens the database for reading and writing and creates it if it does +** not already exist. ** The third options is behavior that is always used for [sqlite3_open()] ** and [sqlite3_open16()]. ** ** If the filename is ":memory:", then an private ** in-memory database is created for the connection. This in-memory @@ -1768,10 +2340,73 @@ ** <b>Note to windows users:</b> 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. +** <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required +** in sqlite3_open_v2()?</todo> +** +** {F12719} If the filename is an empty string, then a private, ephermeral +** on-disk database will be created. +** <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required +** in sqlite3_open_v2()?</todo> +** +** {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 is V is a NULL pointer. */ SQLITE_API int sqlite3_open( const char *filename, /* Database filename (UTF-8) */ sqlite3 **ppDb /* OUT: SQLite db handle */ ); @@ -1785,49 +2420,71 @@ int flags, /* Flags */ const char *zVfs /* Name of VFS module to use */ ); /* -** CAPI3REF: Error Codes And Messages +** CAPI3REF: Error Codes And Messages {F12800} ** ** 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'. If a prior API call failed but the +** with [sqlite3] handle 'db'. If a prior API call failed but the ** most recent API call succeeded, the return value from sqlite3_errcode() ** is undefined. ** ** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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()]. +** Memory to hold the error message string is managed internally. +** The application does not need to worry with freeing the result. +** However, the error string might be overwritten or deallocated b +** subsequent calls to other SQLite interface functions. +** +** INVARIANTS: +** +** {F12801} The [sqlite3_errcode(D)] interface returns the numeric +** [SQLITE_OK | result code] or +** [SQLITE_IOERR_READ | extended result code] +** for the most recent failed interface call associated +** with [sqlite3] handle D. +** +** {U12802} If a prior API call failed but the most recent API call +** succeeded, the return value from [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] are undefined. +** +** {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 UTF8 or UTF16 respectively. +** +** {U12804} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()] +** are only valid until the next SQLite interface call. +** +** {F12807} Calls to [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations of these routines. +** +** {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()]. */ SQLITE_API int sqlite3_errcode(sqlite3 *db); SQLITE_API const char *sqlite3_errmsg(sqlite3*); SQLITE_API const void *sqlite3_errmsg16(sqlite3*); /* -** CAPI3REF: SQL Statement Object -** -** Instance of this object represent single SQL statements. This -** is variously known as a "prepared statement" or a +** CAPI3REF: SQL Statement Object {F13000} +** KEYWORDS: {prepared statement} {prepared statements} +** +** 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: ** ** <ol> @@ -1845,77 +2502,110 @@ ** information. */ typedef struct sqlite3_stmt sqlite3_stmt; /* -** CAPI3REF: Compiling An SQL Statement +** 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. ** -** The first argument "db" is an [sqlite3 | SQLite database handle] +** The first argument "db" is an [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 ** 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. +** 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 +** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *ppStmt is left pointing to a compiled -** [sqlite3_stmt | SQL statement structure] that can be +** 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 compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. +** +** *ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be -** set to NULL. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. The calling -** procedure is responsible for deleting the compiled SQL statement +** set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. +** [error code] is returned. ** ** 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 +** original SQL text. {END} This causes the [sqlite3_step()] interface to ** behave a differently in two ways: ** ** <ol> ** <li> ** 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 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. +** statement and try to run it again. 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. {END} ** </li> ** ** <li> ** When an error occurs, ** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. +** [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. ** </li> ** </ol> +** +** 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, then 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 nBytes bytes +** 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. +** <todo>What does *pzTail point to if there is one statement?</todo> +** +** {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. */ SQLITE_API int sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ @@ -1943,105 +2633,115 @@ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** +** CAPIREF: Retrieving Statement SQL {F13100} +** +** This intereface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement]. +** +** INVARIANTS: +** +** {F13101} If the [prepared statement] passed as +** the an argument to [sqlite3_sql()] was compiled +** compiled using either [sqlite3_prepare_v2()] or +** [sqlite3_prepare16_v2()], +** then [sqlite3_sql()] function 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 an argument to [sqlite3_sql()] was compiled +** compiled using either [sqlite3_prepare()] or +** [sqlite3_prepare16()], +** then [sqlite3_sql()] function 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)]. */ SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt); /* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. +** SQLite uses dynamic typing for the values it stores. +** 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 +** CAPI3REF: SQL Function Context Object {F16001} ** ** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. +** sqlite3_context object. 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 -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: ** ** <ul> ** <li> ? ** <li> ?NNN -** <li> :AAA -** <li> @AAA +** <li> :VVV +** <li> @VVV ** <li> $VVV ** </ul> ** ** 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. -** The values of these parameters (also called "host parameter names") +** VVV alpha-numeric parameter name. +** The values of these parameters (also called "host parameter names" +** or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** -** 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. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. +** 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. The second +** argument is the index of the parameter to be set. The +** first parameter has an index of 1. When the same named +** 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_name()] API if desired. The index +** for "?NNN" parameters is the value of NNN. ** The NNN value must be between 1 and the compile-time ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. ** ** The third argument is the value to bind to the parameter. ** ** 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. The number +** in the parameter. To be clear: the value is the number of <u>bytes</u> +** in the value, not the number of characters. The number ** of bytes does not include the zero-terminator at the end of strings. ** If the fourth parameter is negative, the length of the string is ** number of bytes up to the first zero terminator. ** ** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that +** string after SQLite has finished with it. If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite 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 +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeros. A zeroblob uses a fixed amount of memory ** (just an integer to hold it size) while it is being processed. ** Zeroblobs are intended to serve as place-holders for BLOBs whose ** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative +** [sqlite3_blob_open | increment BLOB I/O] routines. A negative ** value for the zeroblob results in a zero-length BLOB. ** ** The sqlite3_bind_*() routines must be called after ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and ** before [sqlite3_step()]. @@ -2049,12 +2749,89 @@ ** Unbound parameters are interpreted as NULL. ** ** 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] is returned if these routines are called on a virtual -** machine that is the wrong state or which has already been finalized. +** [SQLITE_MISUSE] might be 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 [sqlite3_prepare | 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 occurances of the same +** parameter, or one more than the largest index over all +** parameters to the left if this is the first occurrance +** of this parameter, or 1 if this is the leftmost parameter. +** +** {F13521} The [sqlite3_prepare | SQL statement compiler] fail with +** an [SQLITE_RANGE] error if the index of an SQL parameter +** is less than 1 or greater than SQLITE_MAX_VARIABLE_NUMBER. +** +** {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 V value 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 +** V value after it has finished using the V value. +** +** {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. */ 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); SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int); SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64); @@ -2063,157 +2840,304 @@ SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); 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 Host Parameters -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. +** CAPI3REF: Number Of SQL 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 +** place-holders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** This routine actually returns the index of the largest 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. */ SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*); /* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** 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 ":AAA" or "@AAA" or "$AAA" 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. ** Parameters of the form "?" or "?NNN" have no name. ** -** The first bound 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 the -** UTF-8 encoding even if the named parameter was originally specified -** as UTF-16 in [sqlite3_prepare16()] or [sqlite3_prepare16_v2()]. +** 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 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 +** [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 "?" or +** a numbered parameter "?NNN". */ SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* -** CAPI3REF: Index Of A Parameter With A Given Name -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. +** 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 [prepared statement] +** S whose name matches the UTF-8 string N, or 0 if there is +** no match. */ SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* -** CAPI3REF: Reset All Bindings On A Prepared Statement +** 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 -** [sqlite3_stmt | prepared statement]. Use this routine to +** [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 [prepared statement] S +** back to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*); /* -** CAPI3REF: Number Of Columns In A Result Set +** CAPI3REF: Number Of Columns In A Result Set {F13710} ** ** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. This routine returns 0 +** [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. */ SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt); /* -** CAPI3REF: Column Names In A Result Set +** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. The first parameter is the -** [sqlite3_stmt | prepared statement] that implements the SELECT statement. +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. The first parameter is the +** [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 -** [sqlite3_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** [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 ** (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 left-most column) for the +** result set of [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 left-most column) for the +** result set of [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 memory to hold there 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 returns 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 indentifier +** 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); /* -** CAPI3REF: Source Of Data In A Query Result +** 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 UTF8 or UTF16 string. 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 [sqlite3_stmt | prepared statement] is destroyed using +** the [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 ** database, table, and column. ** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. +** The first argument to the following calls is a [prepared statement]. ** 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. Otherwise, they return the +** 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. ** -** As with all other SQLite APIs, those postfixed with "16" return UTF-16 -** encoded strings, the other functions return UTF-8. +** 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. +** +** 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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: +** +** {U13751} If two or more threads call one or more +** [sqlite3_column_database_name|column metadata interfaces] +** 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); SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int); SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int); SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int); /* -** CAPI3REF: Declared Datatype Of A Query Result -** -** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** 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 +** 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. 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. For example, in -** the database schema: +** 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: ** @@ -2227,18 +3151,40 @@ ** 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. -*/ -SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *, int i); +** +** INVARIANTS: +** +** {F13761} A successful call to [sqlite3_column_decltype(S,N)] +** returns a zero-terminated UTF-8 string containing the +** 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 [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 void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* -** CAPI3REF: Evaluate An SQL Statement -** -** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [prepared 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. ** @@ -2277,15 +3223,15 @@ ** 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, +** [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 +** Perhaps it was called on a [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. ** @@ -2293,46 +3239,81 @@ ** 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. +** [error 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 +** more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. +** +** INVARIANTS: +** +** {F13202} If [prepared statement] S is ready to be +** run, then [sqlite3_step(S)] advances that prepared statement +** until to completion or until it is ready to return another +** row of the result set or an interrupt or 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 appropraite error code that is not one of +** [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE]. +** +** {F15310} If an [sqlite3_interrupt|interrupt] or 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: +** CAPI3REF: Number of columns in a result set {F13770} ** ** Return the number of values in the current row of the result set. ** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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. +** 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. */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt); /* -** CAPI3REF: Fundamental Datatypes -** -** Every value in SQLite has one of five fundamental datatypes: +** CAPI3REF: Fundamental Datatypes {F10265} +** KEYWORDS: SQLITE_TEXT +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: ** ** <ul> ** <li> 64-bit signed integer ** <li> 64-bit IEEE floating point number ** <li> string ** <li> BLOB ** <li> NULL -** </ul> +** </ul> {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 @@ -2349,16 +3330,18 @@ # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 /* -** CAPI3REF: Results Values From A Query +** 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 +** [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 left-most column of the result set ** has an index of 0. @@ -2395,16 +3378,16 @@ ** 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 +** even empty 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. +** but leaves the result in UTF-16 in native byte order 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 @@ -2492,10 +3475,65 @@ ** 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]. +** +** INVARIANTS: +** +** {F13803} The [sqlite3_column_blob(S,N)] interface converts the +** Nth column in the current row of the result set for +** [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 +** [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 +** [prepared statement] S into a 32-bit signed integer and +** returns a copy of that integer. +** +** {F13818} The [sqlite3_column_int64(S,N)] interface converts the +** Nth column in the current row of the result set for +** [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 +** [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 +** [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 +** [prepared statement] S. +** +** {F13830} The [sqlite3_column_value(S,N)] interface returns a +** pointer to the [sqlite3_value] object that for the +** Nth column in the current row of the result set for +** [prepared statement] S. */ SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol); SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol); @@ -2505,51 +3543,78 @@ SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol); SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol); SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol); /* -** CAPI3REF: Destroy A Prepared Statement Object +** 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 +** [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 -** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** [error code] or [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 +** [prepared statement]. 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]. +** [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. */ SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt); /* -** CAPI3REF: Reset A Prepared Statement Object +** CAPI3REF: Reset A Prepared Statement Object {F13330} ** ** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's initial state, ready to be re-executed. +** [prepared 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 +** [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 +** [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 [prepared statement] S. */ SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt); /* -** CAPI3REF: Create Or Redefine SQL Functions -** -** The following two functions are used to add SQL functions or aggregates +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** KEYWORDS: {function creation routines} +** +** 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 ** 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 +** The first argument is the [database connection] 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. ** @@ -2593,34 +3658,44 @@ ** 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. +** +** 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 a +** zero-terminated UTF-8. +** +** {F16106} */ SQLITE_API int sqlite3_create_function( - sqlite3 *, + sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, - void*, + void *pApp, 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*, + sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, - void*, + void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); /* -** CAPI3REF: Text Encodings +** CAPI3REF: Text Encodings {F10267} ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ #define SQLITE_UTF8 1 @@ -2645,11 +3720,11 @@ SQLITE_API int sqlite3_global_recover(void); SQLITE_API void sqlite3_thread_cleanup(void); SQLITE_API int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64); /* -** CAPI3REF: Obtaining SQL Function Parameter Values +** 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. ** @@ -2672,13 +3747,13 @@ ** 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 order -** words if the value is original a string that looks like a number) -** then it is done. Otherwise no conversion occurs. The +** 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 @@ -2688,10 +3763,11 @@ ** 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()]. +** */ SQLITE_API const void *sqlite3_value_blob(sqlite3_value*); SQLITE_API int sqlite3_value_bytes(sqlite3_value*); SQLITE_API int sqlite3_value_bytes16(sqlite3_value*); SQLITE_API double sqlite3_value_double(sqlite3_value*); @@ -2703,21 +3779,24 @@ SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*); SQLITE_API int sqlite3_value_type(sqlite3_value*); SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*); /* -** CAPI3REF: Obtain Aggregate Function Context +** CAPI3REF: Obtain Aggregate Function Context {F16210} ** ** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation +** 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 buffer allocated is freed automatically by SQLite whan the aggregate -** query concludes. +** {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. @@ -2726,24 +3805,25 @@ ** the aggregate SQL function is running. */ SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes); /* -** CAPI3REF: User Data For Functions -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. +** 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. */ SQLITE_API void *sqlite3_user_data(sqlite3_context*); /* -** CAPI3REF: Function Auxiliary Data +** 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 @@ -2752,35 +3832,42 @@ ** 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 with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. +** 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. */ -SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int); -SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior +SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N); +SQLITE_API 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 @@ -2794,11 +3881,11 @@ 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 +** 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. @@ -2808,21 +3895,94 @@ ** to bind values to host parameters in prepared statements. ** Refer to the ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for ** additional information. ** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. +** {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. */ SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); SQLITE_API void sqlite3_result_double(sqlite3_context*, double); SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int); SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int); @@ -2837,53 +3997,58 @@ SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*); SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n); /* -** CAPI3REF: Define New Collating Sequences -** +** 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(). 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 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 -** sequence (so that SQLite cannot call it anymore). Each time the user +** 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. ** -** The remaining arguments to the user-supplied routine are two strings, -** each represented by a [length, data] pair and encoded in the encoding +** {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. The user routine should return negative, zero or positive if +** 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. The destructor is called when the collation is +** 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 +** 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()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. */ SQLITE_API int sqlite3_create_collation( sqlite3*, const char *zName, int eTextRep, @@ -2905,30 +4070,33 @@ void*, int(*xCompare)(void*,int,const void*,int,const void*) ); /* -** CAPI3REF: Collation Needed Callbacks -** +** 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. If sqlite3_collation_needed16() is used, the names -** are passed as UTF-16 in machine native byte order. A call to either +** 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 -** handle. 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()]. */ @@ -2967,27 +4135,28 @@ sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); /* -** CAPI3REF: Suspend Execution For A Short Time -** -** This function causes the current thread to suspend execution -** a number of milliseconds specified in its parameter. -** -** If the operating system does not support sleep requests with +** 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. The number of milliseconds of sleep actually +** 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. +** {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 +** 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 @@ -2999,171 +4168,216 @@ ** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. +** CAPI3REF: Test To See If The Database Is In Auto-Commit Mode {F12930} +** +** 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 reenabled by a [COMMIT] or [ROLLBACK]. ** ** 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. The only way to ** find out if SQLite automatically rolled back the transaction after ** an error is to use this function. ** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. +** INVARIANTS: +** +** {F12931} The [sqlite3_get_autocommit()] interface 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 successful [BEGIN] statement. +** +** {F12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK] +** statement. +** +** +** LIMITATIONS: +*** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. */ SQLITE_API int sqlite3_get_autocommit(sqlite3*); /* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This is the same database handle that was +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [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: Commit And Rollback Notification Callbacks -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. The pArg argument is passed through -** to the callback. If the callback on a commit hook function +** 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. ** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** For the purposes of this API, a transaction is said to have been +** {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. The -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. +** 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. +** <todo> Check on this </todo> {END} ** ** 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*); /* -** CAPI3REF: Data Change Notification Callbacks -** -** Register a callback function with the database connection identified by the +** 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. -** Any callback set by a previous call to this function for the same +** {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 +** {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. The final callback parameter is -** the rowid of the row. In the case of an update, this is the rowid after +** 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. +** {F12984} If another function was previously registered, its pArg value +** is returned. {F12985} Otherwise NULL is returned. */ SQLITE_API void *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); /* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** +** 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. ** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was +** {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. -** -** Virtual tables cannot be used with a shared cache. When shared +** {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. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. But this might change in +** virtual tables will always return an error. {END} +** +** {F10337} This routine returns [SQLITE_OK] if shared cache was +** enabled or disabled successfully. {F10338} An [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. */ SQLITE_API int sqlite3_enable_shared_cache(int); /* -** CAPI3REF: Attempt To Free Heap Memory -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). +** 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. */ SQLITE_API int sqlite3_release_memory(int); /* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is +** 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. -** -** The limit is called "soft", because if [sqlite3_release_memory()] cannot +** 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. -** The default value for the soft heap limit is zero. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. This is why the limit is +** {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. 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. */ SQLITE_API void sqlite3_soft_heap_limit(int); /* -** CAPI3REF: Extract Metadata About A Column Of A Table +** 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. @@ -3235,22 +4449,29 @@ int *pPrimaryKey, /* OUTPUT: True if column part of PK */ int *pAutoinc /* OUTPUT: True if column is auto-increment */ ); /* -** CAPI3REF: Load An Extension -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory +** 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. */ SQLITE_API int sqlite3_load_extension( sqlite3 *db, /* Load the extension into this database connection */ @@ -3258,59 +4479,62 @@ 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 +** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. +** 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} */ SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff); /* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked +** 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()]. +** [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. ** -** Duplicate extensions are detected so calling this routine multiple +** {F12642} Duplicate extensions are detected so calling this routine multiple ** times with the same extension is harmless. ** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). If you run a memory leak +** {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. ** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** 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_auto_extension()] ** calls. ** -** This call disabled 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); @@ -3381,11 +4605,12 @@ ** The aConstraint[] array records WHERE clause constraints of the ** form: ** ** column OP expr ** -** Where OP is =, <, <=, >, or >=. The particular operator is stored +** 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. ** @@ -3550,11 +4775,11 @@ ** ****** EXPERIMENTAL - subject to change without notice ************** */ /* -** CAPI3REF: A Handle To An Open BLOB +** 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 @@ -3563,30 +4788,32 @@ ** blob in bytes. */ typedef struct sqlite3_blob sqlite3_blob; /* -** CAPI3REF: Open A BLOB For Incremental I/O -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: +** 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: ** ** <pre> ** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** If the flags parameter is non-zero, the blob is opened for +** </pre> {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. -** -** On success, [SQLITE_OK] is returned and the new +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new ** [sqlite3_blob | blob handle] is written to *ppBlob. -** Otherwise an error code is returned and +** {F17814} Otherwise an error code is returned and ** any value written to *ppBlob should not be used by the caller. -** This function sets the database-handle error code and message +** {F17815} This function sets the database-handle error code and message ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** <todo>We should go through and mark all interfaces that behave this +** way with a similar statement</todo> */ SQLITE_API int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, @@ -3595,95 +4822,113 @@ int flags, sqlite3_blob **ppBlob ); /* -** CAPI3REF: Close A BLOB Handle +** 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. */ SQLITE_API int sqlite3_blob_close(sqlite3_blob *); /* -** CAPI3REF: Return The Size Of An Open BLOB -** -** Return the size in bytes of the blob accessible via the open +** 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. */ SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *); /* -** CAPI3REF: Read Data From A BLOB Incrementally +** 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. -** n bytes of data are copied into buffer +** {F17851} n bytes of data are copied into buffer ** z from the open blob, starting at offset iOffset. ** -** On success, SQLITE_OK is returned. Otherwise, an -** [SQLITE_ERROR | SQLite error code] or an -** [SQLITE_IOERR_READ | extended error code] is returned. +** {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 +** [error code] or an [extended error code] is returned. */ SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); /* -** CAPI3REF: Write Data Into A BLOB Incrementally +** 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. -** n bytes of data are copied from the 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 [sqlite3_blob | blob-handle] passed as the first argument +** {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. -** -** On success, SQLITE_OK is returned. Otherwise, an -** [SQLITE_ERROR | SQLite error code] or an -** [SQLITE_IOERR_READ | extended error code] is returned. +** {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 +** [error code] or an [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 +** 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. ** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 +** {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. ** -** 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. */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName); SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt); SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*); /* -** CAPI3REF: Mutexes +** 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. @@ -3713,14 +4958,14 @@ ** 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. ** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument +** {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: ** ** <ul> ** <li> SQLITE_MUTEX_FAST ** <li> SQLITE_MUTEX_RECURSIVE @@ -3727,64 +4972,66 @@ ** <li> SQLITE_MUTEX_STATIC_MASTER ** <li> SQLITE_MUTEX_STATIC_MEM ** <li> SQLITE_MUTEX_STATIC_MEM2 ** <li> SQLITE_MUTEX_STATIC_PRNG ** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** The first two constants cause sqlite3_mutex_alloc() to create +** </ul> {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. +** 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. But SQLite will only request a recursive mutex in -** cases where it really needs one. If a faster non-recursive mutex +** 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. ** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. Four static mutexes are +** {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. ** -** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST +** {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. 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 sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. +** 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. If another thread is already within the mutex, +** 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. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, +** 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. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. +** 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. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior +** 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. SQLite will -** never do either. +** calling thread or is not currently allocated. {F17033} SQLite will +** never do either. {END} ** ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()]. */ SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int); SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*); @@ -3791,48 +5038,48 @@ SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*); SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*); SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*); /* -** CAPI3REF: Mutex Verifcation Routines +** CAPI3REF: Mutex Verifcation Routines {F17080} ** ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core +** 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. The core only +** 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. 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. ** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** The implementation is not required to provided versions of these +** {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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. This seems counter-intuitive since +** 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. 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*); SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*); /* -** CAPI3REF: Mutex Types -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. +** 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() */ @@ -3839,34 +5086,73 @@ #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 -** -** The [sqlite3_file_control()] interface makes a direct call to the +** 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. The +** with a particular database identified by the second argument. {F11302} The ** name of the database is the name assigned to the database by the ** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine +** 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. The return value of the xFileControl +** the xFileControl method. {F11305} The return value of the xFileControl ** method becomes the return value of this routine. ** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error +** {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()]. The underlying xFileControl method might -** also return SQLITE_ERROR. 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. +** xFileControl method. {END} ** ** See also: [SQLITE_FCNTL_LOCKSTATE] */ 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 a 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 meansing 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_FAULT_CONFIG 1 +#define SQLITE_TESTCTRL_FAULT_FAILURES 2 +#define SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES 3 +#define SQLITE_TESTCTRL_FAULT_PENDING 4 + + + + /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */ @@ -4308,12 +5594,69 @@ void *pArg; /* First arg to busy callback */ 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 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. +** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque +** pointer types (i.e. FuncDef) defined above. */ /************** Include btree.h in the middle of sqliteInt.h *****************/ /************** Begin file btree.h *******************************************/ /* ** 2001 September 15 @@ -4328,11 +5671,11 @@ ************************************************************************* ** This header file defines the interface that the sqlite B-Tree file ** subsystem. See comments in the source code for a detailed description ** of what each interface routine does. ** -** @(#) $Id: btree.h,v 1.93 2007/09/03 15:19:35 drh Exp $ +** @(#) $Id: btree.h,v 1.94 2007/12/07 18:55:28 drh Exp $ */ #ifndef _BTREE_H_ #define _BTREE_H_ /* TODO: This definition is just included so other modules compile. It @@ -4397,11 +5740,10 @@ ** are not associated with PAGER_ values. */ #define BTREE_PRIVATE 64 /* Never share with other connections */ SQLITE_PRIVATE int sqlite3BtreeClose(Btree*); -SQLITE_PRIVATE int sqlite3BtreeSetBusyHandler(Btree*,BusyHandler*); SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int); SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int); SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*); SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int); SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*); @@ -4539,11 +5881,11 @@ ** ** This header defines the interface to the virtual database engine ** 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.115 2007/11/14 06:48:48 danielk1977 Exp $ +** $Id: vdbe.h,v 1.125 2008/01/17 17:27:31 drh Exp $ */ #ifndef _SQLITE_VDBE_H_ #define _SQLITE_VDBE_H_ /* @@ -4552,20 +5894,45 @@ ** of this structure. */ 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; + +/* ** A single instruction of the virtual machine has an opcode ** and as many as three operands. The instruction is recorded ** as an instance of the following structure: */ struct VdbeOp { u8 opcode; /* What operation to perform */ + signed char p4type; /* One of the P4_xxx constants for p4 */ + u8 flags; /* Flags for internal use */ + u8 p5; /* Fifth parameter is an unsigned character */ int p1; /* First operand */ int p2; /* Second parameter (often the jump destination) */ - char *p3; /* Third parameter */ - int p3type; /* One of the P3_xxx constants defined below */ + 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 */ + } p4; +#ifdef SQLITE_DEBUG + char *zComment; /* Comment to improve readability */ +#endif #ifdef VDBE_PROFILE int cnt; /* Number of times this instruction was executed */ long long cycles; /* Total time spend executing this instruction */ #endif }; @@ -4576,40 +5943,41 @@ ** it takes up less space. */ struct VdbeOpList { u8 opcode; /* What operation to perform */ signed char p1; /* First operand */ - short int p2; /* Second parameter (often the jump destination) */ - char *p3; /* Third parameter */ + signed char p2; /* Second parameter (often the jump destination) */ + signed char p3; /* Third parameter */ }; typedef struct VdbeOpList VdbeOpList; /* ** Allowed values of VdbeOp.p3type */ -#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 P3 argument using P3_KEYINFO, a copy of the KeyInfo structure +#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 */ + +/* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure ** is made. That copy is freed when the Vdbe is finalized. But if the -** argument is P3_KEYINFO_HANDOFF, the passed in pointer is used. It still +** argument is P4_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 P3_KEYINFO_HANDOFF (-9) +#define P4_KEYINFO_HANDOFF (-9) /* ** The Vdbe.aColName array contains 5n Mem structures, where n is the ** number of columns of data returned by the statement. */ @@ -4634,185 +6002,207 @@ */ /************** Include opcodes.h in the middle of vdbe.h ********************/ /************** Begin file opcodes.h *****************************************/ /* Automatically generated. Do not edit */ /* See the mkopcodeh.awk script for details */ -#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_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_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_VNext 1 +#define OP_Column 2 +#define OP_SetCookie 3 +#define OP_Real 125 /* same as TK_FLOAT */ +#define OP_Sequence 4 +#define OP_MoveGt 5 +#define OP_Ge 72 /* same as TK_GE */ +#define OP_RowKey 6 +#define OP_SCopy 7 +#define OP_Eq 68 /* same as TK_EQ */ +#define OP_OpenWrite 8 +#define OP_NotNull 66 /* same as TK_NOTNULL */ +#define OP_If 9 #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_MemInt 30 -#define OP_Dup 31 -#define OP_Rewind 32 +#define OP_String8 88 /* same as TK_STRING */ +#define OP_VRowid 10 +#define OP_CollSeq 11 +#define OP_OpenRead 12 +#define OP_Expire 13 +#define OP_AutoCommit 14 +#define OP_Gt 69 /* same as TK_GT */ +#define OP_IntegrityCk 15 +#define OP_Sort 17 +#define OP_Copy 18 +#define OP_Trace 19 +#define OP_Function 20 +#define OP_IfNeg 21 +#define OP_And 61 /* same as TK_AND */ +#define OP_Subtract 79 /* same as TK_MINUS */ +#define OP_Noop 22 +#define OP_Return 23 +#define OP_Remainder 82 /* same as TK_REM */ +#define OP_NewRowid 24 #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_Variable 25 +#define OP_String 26 +#define OP_RealAffinity 27 +#define OP_VRename 28 +#define OP_ParseSchema 29 +#define OP_VOpen 30 +#define OP_Close 31 +#define OP_CreateIndex 32 +#define OP_IsUnique 33 +#define OP_NotFound 34 +#define OP_Int64 35 +#define OP_MustBeInt 36 +#define OP_Halt 37 +#define OP_Rowid 38 +#define OP_IdxLT 39 +#define OP_AddImm 40 +#define OP_Statement 41 +#define OP_RowData 42 +#define OP_MemMax 43 +#define OP_Or 60 /* same as TK_OR */ +#define OP_NotExists 44 +#define OP_Gosub 45 +#define OP_Divide 81 /* same as TK_SLASH */ +#define OP_Integer 46 +#define OP_ToNumeric 140 /* same as TK_TO_NUMERIC*/ +#define OP_Prev 47 +#define OP_Concat 83 /* same as TK_CONCAT */ #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_VColumn 48 +#define OP_CreateTable 49 +#define OP_Last 50 +#define OP_IsNull 65 /* same as TK_ISNULL */ +#define OP_IncrVacuum 51 +#define OP_IdxRowid 52 +#define OP_ShiftRight 77 /* same as TK_RSHIFT */ +#define OP_ResetCount 53 +#define OP_FifoWrite 54 +#define OP_ContextPush 55 +#define OP_DropTrigger 56 +#define OP_DropIndex 57 +#define OP_IdxGE 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_Prev 96 -#define OP_ContextPush 97 -#define OP_DropTrigger 98 -#define OP_IdxGT 99 -#define OP_MemNull 100 -#define OP_IfMemNeg 101 -#define OP_And 61 /* same as TK_AND */ -#define OP_VColumn 102 -#define OP_Return 103 -#define OP_OpenWrite 104 -#define OP_Integer 105 -#define OP_Transaction 106 -#define OP_CollSeq 107 -#define OP_VRename 108 +#define OP_MoveLe 63 +#define OP_IfNot 64 +#define OP_DropTable 73 +#define OP_MakeRecord 84 #define OP_ToBlob 139 /* same as TK_TO_BLOB */ -#define OP_Sequence 109 -#define OP_ContextPop 110 -#define OP_ShiftRight 77 /* same as TK_RSHIFT */ -#define OP_VCreate 111 -#define OP_CreateTable 112 -#define OP_AddImm 113 +#define OP_ResultRow 85 +#define OP_Delete 86 +#define OP_AggFinal 89 +#define OP_ShiftLeft 76 /* same as TK_LSHIFT */ +#define OP_Goto 90 +#define OP_TableLock 91 +#define OP_FifoRead 92 +#define OP_Clear 93 +#define OP_MoveLt 94 +#define OP_Le 70 /* same as TK_LE */ +#define OP_VerifyCookie 95 +#define OP_AggStep 96 #define OP_ToText 138 /* same as TK_TO_TEXT */ -#define OP_DropTable 114 -#define OP_IsUnique 115 -#define OP_VOpen 116 -#define OP_Noop 117 -#define OP_RowKey 118 -#define OP_Expire 119 -#define OP_FifoRead 120 -#define OP_Delete 121 -#define OP_IfMemPos 122 -#define OP_Subtract 79 /* same as TK_MINUS */ -#define OP_MemIncr 123 -#define OP_Blob 124 -#define OP_MakeIdxRec 127 -#define OP_Goto 128 -#define OP_Negative 85 /* same as TK_UMINUS */ -#define OP_ParseSchema 129 -#define OP_Eq 68 /* same as TK_EQ */ -#define OP_VNext 130 -#define OP_Pop 131 -#define OP_Le 70 /* same as TK_LE */ -#define OP_TableLock 132 -#define OP_VerifyCookie 133 -#define OP_Column 134 -#define OP_OpenRead 135 -#define OP_ResetCount 136 +#define OP_Not 16 /* same as TK_NOT */ +#define OP_ToReal 142 /* same as TK_TO_REAL */ +#define OP_SetNumColumns 97 +#define OP_Transaction 98 +#define OP_VFilter 99 +#define OP_Ne 67 /* same as TK_NE */ +#define OP_VDestroy 100 +#define OP_ContextPop 101 +#define OP_BitOr 75 /* same as TK_BITOR */ +#define OP_Next 102 +#define OP_IdxInsert 103 +#define OP_Lt 71 /* same as TK_LT */ +#define OP_Insert 104 +#define OP_Destroy 105 +#define OP_ReadCookie 106 +#define OP_ForceInt 107 +#define OP_LoadAnalysis 108 +#define OP_Explain 109 +#define OP_OpenPseudo 110 +#define OP_OpenEphemeral 111 +#define OP_Null 112 +#define OP_Move 113 +#define OP_Blob 114 +#define OP_Add 78 /* same as TK_PLUS */ +#define OP_Rewind 115 +#define OP_MoveGe 116 +#define OP_VBegin 117 +#define OP_VUpdate 118 +#define OP_IfZero 119 +#define OP_BitNot 87 /* same as TK_BITNOT */ +#define OP_VCreate 120 +#define OP_Found 121 +#define OP_IfPos 122 +#define OP_NullRow 123 /* The following opcode values are never used */ +#define OP_NotUsed_124 124 +#define OP_NotUsed_126 126 +#define OP_NotUsed_127 127 +#define OP_NotUsed_128 128 +#define OP_NotUsed_129 129 +#define OP_NotUsed_130 130 +#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 -/* 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 0xddaf -#define NOPUSH_MASK_7 0x0ebe -#define NOPUSH_MASK_8 0x7dbf -#define NOPUSH_MASK_9 0x0000 + +/* 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, 0x10, 0x02, 0x11, 0x02, 0x00,\ +/* 8 */ 0x00, 0x05, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 16 */ 0x04, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00,\ +/* 24 */ 0x02, 0x02, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00,\ +/* 32 */ 0x02, 0x11, 0x11, 0x02, 0x05, 0x00, 0x02, 0x11,\ +/* 40 */ 0x04, 0x00, 0x02, 0x0c, 0x11, 0x01, 0x02, 0x01,\ +/* 48 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x04, 0x00,\ +/* 56 */ 0x00, 0x00, 0x11, 0x08, 0x2c, 0x2c, 0x00, 0x11,\ +/* 64 */ 0x05, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\ +/* 72 */ 0x15, 0x00, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\ +/* 80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x00, 0x00, 0x00, 0x04,\ +/* 88 */ 0x02, 0x00, 0x01, 0x00, 0x01, 0x00, 0x11, 0x00,\ +/* 96 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x08,\ +/* 104 */ 0x00, 0x02, 0x02, 0x05, 0x00, 0x00, 0x00, 0x00,\ +/* 112 */ 0x02, 0x00, 0x02, 0x01, 0x11, 0x00, 0x00, 0x05,\ +/* 120 */ 0x00, 0x11, 0x05, 0x00, 0x00, 0x02, 0x00, 0x00,\ +/* 128 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\ +/* 136 */ 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,} /************** End of opcodes.h *********************************************/ /************** Continuing where we left off in vdbe.h ***********************/ /* ** Prototypes for the VDBE interface. See comments on the implementation ** for a description of what each of these routines does. */ SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*); -SQLITE_PRIVATE int sqlite3VdbeAddOp(Vdbe*,int,int,int); -SQLITE_PRIVATE int sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int); +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 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 sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N); +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N); SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int); SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int); SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int); @@ -4857,11 +6247,11 @@ ************************************************************************* ** This header file defines the interface that the sqlite page cache ** 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.67 2007/09/03 15:19:35 drh Exp $ +** @(#) $Id: pager.h,v 1.68 2007/11/28 16:19:56 drh Exp $ */ #ifndef _PAGER_H_ #define _PAGER_H_ @@ -4938,10 +6328,11 @@ SQLITE_PRIVATE int sqlite3PagerNosync(Pager*); 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 void *sqlite3PagerTempSpace(Pager*); #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO) SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int); #endif @@ -4970,66 +6361,10 @@ #endif /* _PAGER_H_ */ /************** 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 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 **********************************************/ /* ** 2001 September 16 @@ -5158,20 +6493,10 @@ ** of the file. */ #ifndef SQLITE_TEMP_FILE_PREFIX # define SQLITE_TEMP_FILE_PREFIX "etilqs_" #endif - -/* -** If using an alternative OS interface, then we must have an "os_other.h" -** header file available for that interface. Presumably the "os_other.h" -** header file contains #defines similar to those above. -*/ -#if OS_OTHER -# include "os_other.h" -#endif - /* ** The following values may be passed as the second argument to ** sqlite3OsLock(). The various locks exhibit the following semantics: ** @@ -5510,10 +6835,11 @@ int errCode; /* Most recent error code (SQLITE_*) */ int errMask; /* & result codes with this before returning */ 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 */ + signed 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) */ i64 priorNewRowid; /* Last randomly generated ROWID */ int magic; /* Magic number for detect library misuse */ @@ -5618,10 +6944,11 @@ ** The numbers are obtained at random and have no special meaning, other ** than being distinct from one another. */ #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 */ /* ** Each SQL function is defined by an instance of the following @@ -5729,11 +7056,11 @@ ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve ** the speed a little by number the values consecutively. ** ** 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 P3 operand, they will be more readable. +** used as the P4 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. */ #define SQLITE_AFF_TEXT 'a' @@ -5741,10 +7068,24 @@ #define SQLITE_AFF_NUMERIC 'c' #define SQLITE_AFF_INTEGER 'd' #define SQLITE_AFF_REAL 'e' #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_NULLEQUAL 0x10 /* compare NULLs equal */ +#define SQLITE_STOREP2 0x80 /* Store result in reg[P2] rather than jump */ /* ** Each SQL table is represented in memory by an instance of the ** following structure. ** @@ -5913,10 +7254,11 @@ */ struct KeyInfo { sqlite3 *db; /* The database connection */ u8 enc; /* Text encoding - one of the TEXT_Utf* values */ u8 incrKey; /* Increase 2nd key by epsilon before comparison */ + u8 prefixIsEqual; /* Treat a prefix as equal */ int nField; /* Number of entries in aColl[] */ u8 *aSortOrder; /* If defined an aSortOrder[i] is true, sort DESC */ CollSeq *aColl[1]; /* Collating sequence for each term of the key */ }; @@ -6256,10 +7598,14 @@ ** FROM clause and the WhereLevel structure is a convenient place. */ sqlite3_index_info *pIdxInfo; /* Index info for n-th source table */ }; +#define ORDERBY_NORMAL 0 +#define ORDERBY_MIN 1 +#define ORDERBY_MAX 2 + /* ** The WHERE clause processing routine has two halves. The ** first part does the start of the WHERE loop and the second ** half does the tail of the WHERE loop. An instance of ** this structure is returned by the first half and passed @@ -6321,11 +7667,11 @@ ** offset). But later on, nLimit and nOffset become the memory locations ** in the VDBE that record the limit and offset counters. ** ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes. ** These addresses must be stored so that we can go back and fill in -** the P3_KEYINFO and P2 parameters later. Neither the KeyInfo nor +** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor ** the number of columns in P2 can be computed at the same time ** as the OP_OpenEphm instruction is coded because not ** enough information about the compound query is known at that point. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences ** for the result set. The KeyInfo for addrOpenTran[2] contains collating @@ -6344,10 +7690,11 @@ Expr *pWhere; /* The WHERE clause */ ExprList *pGroupBy; /* The GROUP BY clause */ Expr *pHaving; /* The HAVING clause */ ExprList *pOrderBy; /* The ORDER BY clause */ Select *pPrior; /* Prior select in a compound select statement */ + Select *pNext; /* Next select to the left in a compound */ Select *pRightmost; /* Right-most select in a compound select statement */ Expr *pLimit; /* LIMIT expression. NULL means not used. */ Expr *pOffset; /* OFFSET expression. NULL means not used. */ int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */ int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */ @@ -6356,22 +7703,34 @@ /* ** The results of a select can be distributed in several ways. */ #define SRT_Union 1 /* Store result as keys in an index */ #define SRT_Except 2 /* Remove result from a UNION index */ -#define SRT_Discard 3 /* Do not save the results anywhere */ +#define SRT_Exists 3 /* Store 1 if the result is not empty */ +#define SRT_Discard 4 /* Do not save the results anywhere */ /* The ORDER BY clause is ignored for all of the above */ -#define IgnorableOrderby(X) (X<=SRT_Discard) - -#define SRT_Callback 4 /* Invoke a callback with each row of result */ -#define SRT_Mem 5 /* Store result in a memory cell */ -#define SRT_Set 6 /* Store non-null results as keys in an index */ -#define SRT_Table 7 /* Store result as data with an automatic rowid */ -#define SRT_EphemTab 8 /* Create transient tab and store like SRT_Table */ -#define SRT_Subroutine 9 /* Call a subroutine to handle results */ -#define SRT_Exists 10 /* Store 1 if the result is not empty */ +#define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard) + +#define SRT_Callback 5 /* Invoke a callback with each row of result */ +#define SRT_Mem 6 /* Store result in a memory cell */ +#define SRT_Set 7 /* Store non-null results as keys in an index */ +#define SRT_Table 8 /* Store result as data with an automatic rowid */ +#define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */ +#define SRT_Subroutine 10 /* Call a subroutine to handle results */ + +/* +** A structure used to customize the behaviour of sqlite3Select(). See +** comments above sqlite3Select() for details. +*/ +typedef struct SelectDest SelectDest; +struct SelectDest { + u8 eDest; /* How to dispose of the results */ + u8 affinity; /* Affinity used when eDest==SRT_Set */ + int iParm; /* A parameter used by the eDest disposal method */ + int iMem; /* Base register where results are written */ +}; /* ** An SQL parser context. A copy of this structure is passed through ** the parser and down into all the parser action routine in order to ** carry around information that is global to the entire parse. @@ -6395,15 +7754,20 @@ u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */ u8 nameClash; /* A permanent table name clashes with temp table name */ u8 checkSchema; /* Causes schema cookie check after an error */ u8 nested; /* Number of nested calls to the parser/code generator */ u8 parseError; /* True after a parsing error. Ticket #1794 */ + u8 nTempReg; /* Number of temporary registers in aTempReg[] */ + u8 nTempInUse; /* Number of aTempReg[] currently checked out */ + int aTempReg[8]; /* Holding area for temporary registers */ + int nRangeReg; /* Size of the temporary register block */ + int iRangeReg; /* First register in temporary register block */ int nErr; /* Number of errors seen */ int nTab; /* Number of previously allocated VDBE cursors */ int nMem; /* Number of memory cells used so far */ int nSet; /* Number of sets used so far */ - int ckOffset; /* Stack offset to data used by CHECK constraints */ + int ckBase; /* Base register of data during check constraints */ u32 writeMask; /* Start a write transaction on these databases */ u32 cookieMask; /* Bitmask of schema verified databases */ int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */ int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */ #ifndef SQLITE_OMIT_SHARED_CACHE @@ -6412,10 +7776,12 @@ #endif /* Above is constant between recursions. Below is reset before and after ** each recursion */ + int regRowid; /* Register holding rowid of CREATE TABLE entry */ + int regRoot; /* Register holding root page number for new objects */ int nVar; /* Number of '?' variables seen in the SQL so far */ int nVarExpr; /* Number of used slots in apVarExpr[] */ int nVarExprAlloc; /* Number of allocated slots in apVarExpr[] */ Expr **apVarExpr; /* Pointers to :aaa and $aaaa wildcard expressions */ u8 explain; /* True if the EXPLAIN flag is found on the query */ @@ -6584,10 +7950,12 @@ */ struct TriggerStack { Table *pTab; /* Table that triggers are currently being coded on */ int newIdx; /* Index of vdbe cursor to "new" temp table */ int oldIdx; /* Index of vdbe cursor to "old" temp table */ + u32 newColMask; + u32 oldColMask; int orconf; /* Current orconf policy */ int ignoreJump; /* where to jump to for a RAISE(IGNORE) */ Trigger *pTrigger; /* The trigger currently being coded */ TriggerStack *pNext; /* Next trigger down on the trigger stack */ }; @@ -6601,10 +7969,24 @@ struct DbFixer { Parse *pParse; /* The parsing context. Error messages written here */ const char *zDb; /* Make sure all objects are contained in this database */ const char *zType; /* Type of the container - used for error messages */ const Token *pName; /* Name of the container - used for error messages */ +}; + +/* +** An objected used to accumulate the text of a string where we +** do not necessarily know how big the string will be in the end. +*/ +struct StrAccum { + char *zBase; /* A base allocation. Not from malloc. */ + char *zText; /* The string collected so far */ + int nChar; /* Length of the string so far */ + int nAlloc; /* Amount of space allocated in zText */ + u8 mallocFailed; /* Becomes true if any memory allocation fails */ + u8 useMalloc; /* True if zText is enlargable using realloc */ + u8 tooBig; /* Becomes true if string size exceeds limits */ }; /* ** A pointer to this structure is used to communicate information ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback. @@ -6633,12 +8015,14 @@ ** corruption is first detected. */ #ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3Corrupt(void); # define SQLITE_CORRUPT_BKPT sqlite3Corrupt() +# define DEBUGONLY(X) X #else # define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT +# define DEBUGONLY(X) #endif /* ** Internal function prototypes */ @@ -6658,10 +8042,12 @@ SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...); SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list); #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...); +#endif +#if defined(SQLITE_TEST) SQLITE_PRIVATE void *sqlite3TextToPtr(const char*); #endif SQLITE_PRIVATE void sqlite3SetString(char **, ...); SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...); SQLITE_PRIVATE void sqlite3ErrorClear(Parse*); @@ -6668,10 +8054,14 @@ SQLITE_PRIVATE void sqlite3Dequote(char*); SQLITE_PRIVATE void sqlite3DequoteExpr(sqlite3*, Expr*); SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int); SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **); SQLITE_PRIVATE void sqlite3FinishCoding(Parse*); +SQLITE_PRIVATE int sqlite3GetTempReg(Parse*); +SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int); +SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int); +SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int); SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*, int, Expr*, Expr*, const Token*); SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*); SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*); SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*); SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*); @@ -6720,39 +8110,41 @@ SQLITE_PRIVATE void sqlite3IdListDelete(IdList*); SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList*); SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*, Token*, int, int); SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int); -SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff); +SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*, Select*, int, int*, char *aff); SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*, Expr*,ExprList*,int,Expr*,Expr*); SQLITE_PRIVATE void sqlite3SelectDelete(Select*); +SQLITE_PRIVATE void sqlite3SelectMask(Parse *, Select *, u32); SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*); SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int); SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int); SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*); SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int); -SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**); +SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u8); SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*); -SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int); -SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*); -SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*); -SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*); +SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int, int); +SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int); +SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*); +SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int); +SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int); SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int); SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int); SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*); -SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,const char*, const char*); +SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*); SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*); SQLITE_PRIVATE void sqlite3Vacuum(Parse*); SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*); SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*); SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*); SQLITE_PRIVATE int sqlite3ExprResolveNames(NameContext *, Expr *); -SQLITE_PRIVATE int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); -SQLITE_PRIVATE int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*); +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*); SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*); SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(Parse *, const char*); SQLITE_PRIVATE void sqlite3Randomness(int, void*); SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*); SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int); @@ -6762,16 +8154,17 @@ SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*); SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*); SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*); SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*); SQLITE_PRIVATE int sqlite3IsRowid(const char*); -SQLITE_PRIVATE void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int); -SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*); -SQLITE_PRIVATE void sqlite3GenerateIndexKey(Vdbe*, Index*, int); -SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int); -SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int, int); -SQLITE_PRIVATE void sqlite3OpenTableAndIndices(Parse*, Table*, int, int); +SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int); +SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*); +SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int); +SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int, + int*,int,int,int,int); +SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*,int,int,int,int); +SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int); SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int); SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*); SQLITE_PRIVATE void sqlite3TokenCopy(sqlite3*,Token*, Token*); SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*); SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*); @@ -6778,24 +8171,30 @@ SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*); SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*); SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int); SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*); SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3*); -SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3*); -SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3*); -SQLITE_PRIVATE int sqlite3SafetyCheck(sqlite3*); -SQLITE_PRIVATE void sqlite3ChangeCookie(sqlite3*, Vdbe*, int); +#ifdef SQLITE_DEBUG +SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3*); +SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3*); +#else +# define sqlite3SafetyOn(A) 0 +# define sqlite3SafetyOff(A) 0 +#endif +SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*); +SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*); +SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int); #ifndef SQLITE_OMIT_TRIGGER SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*, Expr*,int, int); SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*); SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int); SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*); SQLITE_PRIVATE int sqlite3TriggersExist(Parse*, Table*, int, ExprList*); SQLITE_PRIVATE int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, - int, int); + int, int, u32*, u32*); void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*); SQLITE_PRIVATE void sqlite3DeleteTriggerStep(TriggerStep*); SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*); SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*, ExprList*,Select*,int); @@ -6806,11 +8205,11 @@ #else # define sqlite3TriggersExist(A,B,C,D,E,F) 0 # define sqlite3DeleteTrigger(A) # define sqlite3DropTriggerPtr(A,B) # define sqlite3UnlinkAndDeleteTrigger(A,B,C) -# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0 +# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I,J,K) 0 #endif SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*); SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int); SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int); @@ -6851,11 +8250,11 @@ SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2); SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity); SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr); SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*); SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...); -SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z); +SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n); SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **); SQLITE_PRIVATE const char *sqlite3ErrStr(int); SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse); SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int); SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName); @@ -6906,13 +8305,16 @@ SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *); SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*)); SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int); -SQLITE_PRIVATE void sqlite3AbortOtherActiveVdbes(sqlite3 *, Vdbe *); SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *); +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int); +SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*); +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*); +SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int); /* ** The interface to the LEMON-generated parser */ SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t)); @@ -6934,30 +8336,10 @@ #endif #ifdef SQLITE_TEST SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*); #endif - -/* -** The MallocDisallow() and MallocAllow() routines are like asserts. -** Call them around a section of code that you do not expect to do -** any memory allocation. -*/ -#ifdef SQLITE_MEMDEBUG -SQLITE_PRIVATE void sqlite3MallocDisallow(void); -SQLITE_PRIVATE void sqlite3MallocAllow(void); -SQLITE_PRIVATE void sqlite3MallocBenignFailure(int); -SQLITE_PRIVATE void sqlite3MallocEnterBenignBlock(int isBenign); -SQLITE_PRIVATE void sqlite3MallocLeaveBenignBlock(); -#else -# define sqlite3MallocDisallow() -# define sqlite3MallocAllow() -# define sqlite3MallocBenignFailure(x) -# define sqlite3MallocEnterBenignBlock(x); -# define sqlite3MallocLeaveBenignBlock(); -#endif - #ifdef SQLITE_OMIT_VIRTUALTABLE # define sqlite3VtabClear(X) # define sqlite3VtabSync(X,Y) (Y) # define sqlite3VtabRollback(X) @@ -6981,10 +8363,45 @@ SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*); SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**); SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*); SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*); SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *); + + +/* +** Available fault injectors. Should be numbered beginning with 0. +*/ +#define SQLITE_FAULTINJECTOR_MALLOC 0 +#define SQLITE_FAULTINJECTOR_COUNT 1 + +/* +** The interface to the fault injector subsystem. If the fault injector +** mechanism is disabled at compile-time then set up macros so that no +** unnecessary code is generated. +*/ +#ifndef SQLITE_OMIT_FAULTINJECTOR +SQLITE_PRIVATE void sqlite3FaultConfig(int,int,int); +SQLITE_PRIVATE int sqlite3FaultFailures(int); +SQLITE_PRIVATE int sqlite3FaultBenignFailures(int); +SQLITE_PRIVATE int sqlite3FaultPending(int); +SQLITE_PRIVATE void sqlite3FaultBenign(int,int); +SQLITE_PRIVATE int sqlite3FaultStep(int); +#else +# define sqlite3FaultConfig(A,B,C) +# define sqlite3FaultFailures(A) 0 +# define sqlite3FaultBenignFailures(A) 0 +# define sqlite3FaultPending(A) (-1) +# define sqlite3FaultBenign(A,B) +# define sqlite3FaultStep(A) 0 +#endif + + + +#define IN_INDEX_ROWID 1 +#define IN_INDEX_EPH 2 +#define IN_INDEX_INDEX 3 +SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int); #ifdef SQLITE_ENABLE_ATOMIC_WRITE SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int); SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *); SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *); @@ -7044,11 +8461,11 @@ ** ** There is only one exported symbol in this file - the function ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file. ** All other code has file scope. ** -** $Id: date.c,v 1.73 2007/09/12 17:01:45 danielk1977 Exp $ +** $Id: date.c,v 1.75 2008/01/17 22:27:54 drh Exp $ ** ** SQLite processes all times and dates as Julian Day numbers. The ** dates and times are stored as the number of days since noon ** in Greenwich on November 24, 4714 B.C. according to the Gregorian ** calendar system. @@ -7678,21 +9095,28 @@ /* ** Process time function arguments. argv[0] is a date-time stamp. ** argv[1] and following are modifiers. Parse them all and write ** the resulting time into the DateTime structure p. Return 0 ** on success and 1 if there are any errors. +** +** If there are zero parameters (if even argv[0] is undefined) +** then assume a default value of "now" for argv[0]. */ static int isDate( sqlite3_context *context, int argc, sqlite3_value **argv, DateTime *p ){ int i; const unsigned char *z; - if( argc==0 ) return 1; - z = sqlite3_value_text(argv[0]); + static const unsigned char zDflt[] = "now"; + if( argc==0 ){ + z = zDflt; + }else{ + z = sqlite3_value_text(argv[0]); + } if( !z || parseDateOrTime(context, (char*)z, p) ){ return 1; } for(i=1; i<argc; i++){ if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){ @@ -7852,11 +9276,14 @@ }else if( n>SQLITE_MAX_LENGTH ){ sqlite3_result_error_toobig(context); return; }else{ z = sqlite3_malloc( n ); - if( z==0 ) return; + if( z==0 ){ + sqlite3_result_error_nomem(context); + return; + } } computeJD(&x); computeYMD_HMS(&x); for(i=j=0; zFmt[i]; i++){ if( zFmt[i]!='%' ){ @@ -7907,19 +9334,17 @@ break; } case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break; case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break; case 'Y': sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=strlen(&z[j]);break; - case '%': z[j++] = '%'; break; + default: z[j++] = '%'; break; } } } z[j] = 0; - sqlite3_result_text(context, z, -1, SQLITE_TRANSIENT); - if( z!=zBuf ){ - sqlite3_free(z); - } + sqlite3_result_text(context, z, -1, + z==zBuf ? SQLITE_TRANSIENT : sqlite3_free); } /* ** current_time() ** @@ -7928,16 +9353,11 @@ static void ctimeFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ - sqlite3_value *pVal = sqlite3ValueNew(0); - if( pVal ){ - sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC); - timeFunc(context, 1, &pVal); - sqlite3ValueFree(pVal); - } + timeFunc(context, 0, 0); } /* ** current_date() ** @@ -7946,16 +9366,11 @@ static void cdateFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ - sqlite3_value *pVal = sqlite3ValueNew(0); - if( pVal ){ - sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC); - dateFunc(context, 1, &pVal); - sqlite3ValueFree(pVal); - } + dateFunc(context, 0, 0); } /* ** current_timestamp() ** @@ -7964,16 +9379,11 @@ static void ctimestampFunc( sqlite3_context *context, int argc, sqlite3_value **argv ){ - sqlite3_value *pVal = sqlite3ValueNew(0); - if( pVal ){ - sqlite3ValueSetStr(pVal, -1, "now", SQLITE_UTF8, SQLITE_STATIC); - datetimeFunc(context, 1, &pVal); - sqlite3ValueFree(pVal); - } + datetimeFunc(context, 0, 0); } #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */ #ifdef SQLITE_OMIT_DATETIME_FUNCS /* @@ -8161,39 +9571,17 @@ return id->pMethods->xCheckReservedLock(id); } SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){ return id->pMethods->xFileControl(id,op,pArg); } - -#ifdef SQLITE_TEST - /* The following two variables are used to override the values returned - ** by the xSectorSize() and xDeviceCharacteristics() vfs methods for - ** testing purposes. They are usually set by a test command implemented - ** in test6.c. - */ - int sqlite3_test_sector_size = 0; - int sqlite3_test_device_characteristics = 0; - int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ - int dc = id->pMethods->xDeviceCharacteristics(id); - return dc | sqlite3_test_device_characteristics; - } - int sqlite3OsSectorSize(sqlite3_file *id){ - if( sqlite3_test_sector_size==0 ){ - int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; - return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); - } - return sqlite3_test_sector_size; - } -#else - int sqlite3OsSectorSize(sqlite3_file *id){ - int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; - return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); - } - int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ - return id->pMethods->xDeviceCharacteristics(id); - } -#endif +SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){ + int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; + return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE); +} +SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){ + return id->pMethods->xDeviceCharacteristics(id); +} /* ** The next group of routines are convenience wrappers around the ** VFS methods. */ @@ -8285,11 +9673,13 @@ /* ** Locate a VFS by name. If no name is given, simply return the ** first VFS on the list. */ SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){ +#ifndef SQLITE_MUTEX_NOOP sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); +#endif sqlite3_vfs *pVfs = 0; static int isInit = 0; sqlite3_mutex_enter(mutex); if( !isInit ){ vfsList = sqlite3OsDefaultVfs(); @@ -8327,11 +9717,13 @@ ** Register a VFS with the system. It is harmless to register the same ** VFS multiple times. The new VFS becomes the default if makeDflt is ** true. */ SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){ +#ifndef SQLITE_MUTEX_NOOP sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); +#endif sqlite3_vfs_find(0); /* Make sure we are initialized */ sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); if( makeDflt || vfsList==0 ){ pVfs->pNext = vfsList; @@ -8347,18 +9739,169 @@ /* ** Unregister a VFS so that it is no longer accessible. */ SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){ +#ifndef SQLITE_MUTEX_NOOP sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); +#endif sqlite3_mutex_enter(mutex); vfsUnlink(pVfs); sqlite3_mutex_leave(mutex); return SQLITE_OK; } /************** End of os.c **************************************************/ +/************** Begin file fault.c *******************************************/ +/* +** 2008 Jan 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 contains code to implement a fault-injector used for +** testing and verification of SQLite. +** +** Subsystems within SQLite can call sqlite3FaultStep() to see if +** they should simulate a fault. sqlite3FaultStep() normally returns +** zero but will return non-zero if a fault should be simulated. +** Fault injectors can be used, for example, to simulate memory +** allocation failures or I/O errors. +** +** The fault injector is omitted from the code if SQLite is +** compiled with -DSQLITE_OMIT_FAULTINJECTOR=1. There is a very +** small performance hit for leaving the fault injector in the code. +** Commerical products will probably want to omit the fault injector +** from production builds. But safety-critical systems who work +** under the motto "fly what you test and test what you fly" may +** choose to leave the fault injector enabled even in production. +*/ + +#ifndef SQLITE_OMIT_FAULTINJECTOR + +/* +** There can be various kinds of faults. For example, there can be +** a memory allocation failure. Or an I/O failure. For each different +** fault type, there is a separate FaultInjector structure to keep track +** of the status of that fault. +*/ +static struct FaultInjector { + int iCountdown; /* Number of pending successes before we hit a failure */ + int nRepeat; /* Number of times to repeat the failure */ + int nBenign; /* Number of benign failures seen since last config */ + int nFail; /* Number of failures seen since last config */ + u8 enable; /* True if enabled */ + u8 benign; /* Ture if next failure will be benign */ +} aFault[SQLITE_FAULTINJECTOR_COUNT]; + +/* +** This routine configures and enables a fault injector. After +** calling this routine, aFaultStep() will return false (zero) +** nDelay times, then it will return true nRepeat times, +** then it will again begin returning false. +*/ +SQLITE_PRIVATE void sqlite3FaultConfig(int id, int nDelay, int nRepeat){ + assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT ); + aFault[id].iCountdown = nDelay; + aFault[id].nRepeat = nRepeat; + aFault[id].nBenign = 0; + aFault[id].nFail = 0; + aFault[id].enable = nDelay>=0; + aFault[id].benign = 0; +} + +/* +** Return the number of faults (both hard and benign faults) that have +** occurred since the injector was last configured. +*/ +SQLITE_PRIVATE int sqlite3FaultFailures(int id){ + assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT ); + return aFault[id].nFail; +} + +/* +** Return the number of benign faults that have occurred since the +** injector was last configured. +*/ +SQLITE_PRIVATE int sqlite3FaultBenignFailures(int id){ + assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT ); + return aFault[id].nBenign; +} + +/* +** Return the number of successes that will occur before the next failure. +** If no failures are scheduled, return -1. +*/ +SQLITE_PRIVATE int sqlite3FaultPending(int id){ + assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT ); + if( aFault[id].enable ){ + return aFault[id].iCountdown; + }else{ + return -1; + } +} + +/* +** After this routine causes subsequent faults to be either benign +** or hard (not benign), according to the "enable" parameter. +** +** Most faults are hard. In other words, most faults cause +** an error to be propagated back up to the application interface. +** However, sometimes a fault is easily recoverable. For example, +** if a malloc fails while resizing a hash table, this is completely +** recoverable simply by not carrying out the resize. The hash table +** will continue to function normally. So a malloc failure during +** a hash table resize is a benign fault. +*/ +SQLITE_PRIVATE void sqlite3FaultBenign(int id, int enable){ + assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT ); + aFault[id].benign = enable; +} + +/* +** This routine exists as a place to set a breakpoint that will +** fire on any simulated fault. +*/ +static void sqlite3Fault(void){ + static int cnt = 0; + cnt++; +} + + +/* +** Check to see if a fault should be simulated. Return true to simulate +** the fault. Return false if the fault should not be simulated. +*/ +SQLITE_PRIVATE int sqlite3FaultStep(int id){ + assert( id>=0 && id<SQLITE_FAULTINJECTOR_COUNT ); + if( likely(!aFault[id].enable) ){ + return 0; + } + if( aFault[id].iCountdown>0 ){ + aFault[id].iCountdown--; + return 0; + } + sqlite3Fault(); + aFault[id].nFail++; + if( aFault[id].benign ){ + aFault[id].nBenign++; + } + aFault[id].nRepeat--; + if( aFault[id].nRepeat<=0 ){ + aFault[id].enable = 0; + } + return 1; +} + +#endif /* SQLITE_OMIT_FAULTINJECTOR */ + +/************** End of fault.c ***********************************************/ /************** Begin file mem1.c ********************************************/ /* ** 2007 August 14 ** ** The author disclaims copyright to this source code. In place of @@ -8370,19 +9913,20 @@ ** ************************************************************************* ** This file contains the C functions that implement a memory ** allocation subsystem for use by SQLite. ** -** $Id: mem1.c,v 1.13 2007/11/05 17:54:17 drh Exp $ +** $Id: mem1.c,v 1.14 2007/11/29 18:36:49 drh Exp $ */ /* ** This version of the memory allocator is the default. It is ** used when no other memory allocator is specified using compile-time ** macros. */ -#if !defined(SQLITE_MEMDEBUG) && !defined(SQLITE_MEMORY_SIZE) +#if !defined(SQLITE_MEMDEBUG) && !defined(SQLITE_MEMORY_SIZE) \ + && !defined(SQLITE_MMAP_HEAP_SIZE) /* ** We will eventually construct multiple memory allocation subsystems ** suitable for use in various contexts: ** @@ -8603,19 +10147,19 @@ ** ************************************************************************* ** This file contains the C functions that implement a memory ** allocation subsystem for use by SQLite. ** -** $Id: mem2.c,v 1.17 2007/11/05 17:54:17 drh Exp $ +** $Id: mem2.c,v 1.19 2008/01/22 21:30:53 drh Exp $ */ /* ** This version of the memory allocator is used only if the ** SQLITE_MEMDEBUG macro is defined and SQLITE_OMIT_MEMORY_ALLOCATION ** is not defined. */ -#if defined(SQLITE_MEMDEBUG) && !defined(SQLITE_MEMORY_SIZE) +#if defined(SQLITE_MEMDEBUG) /* ** We will eventually construct multiple memory allocation subsystems ** suitable for use in various contexts: ** @@ -8726,22 +10270,10 @@ */ int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */ char zTitle[100]; /* The title text */ /* - ** These values are used to simulate malloc failures. When - ** iFail is 1, simulate a malloc failures and reset the value - ** to iReset. - */ - int iFail; /* Decrement and fail malloc when this is 1 */ - int iReset; /* When malloc fails set iiFail to this value */ - int iFailCnt; /* Number of failures */ - int iBenignFailCnt; /* Number of benign failures */ - int iNextIsBenign; /* True if the next call to malloc may fail benignly */ - int iIsBenign; /* All malloc calls may fail benignly */ - - /* ** sqlite3MallocDisallow() increments the following counter. ** sqlite3MallocAllow() decrements it. */ int disallow; /* Do not allow memory allocation */ @@ -8845,21 +10377,10 @@ assert( pInt[p->iSize/sizeof(int)]==REARGUARD ); return p; } /* -** This routine is called once the first time a simulated memory -** failure occurs. The sole purpose of this routine is to provide -** a convenient place to set a debugger breakpoint when debugging -** errors related to malloc() failures. -*/ -static void sqlite3MemsysFailed(void){ - mem.iFailCnt = 0; - mem.iBenignFailCnt = 0; -} - -/* ** Allocate nByte bytes of memory. */ SQLITE_API void *sqlite3_malloc(int nByte){ struct MemBlockHdr *pHdr; void **pBt; @@ -8880,25 +10401,12 @@ }else{ mem.sizeCnt[nByte/8]++; } totalSize = nByte + sizeof(*pHdr) + sizeof(int) + mem.nBacktrace*sizeof(void*) + mem.nTitle; - if( mem.iFail>0 ){ - if( mem.iFail==1 ){ - p = 0; - mem.iFail = mem.iReset; - if( mem.iFailCnt==0 ){ - sqlite3MemsysFailed(); /* A place to set a breakpoint */ - } - mem.iFailCnt++; - if( mem.iNextIsBenign || mem.iIsBenign ){ - mem.iBenignFailCnt++; - } - }else{ - p = malloc(totalSize); - mem.iFail--; - } + if( sqlite3FaultStep(SQLITE_FAULTINJECTOR_MALLOC) ){ + p = 0; }else{ p = malloc(totalSize); if( p==0 ){ sqlite3MemsysAlarm(nByte); p = malloc(totalSize); @@ -8939,11 +10447,10 @@ } p = (void*)pInt; } sqlite3_mutex_leave(mem.mutex); } - mem.iNextIsBenign = 0; return p; } /* ** Free memory. @@ -9078,90 +10585,10 @@ fprintf(out, " >%3d: %d\n", NCSIZE*8, mem.sizeCnt[NCSIZE-1]); } fclose(out); } -/* -** This routine is used to simulate malloc failures. -** -** After calling this routine, there will be iFail successful -** memory allocations and then a failure. If iRepeat is 1 -** all subsequent memory allocations will fail. If iRepeat is -** 0, only a single allocation will fail. If iRepeat is negative -** then the previous setting for iRepeat is unchanged. -** -** Each call to this routine overrides the previous. To disable -** the simulated allocation failure mechanism, set iFail to -1. -** -** This routine returns the number of simulated failures that have -** occurred since the previous call. -*/ -SQLITE_API int sqlite3_memdebug_fail(int iFail, int iRepeat, int *piBenign){ - int n = mem.iFailCnt; - if( piBenign ){ - *piBenign = mem.iBenignFailCnt; - } - mem.iFail = iFail+1; - if( iRepeat>=0 ){ - mem.iReset = iRepeat; - } - mem.iFailCnt = 0; - mem.iBenignFailCnt = 0; - return n; -} - -SQLITE_API int sqlite3_memdebug_pending(){ - return (mem.iFail-1); -} - -/* -** The following three functions are used to indicate to the test -** infrastructure which malloc() calls may fail benignly without -** affecting functionality. This can happen when resizing hash tables -** (failing to resize a hash-table is a performance hit, but not an -** error) or sometimes during a rollback operation. -** -** If the argument is true, sqlite3MallocBenignFailure() indicates that the -** next call to allocate memory may fail benignly. -** -** If sqlite3MallocEnterBenignBlock() is called with a non-zero argument, -** then all memory allocations requested before the next call to -** sqlite3MallocLeaveBenignBlock() may fail benignly. -*/ -SQLITE_PRIVATE void sqlite3MallocBenignFailure(int isBenign){ - if( isBenign ){ - mem.iNextIsBenign = 1; - } -} -SQLITE_PRIVATE void sqlite3MallocEnterBenignBlock(int isBenign){ - if( isBenign ){ - mem.iIsBenign = 1; - } -} -SQLITE_PRIVATE void sqlite3MallocLeaveBenignBlock(){ - mem.iIsBenign = 0; -} - -/* -** The following two routines are used to assert that no memory -** allocations occur between one call and the next. The use of -** these routines does not change the computed results in any way. -** These routines are like asserts. -*/ -SQLITE_PRIVATE void sqlite3MallocDisallow(void){ - assert( mem.mutex!=0 ); - sqlite3_mutex_enter(mem.mutex); - mem.disallow++; - sqlite3_mutex_leave(mem.mutex); -} -SQLITE_PRIVATE void sqlite3MallocAllow(void){ - assert( mem.mutex ); - sqlite3_mutex_enter(mem.mutex); - assert( mem.disallow>0 ); - mem.disallow--; - sqlite3_mutex_leave(mem.mutex); -} #endif /* SQLITE_MEMDEBUG && !SQLITE_OMIT_MEMORY_ALLOCATION */ /************** End of mem2.c ************************************************/ /************** Begin file mem3.c ********************************************/ @@ -9185,18 +10612,22 @@ ** fixed memory pool is SQLITE_MEMORY_SIZE bytes. ** ** This version of the memory allocation subsystem is used if ** and only if SQLITE_MEMORY_SIZE is defined. ** -** $Id: mem3.c,v 1.6 2007/11/07 15:13:25 drh Exp $ +** $Id: mem3.c,v 1.8 2007/12/29 13:18:22 drh Exp $ */ /* ** This version of the memory allocator is used only when ** SQLITE_MEMORY_SIZE is defined. */ #if defined(SQLITE_MEMORY_SIZE) + +#ifdef SQLITE_MEMDEBUG +# error cannot define both SQLITE_MEMDEBUG and SQLITE_MEMORY_SIZE +#endif /* ** Maximum size (in Mem3Blocks) of a "small" chunk. */ #define MX_SMALL 10 @@ -9211,15 +10642,20 @@ ** A memory allocation (also called a "chunk") consists of two or ** more blocks where each block is 8 bytes. The first 8 bytes are ** a header that is not returned to the user. ** ** A chunk is two or more blocks that is either checked out or -** free. The first block has format u.hdr. u.hdr.size is the +** free. The first block has format u.hdr. u.hdr.size4x is 4 times the ** size of the allocation in blocks if the allocation is free. -** If the allocation is checked out, u.hdr.size is the negative -** of the size. Similarly, u.hdr.prevSize is the size of the -** immediately previous allocation. +** The u.hdr.size4x&1 bit is true if the chunk is checked out and +** false if the chunk is on the freelist. The u.hdr.size4x&2 bit +** is true if the previous chunk is checked out and false if the +** previous chunk is free. The u.hdr.prevSize field is the size of +** the previous chunk in blocks if the previous chunk is on the +** freelist. If the previous chunk is checked out, then +** u.hdr.prevSize can be part of the data for that chunk and should +** not be read or written. ** ** We often identify a chunk by its index in mem.aPool[]. When ** this is done, the chunk index refers to the second block of ** the chunk. In this way, the first chunk has an index of 1. ** A chunk index of 0 means "no such chunk" and is the equivalent @@ -9229,22 +10665,23 @@ ** two fields form a double-linked list of chunks of related sizes. ** Pointers to the head of the list are stored in mem.aiSmall[] ** for smaller chunks and mem.aiHash[] for larger chunks. ** ** The second block of a chunk is user data if the chunk is checked -** out. +** out. If a chunk is checked out, the user data may extend into +** the u.hdr.prevSize value of the following chunk. */ typedef struct Mem3Block Mem3Block; struct Mem3Block { union { struct { - int prevSize; /* Size of previous chunk in Mem3Block elements */ - int size; /* Size of current chunk in Mem3Block elements */ + u32 prevSize; /* Size of previous chunk in Mem3Block elements */ + u32 size4x; /* 4x the size of current chunk in Mem3Block elements */ } hdr; struct { - int next; /* Index in mem.aPool[] of next free chunk */ - int prev; /* Index in mem.aPool[] of previous free chunk */ + u32 next; /* Index in mem.aPool[] of next free chunk */ + u32 prev; /* Index in mem.aPool[] of previous free chunk */ } list; } u; }; /* @@ -9265,28 +10702,28 @@ sqlite3_mutex *mutex; /* ** The minimum amount of free space that we have seen. */ - int mnMaster; + u32 mnMaster; /* ** iMaster is the index of the master chunk. Most new allocations ** occur off of this chunk. szMaster is the size (in Mem3Blocks) ** of the current master. iMaster is 0 if there is not master chunk. ** The master chunk is not in either the aiHash[] or aiSmall[]. */ - int iMaster; - int szMaster; + u32 iMaster; + u32 szMaster; /* ** Array of lists of free blocks according to the block size ** for smaller chunks, or a hash on the block size for larger ** chunks. */ - int aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */ - int aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */ + u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */ + u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */ /* ** Memory available for allocation */ Mem3Block aPool[SQLITE_MEMORY_SIZE/sizeof(Mem3Block)+2]; @@ -9294,13 +10731,13 @@ /* ** Unlink the chunk at mem.aPool[i] from list it is currently ** on. *pRoot is the list that i is a member of. */ -static void memsys3UnlinkFromList(int i, int *pRoot){ - int next = mem.aPool[i].u.list.next; - int prev = mem.aPool[i].u.list.prev; +static void memsys3UnlinkFromList(u32 i, u32 *pRoot){ + u32 next = mem.aPool[i].u.list.next; + u32 prev = mem.aPool[i].u.list.prev; assert( sqlite3_mutex_held(mem.mutex) ); if( prev==0 ){ *pRoot = next; }else{ mem.aPool[prev].u.list.next = next; @@ -9314,14 +10751,16 @@ /* ** Unlink the chunk at index i from ** whatever list is currently a member of. */ -static void memsys3Unlink(int i){ - int size, hash; +static void memsys3Unlink(u32 i){ + u32 size, hash; assert( sqlite3_mutex_held(mem.mutex) ); - size = mem.aPool[i-1].u.hdr.size; + assert( (mem.aPool[i-1].u.hdr.size4x & 1)==0 ); + assert( i>=1 ); + size = mem.aPool[i-1].u.hdr.size4x/4; assert( size==mem.aPool[i+size-1].u.hdr.prevSize ); assert( size>=2 ); if( size <= MX_SMALL ){ memsys3UnlinkFromList(i, &mem.aiSmall[size-2]); }else{ @@ -9332,11 +10771,11 @@ /* ** Link the chunk at mem.aPool[i] so that is on the list rooted ** at *pRoot. */ -static void memsys3LinkIntoList(int i, int *pRoot){ +static void memsys3LinkIntoList(u32 i, u32 *pRoot){ assert( sqlite3_mutex_held(mem.mutex) ); mem.aPool[i].u.list.next = *pRoot; mem.aPool[i].u.list.prev = 0; if( *pRoot ){ mem.aPool[*pRoot].u.list.prev = i; @@ -9346,14 +10785,16 @@ /* ** Link the chunk at index i into either the appropriate ** small chunk list, or into the large chunk hash table. */ -static void memsys3Link(int i){ - int size, hash; +static void memsys3Link(u32 i){ + u32 size, hash; assert( sqlite3_mutex_held(mem.mutex) ); - size = mem.aPool[i-1].u.hdr.size; + assert( i>=1 ); + assert( (mem.aPool[i-1].u.hdr.size4x & 1)==0 ); + size = mem.aPool[i-1].u.hdr.size4x/4; assert( size==mem.aPool[i+size-1].u.hdr.prevSize ); assert( size>=2 ); if( size <= MX_SMALL ){ memsys3LinkIntoList(i, &mem.aiSmall[size-2]); }else{ @@ -9369,12 +10810,13 @@ ** this routine is called. */ static void memsys3Enter(void){ if( mem.mutex==0 ){ mem.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); - mem.aPool[0].u.hdr.size = SQLITE_MEMORY_SIZE/8; + mem.aPool[0].u.hdr.size4x = SQLITE_MEMORY_SIZE/2 + 2; mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.prevSize = SQLITE_MEMORY_SIZE/8; + mem.aPool[SQLITE_MEMORY_SIZE/8].u.hdr.size4x = 1; mem.iMaster = 1; mem.szMaster = SQLITE_MEMORY_SIZE/8; mem.mnMaster = mem.szMaster; } sqlite3_mutex_enter(mem.mutex); @@ -9442,25 +10884,29 @@ ** size returned omits the 8-byte header overhead. This only ** works for chunks that are currently checked out. */ static int memsys3Size(void *p){ Mem3Block *pBlock = (Mem3Block*)p; - assert( pBlock[-1].u.hdr.size<0 ); - return (-1-pBlock[-1].u.hdr.size)*8; + assert( (pBlock[-1].u.hdr.size4x&1)!=0 ); + return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; } /* ** Chunk i is a free chunk that has been unlinked. Adjust its ** size parameters for check-out and return a pointer to the ** user portion of the chunk. */ -static void *memsys3Checkout(int i, int nBlock){ +static void *memsys3Checkout(u32 i, int nBlock){ + u32 x; assert( sqlite3_mutex_held(mem.mutex) ); - assert( mem.aPool[i-1].u.hdr.size==nBlock ); + assert( i>=1 ); + assert( mem.aPool[i-1].u.hdr.size4x/4==nBlock ); assert( mem.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); - mem.aPool[i-1].u.hdr.size = -nBlock; - mem.aPool[i+nBlock-1].u.hdr.prevSize = -nBlock; + x = mem.aPool[i-1].u.hdr.size4x; + mem.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); + mem.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; + mem.aPool[i+nBlock-1].u.hdr.size4x |= 2; return &mem.aPool[i]; } /* ** Carve a piece off of the end of the mem.iMaster free chunk. @@ -9477,18 +10923,20 @@ mem.szMaster = 0; mem.mnMaster = 0; return p; }else{ /* Split the master block. Return the tail. */ - int newi; + u32 newi, x; newi = mem.iMaster + mem.szMaster - nBlock; assert( newi > mem.iMaster+1 ); - mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = -nBlock; - mem.aPool[newi-1].u.hdr.size = -nBlock; + mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = nBlock; + mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x |= 2; + mem.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; mem.szMaster -= nBlock; mem.aPool[newi-1].u.hdr.prevSize = mem.szMaster; - mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster; + x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2; + mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x; if( mem.szMaster < mem.mnMaster ){ mem.mnMaster = mem.szMaster; } return (void*)&mem.aPool[newi]; } @@ -9508,31 +10956,34 @@ ** linked into the hash tables. That is not the normal state of ** affairs, of course. The calling routine must link the master ** chunk before invoking this routine, then must unlink the (possibly ** changed) master chunk once this routine has finished. */ -static void memsys3Merge(int *pRoot){ - int iNext, prev, size, i; +static void memsys3Merge(u32 *pRoot){ + u32 iNext, prev, size, i, x; assert( sqlite3_mutex_held(mem.mutex) ); for(i=*pRoot; i>0; i=iNext){ iNext = mem.aPool[i].u.list.next; - size = mem.aPool[i-1].u.hdr.size; - assert( size>0 ); - if( mem.aPool[i-1].u.hdr.prevSize>0 ){ + size = mem.aPool[i-1].u.hdr.size4x; + assert( (size&1)==0 ); + if( (size&2)==0 ){ memsys3UnlinkFromList(i, pRoot); - prev = i - mem.aPool[i-1].u.hdr.prevSize; - assert( prev>=0 ); + assert( i > mem.aPool[i-1].u.hdr.prevSize ); + prev = i - mem.aPool[i-1].u.hdr.prevSize; if( prev==iNext ){ iNext = mem.aPool[prev].u.list.next; } memsys3Unlink(prev); - size = i + size - prev; - mem.aPool[prev-1].u.hdr.size = size; + size = i + size/4 - prev; + x = mem.aPool[prev-1].u.hdr.size4x & 2; + mem.aPool[prev-1].u.hdr.size4x = size*4 | x; mem.aPool[prev+size-1].u.hdr.prevSize = size; memsys3Link(prev); i = prev; + }else{ + size /= 4; } if( size>mem.szMaster ){ mem.iMaster = i; mem.szMaster = size; } @@ -9542,20 +10993,20 @@ /* ** Return a block of memory of at least nBytes in size. ** Return NULL if unable. */ static void *memsys3Malloc(int nByte){ - int i; + u32 i; int nBlock; int toFree; assert( sqlite3_mutex_held(mem.mutex) ); assert( sizeof(Mem3Block)==8 ); - if( nByte<=0 ){ + if( nByte<=12 ){ nBlock = 2; }else{ - nBlock = (nByte + 15)/8; + nBlock = (nByte + 11)/8; } assert( nBlock >= 2 ); /* STEP 1: ** Look for an entry of the correct size in either the small @@ -9569,11 +11020,11 @@ return memsys3Checkout(i, nBlock); } }else{ int hash = nBlock % N_HASH; for(i=mem.aiHash[hash]; i>0; i=mem.aPool[i].u.list.next){ - if( mem.aPool[i-1].u.hdr.size==nBlock ){ + if( mem.aPool[i-1].u.hdr.size4x/4==nBlock ){ memsys3UnlinkFromList(i, &mem.aiHash[hash]); return memsys3Checkout(i, nBlock); } } } @@ -9623,35 +11074,38 @@ ** Free an outstanding memory allocation. */ void memsys3Free(void *pOld){ Mem3Block *p = (Mem3Block*)pOld; int i; - int size; + u32 size, x; assert( sqlite3_mutex_held(mem.mutex) ); assert( p>mem.aPool && p<&mem.aPool[SQLITE_MEMORY_SIZE/8] ); i = p - mem.aPool; - size = -mem.aPool[i-1].u.hdr.size; - assert( size>=2 ); - assert( mem.aPool[i+size-1].u.hdr.prevSize==-size ); - mem.aPool[i-1].u.hdr.size = size; + assert( (mem.aPool[i-1].u.hdr.size4x&1)==1 ); + size = mem.aPool[i-1].u.hdr.size4x/4; + assert( i+size<=SQLITE_MEMORY_SIZE/8+1 ); + mem.aPool[i-1].u.hdr.size4x &= ~1; mem.aPool[i+size-1].u.hdr.prevSize = size; + mem.aPool[i+size-1].u.hdr.size4x &= ~2; memsys3Link(i); /* Try to expand the master using the newly freed chunk */ if( mem.iMaster ){ - while( mem.aPool[mem.iMaster-1].u.hdr.prevSize>0 ){ + while( (mem.aPool[mem.iMaster-1].u.hdr.size4x&2)==0 ){ size = mem.aPool[mem.iMaster-1].u.hdr.prevSize; mem.iMaster -= size; mem.szMaster += size; memsys3Unlink(mem.iMaster); - mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster; + x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2; + mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x; mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster; } - while( mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size>0 ){ + x = mem.aPool[mem.iMaster-1].u.hdr.size4x & 2; + while( (mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x&1)==0 ){ memsys3Unlink(mem.iMaster+mem.szMaster); - mem.szMaster += mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size; - mem.aPool[mem.iMaster-1].u.hdr.size = mem.szMaster; + mem.szMaster += mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.size4x/4; + mem.aPool[mem.iMaster-1].u.hdr.size4x = mem.szMaster*4 | x; mem.aPool[mem.iMaster+mem.szMaster-1].u.hdr.prevSize = mem.szMaster; } } } @@ -9718,11 +11172,12 @@ ** allocations into that log. */ SQLITE_API void sqlite3_memdebug_dump(const char *zFilename){ #ifdef SQLITE_DEBUG FILE *out; - int i, j, size; + int i, j; + u32 size; if( zFilename==0 || zFilename[0]==0 ){ out = stdout; }else{ out = fopen(zFilename, "w"); if( out==0 ){ @@ -9731,43 +11186,49 @@ return; } } memsys3Enter(); fprintf(out, "CHUNKS:\n"); - for(i=1; i<=SQLITE_MEMORY_SIZE/8; i+=size){ - size = mem.aPool[i-1].u.hdr.size; - if( size>=-1 && size<=1 ){ + for(i=1; i<=SQLITE_MEMORY_SIZE/8; i+=size/4){ + size = mem.aPool[i-1].u.hdr.size4x; + if( size/4<=1 ){ fprintf(out, "%p size error\n", &mem.aPool[i]); assert( 0 ); break; } - if( mem.aPool[i+(size<0?-size:size)-1].u.hdr.prevSize!=size ){ + if( (size&1)==0 && mem.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){ fprintf(out, "%p tail size does not match\n", &mem.aPool[i]); assert( 0 ); break; } - if( size<0 ){ - size = -size; - fprintf(out, "%p %6d bytes checked out\n", &mem.aPool[i], size*8-8); - }else{ - fprintf(out, "%p %6d bytes free%s\n", &mem.aPool[i], size*8-8, + if( ((mem.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){ + fprintf(out, "%p tail checkout bit is incorrect\n", &mem.aPool[i]); + assert( 0 ); + break; + } + if( size&1 ){ + fprintf(out, "%p %6d bytes checked out\n", &mem.aPool[i], (size/4)*8-8); + }else{ + fprintf(out, "%p %6d bytes free%s\n", &mem.aPool[i], (size/4)*8-8, i==mem.iMaster ? " **master**" : ""); } } for(i=0; i<MX_SMALL-1; i++){ if( mem.aiSmall[i]==0 ) continue; fprintf(out, "small(%2d):", i); for(j = mem.aiSmall[i]; j>0; j=mem.aPool[j].u.list.next){ - fprintf(out, " %p(%d)", &mem.aPool[j], mem.aPool[j-1].u.hdr.size*8-8); + fprintf(out, " %p(%d)", &mem.aPool[j], + (mem.aPool[j-1].u.hdr.size4x/4)*8-8); } fprintf(out, "\n"); } for(i=0; i<N_HASH; i++){ if( mem.aiHash[i]==0 ) continue; fprintf(out, "hash(%2d):", i); for(j = mem.aiHash[i]; j>0; j=mem.aPool[j].u.list.next){ - fprintf(out, " %p(%d)", &mem.aPool[j], mem.aPool[j-1].u.hdr.size*8-8); + fprintf(out, " %p(%d)", &mem.aPool[j], + (mem.aPool[j-1].u.hdr.size4x/4)*8-8); } fprintf(out, "\n"); } fprintf(out, "master=%d\n", mem.iMaster); fprintf(out, "nowUsed=%d\n", SQLITE_MEMORY_SIZE - mem.szMaster*8); @@ -9925,11 +11386,11 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for OS/2 ** -** $Id: mutex_os2.c,v 1.3 2007/10/02 19:56:04 pweilbacher Exp $ +** $Id: mutex_os2.c,v 1.4 2007/12/30 23:29:07 pweilbacher Exp $ */ /* ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined. ** See the mutex.h file for details. @@ -10016,12 +11477,12 @@ while( !isInit ) { static long lock = 0; DosEnterCritSec(); lock++; if( lock == 1 ) { - DosExitCritSec(); int i; + DosExitCritSec(); for(i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++) { staticMutexes[i].mutexName = (PSZ)malloc(mutex_name_len + 1); sqlite3_snprintf(mutex_name_len + 1, /* one more for the number */ staticMutexes[i].mutexName, "%s%1d", mutex_name, i); DosCreateMutexSem(staticMutexes[i].mutexName, @@ -10163,11 +11624,11 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the C functions that implement mutexes for pthreads ** -** $Id: mutex_unix.c,v 1.2 2007/08/28 22:24:35 drh Exp $ +** $Id: mutex_unix.c,v 1.5 2007/11/28 14:04:57 drh Exp $ */ /* ** The code in this file is only used if we are compiling threadsafe ** under unix with pthreads. @@ -10176,10 +11637,11 @@ ** supports recursive mutexes. */ #ifdef SQLITE_MUTEX_PTHREADS #include <pthread.h> + /* ** Each recursive mutex is an instance of the following structure. */ struct sqlite3_mutex { @@ -10244,15 +11706,22 @@ sqlite3_mutex *p; switch( iType ){ case SQLITE_MUTEX_RECURSIVE: { p = sqlite3MallocZero( sizeof(*p) ); if( p ){ +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, we will have to + ** build our own. See below. */ + pthread_mutex_init(&p->mutex, 0); +#else + /* Use a recursive mutex if it is available */ pthread_mutexattr_t recursiveAttr; pthread_mutexattr_init(&recursiveAttr); pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&p->mutex, &recursiveAttr); pthread_mutexattr_destroy(&recursiveAttr); +#endif p->id = iType; } break; } case SQLITE_MUTEX_FAST: { @@ -10300,13 +11769,41 @@ ** more than once, the behavior is undefined. */ SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){ assert( p ); assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that pthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + pthread_t self = pthread_self(); + if( p->nRef>0 && pthread_equal(p->owner, self) ){ + p->nRef++; + }else{ + pthread_mutex_lock(&p->mutex); + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ pthread_mutex_lock(&p->mutex); p->owner = pthread_self(); p->nRef++; +#endif + #ifdef SQLITE_DEBUG if( p->trace ){ printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif @@ -10313,22 +11810,53 @@ } SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){ int rc; assert( p ); assert( p->id==SQLITE_MUTEX_RECURSIVE || sqlite3_mutex_notheld(p) ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + /* If recursive mutexes are not available, then we have to grow + ** our own. This implementation assumes that pthread_equal() + ** is atomic - that it cannot be deceived into thinking self + ** and p->owner are equal if p->owner changes between two values + ** that are not equal to self while the comparison is taking place. + ** This implementation also assumes a coherent cache - that + ** separate processes cannot read different values from the same + ** address at the same time. If either of these two conditions + ** are not met, then the mutexes will fail and problems will result. + */ + { + pthread_t self = pthread_self(); + if( p->nRef>0 && pthread_equal(p->owner, self) ){ + p->nRef++; + rc = SQLITE_OK; + }else if( pthread_mutex_lock(&p->mutex)==0 ){ + assert( p->nRef==0 ); + p->owner = self; + p->nRef = 1; + rc = SQLITE_OK; + }else{ + rc = SQLITE_BUSY; + } + } +#else + /* Use the built-in recursive mutexes if they are available. + */ if( pthread_mutex_trylock(&p->mutex)==0 ){ p->owner = pthread_self(); p->nRef++; rc = SQLITE_OK; -#ifdef SQLITE_DEBUG - if( p->trace ){ - printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); - } -#endif }else{ rc = SQLITE_BUSY; } +#endif + +#ifdef SQLITE_DEBUG + if( rc==SQLITE_OK && p->trace ){ + printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); + } +#endif return rc; } /* ** The sqlite3_mutex_leave() routine exits a mutex that was @@ -10339,16 +11867,24 @@ SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){ assert( p ); assert( sqlite3_mutex_held(p) ); p->nRef--; assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); + +#ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX + if( p->nRef==0 ){ + pthread_mutex_unlock(&p->mutex); + } +#else + pthread_mutex_unlock(&p->mutex); +#endif + #ifdef SQLITE_DEBUG if( p->trace ){ printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); } #endif - pthread_mutex_unlock(&p->mutex); } /* ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are ** intended for use only inside assert() statements. On some platforms, @@ -10910,10 +12446,11 @@ NULL pointers replaced by SQL NULL. %Q */ #define etTOKEN 13 /* a pointer to a Token structure */ #define etSRCLIST 14 /* a pointer to a SrcList */ #define etPOINTER 15 /* The %p conversion */ #define etSQLESCAPE3 16 /* %w -> Strings with '\"' doubled */ +#define etORDINAL 17 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */ /* ** An "etByte" is an 8-bit unsigned value. */ @@ -10969,10 +12506,11 @@ { 'n', 0, 0, etSIZE, 0, 0 }, { '%', 0, 0, etPERCENT, 0, 0 }, { 'p', 16, 0, etPOINTER, 0, 1 }, { 'T', 0, 2, etTOKEN, 0, 0 }, { 'S', 0, 2, etSRCLIST, 0, 0 }, + { 'r', 10, 3, etORDINAL, 0, 0 }, }; #define etNINFO (sizeof(fmtinfo)/sizeof(fmtinfo[0])) /* ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point @@ -11001,10 +12539,24 @@ digit += '0'; *val = (*val - d)*10.0; return digit; } #endif /* SQLITE_OMIT_FLOATING_POINT */ + +/* +** Append N space characters to the given string buffer. +*/ +static void appendSpace(StrAccum *pAccum, int N){ + static const char zSpaces[] = " "; + while( N>=sizeof(zSpaces)-1 ){ + sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1); + N -= sizeof(zSpaces)-1; + } + if( N>0 ){ + sqlite3StrAccumAppend(pAccum, zSpaces, N); + } +} /* ** On machines with a small stack size, you can redefine the ** SQLITE_PRINT_BUF_SIZE to be less than 350. But beware - for ** smaller values some %f conversions may go into an infinite loop. @@ -11039,23 +12591,21 @@ ** ** Note that the order in which automatic variables are declared below ** seems to make a big difference in determining how fast this beast ** will run. */ -static int vxprintf( - void (*func)(void*,const char*,int), /* Consumer of text */ - void *arg, /* First argument to the consumer */ +static void vxprintf( + StrAccum *pAccum, /* Accumulate results here */ int useExtended, /* Allow extended %-conversions */ const char *fmt, /* Format string */ va_list ap /* arguments */ ){ int c; /* Next character in the format string */ char *bufpt; /* Pointer to the conversion buffer */ int precision; /* Precision of the current field */ int length; /* Length of the field */ int idx; /* A general purpose loop counter */ - int count; /* Total number of characters output */ int width; /* Width of the current field */ etByte flag_leftjustify; /* True if "-" flag is present */ etByte flag_plussign; /* True if "+" flag is present */ etByte flag_blanksign; /* True if " " flag is present */ etByte flag_alternateform; /* True if "#" flag is present */ @@ -11070,39 +12620,33 @@ char buf[etBUFSIZE]; /* Conversion buffer */ char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ etByte errorflag = 0; /* True if an error is encountered */ etByte xtype; /* Conversion paradigm */ char *zExtra; /* Extra memory used for etTCLESCAPE conversions */ - static const char spaces[] = - " "; -#define etSPACESIZE (sizeof(spaces)-1) #ifndef SQLITE_OMIT_FLOATING_POINT int exp, e2; /* exponent of real numbers */ double rounder; /* Used for rounding floating point values */ etByte flag_dp; /* True if decimal point should be shown */ etByte flag_rtz; /* True if trailing zeros should be removed */ etByte flag_exp; /* True to force display of the exponent */ int nsd; /* Number of significant digits returned */ #endif - func(arg,"",0); - count = length = 0; + length = 0; bufpt = 0; for(; (c=(*fmt))!=0; ++fmt){ if( c!='%' ){ int amt; bufpt = (char *)fmt; amt = 1; while( (c=(*++fmt))!='%' && c!=0 ) amt++; - (*func)(arg,bufpt,amt); - count += amt; + sqlite3StrAccumAppend(pAccum, bufpt, amt); if( c==0 ) break; } if( (c=(*++fmt))==0 ){ errorflag = 1; - (*func)(arg,"%",1); - count++; + sqlite3StrAccumAppend(pAccum, "%", 1); break; } /* Find out what flags are present */ flag_leftjustify = flag_plussign = flag_blanksign = flag_alternateform = flag_altform2 = flag_zeropad = 0; @@ -11172,18 +12716,18 @@ if( c==fmtinfo[idx].fmttype ){ infop = &fmtinfo[idx]; if( useExtended || (infop->flags & FLAG_INTERN)==0 ){ xtype = infop->type; }else{ - return -1; + return; } break; } } zExtra = 0; if( infop==0 ){ - return -1; + return; } /* Limit the precision to prevent overflowing buf[] during conversion */ if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){ @@ -11214,10 +12758,11 @@ switch( xtype ){ case etPOINTER: flag_longlong = sizeof(char*)==sizeof(i64); flag_long = sizeof(char*)==sizeof(long int); /* Fall through into the next case */ + case etORDINAL: case etRADIX: if( infop->flags & FLAG_SIGNED ){ i64 v; if( flag_longlong ) v = va_arg(ap,i64); else if( flag_long ) v = va_arg(ap,long int); @@ -11240,10 +12785,20 @@ if( longvalue==0 ) flag_alternateform = 0; if( flag_zeropad && precision<width-(prefix!=0) ){ precision = width-(prefix!=0); } bufpt = &buf[etBUFSIZE-1]; + if( xtype==etORDINAL ){ + static const char zOrd[] = "thstndrd"; + int x = longvalue % 10; + if( x>=4 || (longvalue/10)%10==1 ){ + x = 0; + } + buf[etBUFSIZE-3] = zOrd[x*2]; + buf[etBUFSIZE-2] = zOrd[x*2+1]; + bufpt -= 2; + } { register const char *cset; /* Use registers for speed */ register int base; cset = &aDigits[infop->charset]; base = infop->base; @@ -11417,11 +12972,11 @@ length = width; } #endif break; case etSIZE: - *(va_arg(ap,int*)) = count; + *(va_arg(ap,int*)) = pAccum->nChar; length = width = 0; break; case etPERCENT: buf[0] = '%'; bufpt = buf; @@ -11463,11 +13018,11 @@ } needQuote = !isnull && xtype==etSQLESCAPE2; n += i + 1 + needQuote*2; if( n>etBUFSIZE ){ bufpt = zExtra = sqlite3_malloc( n ); - if( bufpt==0 ) return -1; + if( bufpt==0 ) return; }else{ bufpt = buf; } j = 0; if( needQuote ) bufpt[j++] = q; @@ -11483,11 +13038,11 @@ break; } case etTOKEN: { Token *pToken = va_arg(ap, Token*); if( pToken && pToken->z ){ - (*func)(arg, (char*)pToken->z, pToken->n); + sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n); } length = width = 0; break; } case etSRCLIST: { @@ -11494,14 +13049,14 @@ SrcList *pSrc = va_arg(ap, SrcList*); int k = va_arg(ap, int); struct SrcList_item *pItem = &pSrc->a[k]; assert( k>=0 && k<pSrc->nSrc ); if( pItem->zDatabase && pItem->zDatabase[0] ){ - (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase)); - (*func)(arg, ".", 1); - } - (*func)(arg, pItem->zName, strlen(pItem->zName)); + sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1); + sqlite3StrAccumAppend(pAccum, ".", 1); + } + sqlite3StrAccumAppend(pAccum, pItem->zName, -1); length = width = 0; break; } }/* End switch over the format type */ /* @@ -11511,158 +13066,130 @@ */ if( !flag_leftjustify ){ register int nspace; nspace = width-length; if( nspace>0 ){ - count += nspace; - while( nspace>=etSPACESIZE ){ - (*func)(arg,spaces,etSPACESIZE); - nspace -= etSPACESIZE; - } - if( nspace>0 ) (*func)(arg,spaces,nspace); + appendSpace(pAccum, nspace); } } if( length>0 ){ - (*func)(arg,bufpt,length); - count += length; + sqlite3StrAccumAppend(pAccum, bufpt, length); } if( flag_leftjustify ){ register int nspace; nspace = width-length; if( nspace>0 ){ - count += nspace; - while( nspace>=etSPACESIZE ){ - (*func)(arg,spaces,etSPACESIZE); - nspace -= etSPACESIZE; - } - if( nspace>0 ) (*func)(arg,spaces,nspace); + appendSpace(pAccum, nspace); } } if( zExtra ){ sqlite3_free(zExtra); } }/* End for loop over the format string */ - return errorflag ? -1 : count; } /* End of function */ - -/* This structure is used to store state information about the -** write to memory that is currently in progress. -*/ -struct sgMprintf { - char *zBase; /* A base allocation */ - char *zText; /* The string collected so far */ - int nChar; /* Length of the string so far */ - int nTotal; /* Output size if unconstrained */ - int nAlloc; /* Amount of space allocated in zText */ - void *(*xRealloc)(void*,int); /* Function used to realloc memory */ - int iMallocFailed; /* True if xRealloc() has failed */ -}; - -/* -** This function implements the callback from vxprintf. -** -** This routine add nNewChar characters of text in zNewText to -** the sgMprintf structure pointed to by "arg". -*/ -static void mout(void *arg, const char *zNewText, int nNewChar){ - struct sgMprintf *pM = (struct sgMprintf*)arg; - if( pM->iMallocFailed ) return; - pM->nTotal += nNewChar; - if( pM->zText ){ - if( pM->nChar + nNewChar + 1 > pM->nAlloc ){ - if( pM->xRealloc==0 ){ - nNewChar = pM->nAlloc - pM->nChar - 1; - }else{ - int nAlloc = pM->nChar + nNewChar*2 + 1; - if( pM->zText==pM->zBase ){ - pM->zText = pM->xRealloc(0, nAlloc); - if( pM->zText==0 ){ - pM->nAlloc = 0; - pM->iMallocFailed = 1; - return; - }else if( pM->nChar ){ - memcpy(pM->zText, pM->zBase, pM->nChar); - } - }else{ - char *zNew; - zNew = pM->xRealloc(pM->zText, nAlloc); - if( zNew ){ - pM->zText = zNew; - }else{ - pM->iMallocFailed = 1; - pM->xRealloc(pM->zText, 0); - pM->zText = 0; - pM->nAlloc = 0; - return; - } - } - pM->nAlloc = nAlloc; - } - } - if( nNewChar>0 ){ - memcpy(&pM->zText[pM->nChar], zNewText, nNewChar); - pM->nChar += nNewChar; - } - pM->zText[pM->nChar] = 0; - } -} - -/* -** This routine is a wrapper around xprintf() that invokes mout() as -** the consumer. -*/ -static char *base_vprintf( - void *(*xRealloc)(void*, int), /* realloc() function. May be NULL */ - int useInternal, /* Use internal %-conversions if true */ - char *zInitBuf, /* Initially write here, before mallocing */ - int nInitBuf, /* Size of zInitBuf[] */ - const char *zFormat, /* format string */ - va_list ap /* arguments */ -){ - struct sgMprintf sM; - sM.zBase = sM.zText = zInitBuf; - sM.nChar = sM.nTotal = 0; - sM.nAlloc = nInitBuf; - sM.xRealloc = xRealloc; - sM.iMallocFailed = 0; - vxprintf(mout, &sM, useInternal, zFormat, ap); - assert(sM.iMallocFailed==0 || sM.zText==0); - if( xRealloc && !sM.iMallocFailed ){ - if( sM.zText==sM.zBase ){ - sM.zText = xRealloc(0, sM.nChar+1); - if( sM.zText ){ - memcpy(sM.zText, sM.zBase, sM.nChar+1); - } - }else if( sM.nAlloc>sM.nChar+10 ){ - char *zNew; - sqlite3MallocBenignFailure(1); - zNew = xRealloc(sM.zText, sM.nChar+1); +/* +** Append N bytes of text from z to the StrAccum object. +*/ +SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){ + if( p->tooBig | p->mallocFailed ){ + return; + } + if( N<0 ){ + N = strlen(z); + } + if( N==0 ){ + return; + } + if( p->nChar+N >= p->nAlloc ){ + char *zNew; + if( !p->useMalloc ){ + p->tooBig = 1; + N = p->nAlloc - p->nChar - 1; + if( N<=0 ){ + return; + } + }else{ + p->nAlloc += p->nAlloc + N + 1; + if( p->nAlloc > SQLITE_MAX_LENGTH ){ + p->nAlloc = SQLITE_MAX_LENGTH; + if( p->nChar+N >= p->nAlloc ){ + sqlite3StrAccumReset(p); + p->tooBig = 1; + return; + } + } + zNew = sqlite3_malloc( p->nAlloc ); if( zNew ){ - sM.zText = zNew; - } - } - } - return sM.zText; -} - -/* -** Realloc that is a real function, not a macro. -*/ -static void *printf_realloc(void *old, int size){ - return sqlite3_realloc(old, size); + memcpy(zNew, p->zText, p->nChar); + sqlite3StrAccumReset(p); + p->zText = zNew; + }else{ + p->mallocFailed = 1; + sqlite3StrAccumReset(p); + return; + } + } + } + memcpy(&p->zText[p->nChar], z, N); + p->nChar += N; +} + +/* +** Finish off a string by making sure it is zero-terminated. +** Return a pointer to the resulting string. Return a NULL +** pointer if any kind of error was encountered. +*/ +SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){ + if( p->zText ){ + p->zText[p->nChar] = 0; + if( p->useMalloc && p->zText==p->zBase ){ + p->zText = sqlite3_malloc( p->nChar+1 ); + if( p->zText ){ + memcpy(p->zText, p->zBase, p->nChar+1); + }else{ + p->mallocFailed = 1; + } + } + } + return p->zText; +} + +/* +** Reset an StrAccum string. Reclaim all malloced memory. +*/ +SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){ + if( p->zText!=p->zBase ){ + sqlite3_free(p->zText); + p->zText = 0; + } +} + +/* +** Initialize a string accumulator +*/ +static void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n){ + p->zText = p->zBase = zBase; + p->nChar = 0; + p->nAlloc = n; + p->useMalloc = 1; + p->tooBig = 0; + p->mallocFailed = 0; } /* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */ SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){ char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; - z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap); - if( z==0 && db!=0 ){ + StrAccum acc; + sqlite3StrAccumInit(&acc, zBase, sizeof(zBase)); + vxprintf(&acc, 1, zFormat, ap); + z = sqlite3StrAccumFinish(&acc); + if( acc.mallocFailed && db ){ db->mallocFailed = 1; } return z; } @@ -11671,27 +13198,28 @@ ** %-conversion extensions. */ SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){ va_list ap; char *z; - char zBase[SQLITE_PRINT_BUF_SIZE]; va_start(ap, zFormat); - z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap); - va_end(ap); - if( z==0 && db!=0 ){ - db->mallocFailed = 1; - } + z = sqlite3VMPrintf(db, zFormat, ap); + va_end(ap); return z; } /* ** Print into memory obtained from sqlite3_malloc(). Omit the internal ** %-conversion extensions. */ SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){ + char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; - return base_vprintf(sqlite3_realloc, 0, zBase, sizeof(zBase), zFormat, ap); + StrAccum acc; + sqlite3StrAccumInit(&acc, zBase, sizeof(zBase)); + vxprintf(&acc, 0, zFormat, ap); + z = sqlite3StrAccumFinish(&acc); + return z; } /* ** Print into memory obtained from sqlite3_malloc()(). Omit the internal ** %-conversion extensions. @@ -11712,18 +13240,21 @@ ** specified by some locales. */ SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ char *z; va_list ap; + StrAccum acc; if( n<=0 ){ return zBuf; } - zBuf[0] = 0; + sqlite3StrAccumInit(&acc, zBuf, n); + acc.useMalloc = 0; va_start(ap,zFormat); - z = base_vprintf(0, 0, zBuf, n, zFormat, ap); + vxprintf(&acc, 0, zFormat, ap); va_end(ap); + z = sqlite3StrAccumFinish(&acc); return z; } #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG) /* @@ -11730,16 +13261,19 @@ ** A version of printf() that understands %lld. Used for debugging. ** The printf() built into some versions of windows does not understand %lld ** and segfaults if you give it a long long int. */ SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){ - extern int getpid(void); va_list ap; + StrAccum acc; char zBuf[500]; - va_start(ap, zFormat); - base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap); + sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf)); + acc.useMalloc = 0; + va_start(ap,zFormat); + vxprintf(&acc, 0, zFormat, ap); va_end(ap); + sqlite3StrAccumFinish(&acc); fprintf(stdout,"%s", zBuf); fflush(stdout); } #endif @@ -11760,13 +13294,22 @@ ** generator (PRNG) for SQLite. ** ** Random numbers are used by some of the database backends in order ** to generate random integer keys for tables or random filenames. ** -** $Id: random.c,v 1.20 2007/08/21 13:51:23 drh Exp $ -*/ - +** $Id: random.c,v 1.21 2008/01/16 17:46:38 drh Exp $ +*/ + + +/* All threads share a single random number generator. +** This structure is the current state of the generator. +*/ +static struct sqlite3PrngType { + unsigned char isInit; /* True if initialized */ + unsigned char i, j; /* State variables */ + unsigned char s[256]; /* State variables */ +} sqlite3Prng; /* ** Get a single 8-bit random value from the RC4 PRNG. The Mutex ** must be held while executing this routine. ** @@ -11783,18 +13326,10 @@ ** randomness any more. But we will leave this code in all the same. */ static int randomByte(void){ unsigned char t; - /* All threads share a single random number generator. - ** This structure is the current state of the generator. - */ - static struct { - unsigned char isInit; /* True if initialized */ - unsigned char i, j; /* State variables */ - unsigned char s[256]; /* State variables */ - } prng; /* Initialize the state of the random number generator once, ** the first time this routine is called. The seed value does ** not need to contain a lot of randomness since we are not ** trying to do secure encryption or anything like that... @@ -11801,37 +13336,37 @@ ** ** Nothing in this file or anywhere else in SQLite does any kind of ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random ** number generator) not as an encryption device. */ - if( !prng.isInit ){ + if( !sqlite3Prng.isInit ){ int i; char k[256]; - prng.j = 0; - prng.i = 0; + sqlite3Prng.j = 0; + sqlite3Prng.i = 0; sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k); for(i=0; i<256; i++){ - prng.s[i] = i; + sqlite3Prng.s[i] = i; } for(i=0; i<256; i++){ - prng.j += prng.s[i] + k[i]; - t = prng.s[prng.j]; - prng.s[prng.j] = prng.s[i]; - prng.s[i] = t; - } - prng.isInit = 1; + sqlite3Prng.j += sqlite3Prng.s[i] + k[i]; + t = sqlite3Prng.s[sqlite3Prng.j]; + sqlite3Prng.s[sqlite3Prng.j] = sqlite3Prng.s[i]; + sqlite3Prng.s[i] = t; + } + sqlite3Prng.isInit = 1; } /* Generate and return single random byte */ - prng.i++; - t = prng.s[prng.i]; - prng.j += t; - prng.s[prng.i] = prng.s[prng.j]; - prng.s[prng.j] = t; - t += prng.s[prng.i]; - return prng.s[t]; + sqlite3Prng.i++; + t = sqlite3Prng.s[sqlite3Prng.i]; + sqlite3Prng.j += t; + sqlite3Prng.s[sqlite3Prng.i] = sqlite3Prng.s[sqlite3Prng.j]; + sqlite3Prng.s[sqlite3Prng.j] = t; + t += sqlite3Prng.s[sqlite3Prng.i]; + return sqlite3Prng.s[t]; } /* ** Return N random bytes. */ @@ -11845,10 +13380,27 @@ while( N-- ){ *(zBuf++) = randomByte(); } sqlite3_mutex_leave(mutex); } + +#ifdef SQLITE_TEST +/* +** For testing purposes, we sometimes want to preserve the state of +** PRNG and restore the PRNG to its saved state at a later time. +*/ +static struct sqlite3PrngType sqlite3SavedPrng; +SQLITE_PRIVATE void sqlite3SavePrngState(void){ + memcpy(&sqlite3SavedPrng, &sqlite3Prng, sizeof(sqlite3Prng)); +} +SQLITE_PRIVATE void sqlite3RestorePrngState(void){ + memcpy(&sqlite3Prng, &sqlite3SavedPrng, sizeof(sqlite3Prng)); +} +SQLITE_PRIVATE void sqlite3ResetPrngState(void){ + sqlite3Prng.isInit = 0; +} +#endif /* SQLITE_TEST */ /************** End of random.c **********************************************/ /************** Begin file utf.c *********************************************/ /* ** 2004 April 13 @@ -12014,18 +13566,17 @@ FuncDef *pDef; /* Used only when flags==MEM_Agg */ } u; double r; /* Real value */ sqlite3 *db; /* The associated database connection */ char *z; /* String or BLOB value */ - int n; /* Number of characters in string value, including '\0' */ + int n; /* Number of characters in string value, excluding '\0' */ u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */ u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */ u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */ void (*xDel)(void *); /* If not null, call this function to delete Mem.z */ char zShort[NBFS]; /* Space for short strings */ }; -typedef struct Mem Mem; /* One or more of the following flags are set to indicate the validOK ** representations of the value stored in the Mem struct. ** ** If the MEM_Null flag is set, then the value is an SQL NULL value. @@ -12080,11 +13631,10 @@ struct AuxData { void *pAux; /* Aux data for the i-th argument */ void (*xDelete)(void *); /* Destructor for the aux data */ } apAux[1]; /* One slot for each function argument */ }; -typedef struct VdbeFunc VdbeFunc; /* ** The "context" argument for a installable function. A pointer to an ** instance of this structure is the first argument to the routines used ** implement the SQL functions. @@ -12182,12 +13732,10 @@ int nOpAlloc; /* Number of slots allocated for aOp[] */ Op *aOp; /* Space to hold the virtual machine's program */ int nLabel; /* Number of labels used */ int nLabelAlloc; /* Number of slots allocated in aLabel[] */ int *aLabel; /* Space to hold the labels */ - Mem *aStack; /* The operand stack, except string values */ - Mem *pTos; /* Top entry in the operand stack */ Mem **apArg; /* Arguments to currently executing user function */ Mem *aColName; /* Column names to return */ int nCursor; /* Number of slots in apCsr[] */ Cursor **apCsr; /* One element of this array for each open cursor */ int nVar; /* Number of entries in aVar[] */ @@ -12210,13 +13758,12 @@ int inTempTrans; /* True if temp database is transactioned */ int returnStack[25]; /* Return address stack for OP_Gosub & OP_Return */ int returnDepth; /* Next unused element in returnStack[] */ int nResColumn; /* Number of columns in one row of the result set */ char **azResColumn; /* Values for one row of result */ - int popStack; /* Pop the stack this much on entry to VdbeExec() */ char *zErrMsg; /* Error message written here */ - u8 resOnStack; /* True if there are result values on the stack */ + Mem *pResultSet; /* Pointer to an array of results */ u8 explain; /* True if EXPLAIN present on SQL command */ u8 changeCntOn; /* True to update the change-counter */ u8 aborted; /* True if ROLLBACK in another VM causes an abort */ u8 expired; /* True if the VM needs to be recompiled */ u8 minWriteFileFormat; /* Minimum file format for writable database files */ @@ -12271,11 +13818,11 @@ SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*); SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int); SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*); SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int); -SQLITE_PRIVATE int sqlite3VdbeMemMove(Mem*, Mem*); +SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*); SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*)); SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64); SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double); SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*); @@ -12291,14 +13838,14 @@ SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*); SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*); SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p); SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*); SQLITE_PRIVATE const char *sqlite3OpcodeName(int); - -#ifndef NDEBUG -SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem*); -SQLITE_PRIVATE int sqlite3VdbeOpcodeNoPush(u8); +SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int); + +#ifndef NDEBUG +SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem*); #endif SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8); #ifdef SQLITE_DEBUG SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*); SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf); @@ -12841,11 +14388,11 @@ ** Utility functions used throughout sqlite. ** ** This file contains functions for allocating memory, comparing ** strings, and stuff like that. ** -** $Id: util.c,v 1.213 2007/10/23 15:39:45 drh Exp $ +** $Id: util.c,v 1.216 2008/01/23 03:03:05 drh Exp $ */ /* ** Set the most recent error code and error string for the sqlite @@ -13268,29 +14815,10 @@ *pValue = (int)v; return 1; } /* -** Check to make sure we have a valid db pointer. This test is not -** foolproof but it does provide some measure of protection against -** misuse of the interface such as passing in db pointers that are -** NULL or which have been previously closed. If this routine returns -** TRUE it means that the db pointer is invalid and should not be -** dereferenced for any reason. The calling function should invoke -** SQLITE_MISUSE immediately. -*/ -SQLITE_PRIVATE int sqlite3SafetyCheck(sqlite3 *db){ - int magic; - if( db==0 ) return 1; - magic = db->magic; - if( magic!=SQLITE_MAGIC_CLOSED && - magic!=SQLITE_MAGIC_OPEN && - magic!=SQLITE_MAGIC_BUSY ) return 1; - return 0; -} - -/* ** The variable-length integer encoding is as follows: ** ** KEY: ** A = 0xxxxxxx 7 bits of data and one flag bit ** B = 1xxxxxxx 7 bits of data and one flag bit @@ -13461,21 +14989,21 @@ ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary ** value. Return a pointer to its binary value. Space to hold the ** binary value has been obtained from malloc and must be freed by ** the calling routine. */ -SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z){ +SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){ char *zBlob; int i; - int n = strlen(z); - if( n%2 ) return 0; - - zBlob = (char *)sqlite3DbMallocRaw(db, n/2); + + zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1); + n--; if( zBlob ){ for(i=0; i<n; i+=2){ zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]); } + zBlob[i/2] = 0; } return zBlob; } #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */ @@ -13503,10 +15031,11 @@ ** to modify the db structure at all. It could be that db is a stale ** pointer. In other words, it could be that there has been a prior ** call to sqlite3_close(db) and db has been deallocated. And we do ** not want to write into deallocated memory. */ +#ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){ if( db->magic==SQLITE_MAGIC_OPEN ){ db->magic = SQLITE_MAGIC_BUSY; return 0; }else if( db->magic==SQLITE_MAGIC_BUSY ){ @@ -13513,25 +15042,60 @@ db->magic = SQLITE_MAGIC_ERROR; db->u1.isInterrupted = 1; } return 1; } +#endif /* ** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN. ** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY ** when this routine is called. */ +#ifdef SQLITE_DEBUG SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){ if( db->magic==SQLITE_MAGIC_BUSY ){ db->magic = SQLITE_MAGIC_OPEN; return 0; - }else { + }else{ db->magic = SQLITE_MAGIC_ERROR; db->u1.isInterrupted = 1; return 1; } +} +#endif + +/* +** Check to make sure we have a valid db pointer. This test is not +** foolproof but it does provide some measure of protection against +** misuse of the interface such as passing in db pointers that are +** NULL or which have been previously closed. If this routine returns +** 1 it means that the db pointer is valid and 0 if it should not be +** dereferenced for any reason. The calling function should invoke +** SQLITE_MISUSE immediately. +** +** sqlite3SafetyCheckOk() requires that the db pointer be valid for +** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to +** open properly and is not fit for general use but which can be +** used as an argument to sqlite3_errmsg() or sqlite3_close(). +*/ +SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){ + int magic; + if( db==0 ) return 0; + magic = db->magic; + if( magic!=SQLITE_MAGIC_OPEN && + magic!=SQLITE_MAGIC_BUSY ) return 0; + return 1; +} +SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){ + int magic; + if( db==0 ) return 0; + magic = db->magic; + if( magic!=SQLITE_MAGIC_SICK && + magic!=SQLITE_MAGIC_OPEN && + magic!=SQLITE_MAGIC_BUSY ) return 0; + return 1; } /************** End of util.c ************************************************/ /************** Begin file hash.c ********************************************/ /* @@ -13546,11 +15110,11 @@ ** ************************************************************************* ** This is the implementation of generic hash-tables ** used in SQLite. ** -** $Id: hash.c,v 1.24 2007/09/04 14:31:47 danielk1977 Exp $ +** $Id: hash.c,v 1.25 2008/01/22 21:30:53 drh Exp $ */ /* Turn bulk memory into a hash table object by initializing the ** fields of the Hash structure. ** @@ -13760,13 +15324,14 @@ /* There is a call to sqlite3_malloc() inside rehash(). If there is ** already an allocation at pH->ht, then if this malloc() fails it ** is benign (since failing to resize a hash table is a performance ** hit only, not a fatal error). */ - sqlite3MallocBenignFailure(pH->htsize>0); - + sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, pH->htsize>0); new_ht = (struct _ht *)sqlite3MallocZero( new_size*sizeof(struct _ht) ); + sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 0); + if( new_ht==0 ) return; if( pH->ht ) sqlite3_free(pH->ht); pH->ht = new_ht; pH->htsize = new_size; xHash = hashFunction(pH->keyClass); @@ -13956,83 +15521,83 @@ /* Automatically generated. Do not edit */ /* See the mkopcodec.awk script for details. */ #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){ static const char *const azName[] = { "?", - /* 1 */ "ReadCookie", - /* 2 */ "AutoCommit", - /* 3 */ "Found", - /* 4 */ "NullRow", - /* 5 */ "MoveLe", - /* 6 */ "Variable", - /* 7 */ "Pull", - /* 8 */ "RealAffinity", - /* 9 */ "Sort", - /* 10 */ "IfNot", - /* 11 */ "Gosub", - /* 12 */ "NotFound", - /* 13 */ "MoveLt", - /* 14 */ "Rowid", - /* 15 */ "CreateIndex", + /* 1 */ "VNext", + /* 2 */ "Column", + /* 3 */ "SetCookie", + /* 4 */ "Sequence", + /* 5 */ "MoveGt", + /* 6 */ "RowKey", + /* 7 */ "SCopy", + /* 8 */ "OpenWrite", + /* 9 */ "If", + /* 10 */ "VRowid", + /* 11 */ "CollSeq", + /* 12 */ "OpenRead", + /* 13 */ "Expire", + /* 14 */ "AutoCommit", + /* 15 */ "IntegrityCk", /* 16 */ "Not", - /* 17 */ "Push", - /* 18 */ "Explain", - /* 19 */ "Statement", - /* 20 */ "Callback", - /* 21 */ "MemLoad", - /* 22 */ "DropIndex", - /* 23 */ "Null", - /* 24 */ "Int64", - /* 25 */ "LoadAnalysis", - /* 26 */ "IdxInsert", - /* 27 */ "VUpdate", - /* 28 */ "Next", - /* 29 */ "SetNumColumns", - /* 30 */ "MemInt", - /* 31 */ "Dup", - /* 32 */ "Rewind", - /* 33 */ "Last", - /* 34 */ "MustBeInt", - /* 35 */ "MoveGe", - /* 36 */ "IncrVacuum", - /* 37 */ "String", - /* 38 */ "VFilter", - /* 39 */ "ForceInt", - /* 40 */ "Close", - /* 41 */ "AggFinal", - /* 42 */ "AbsValue", - /* 43 */ "RowData", - /* 44 */ "IdxRowid", - /* 45 */ "MoveGt", - /* 46 */ "OpenPseudo", - /* 47 */ "Halt", - /* 48 */ "MemMove", - /* 49 */ "NewRowid", - /* 50 */ "IdxLT", - /* 51 */ "Distinct", - /* 52 */ "MemMax", - /* 53 */ "Function", - /* 54 */ "IntegrityCk", - /* 55 */ "FifoWrite", - /* 56 */ "NotExists", - /* 57 */ "VDestroy", - /* 58 */ "MemStore", + /* 17 */ "Sort", + /* 18 */ "Copy", + /* 19 */ "Trace", + /* 20 */ "Function", + /* 21 */ "IfNeg", + /* 22 */ "Noop", + /* 23 */ "Return", + /* 24 */ "NewRowid", + /* 25 */ "Variable", + /* 26 */ "String", + /* 27 */ "RealAffinity", + /* 28 */ "VRename", + /* 29 */ "ParseSchema", + /* 30 */ "VOpen", + /* 31 */ "Close", + /* 32 */ "CreateIndex", + /* 33 */ "IsUnique", + /* 34 */ "NotFound", + /* 35 */ "Int64", + /* 36 */ "MustBeInt", + /* 37 */ "Halt", + /* 38 */ "Rowid", + /* 39 */ "IdxLT", + /* 40 */ "AddImm", + /* 41 */ "Statement", + /* 42 */ "RowData", + /* 43 */ "MemMax", + /* 44 */ "NotExists", + /* 45 */ "Gosub", + /* 46 */ "Integer", + /* 47 */ "Prev", + /* 48 */ "VColumn", + /* 49 */ "CreateTable", + /* 50 */ "Last", + /* 51 */ "IncrVacuum", + /* 52 */ "IdxRowid", + /* 53 */ "ResetCount", + /* 54 */ "FifoWrite", + /* 55 */ "ContextPush", + /* 56 */ "DropTrigger", + /* 57 */ "DropIndex", + /* 58 */ "IdxGE", /* 59 */ "IdxDelete", /* 60 */ "Or", /* 61 */ "And", /* 62 */ "Vacuum", - /* 63 */ "If", - /* 64 */ "Destroy", + /* 63 */ "MoveLe", + /* 64 */ "IfNot", /* 65 */ "IsNull", /* 66 */ "NotNull", /* 67 */ "Ne", /* 68 */ "Eq", /* 69 */ "Gt", /* 70 */ "Le", /* 71 */ "Lt", /* 72 */ "Ge", - /* 73 */ "AggStep", + /* 73 */ "DropTable", /* 74 */ "BitAnd", /* 75 */ "BitOr", /* 76 */ "ShiftLeft", /* 77 */ "ShiftRight", /* 78 */ "Add", @@ -14039,63 +15604,63 @@ /* 79 */ "Subtract", /* 80 */ "Multiply", /* 81 */ "Divide", /* 82 */ "Remainder", /* 83 */ "Concat", - /* 84 */ "Clear", - /* 85 */ "Negative", - /* 86 */ "Insert", + /* 84 */ "MakeRecord", + /* 85 */ "ResultRow", + /* 86 */ "Delete", /* 87 */ "BitNot", /* 88 */ "String8", - /* 89 */ "VBegin", - /* 90 */ "IdxGE", - /* 91 */ "OpenEphemeral", - /* 92 */ "IfMemZero", - /* 93 */ "VRowid", - /* 94 */ "MakeRecord", - /* 95 */ "SetCookie", - /* 96 */ "Prev", - /* 97 */ "ContextPush", - /* 98 */ "DropTrigger", - /* 99 */ "IdxGT", - /* 100 */ "MemNull", - /* 101 */ "IfMemNeg", - /* 102 */ "VColumn", - /* 103 */ "Return", - /* 104 */ "OpenWrite", - /* 105 */ "Integer", - /* 106 */ "Transaction", - /* 107 */ "CollSeq", - /* 108 */ "VRename", - /* 109 */ "Sequence", - /* 110 */ "ContextPop", - /* 111 */ "VCreate", - /* 112 */ "CreateTable", - /* 113 */ "AddImm", - /* 114 */ "DropTable", - /* 115 */ "IsUnique", - /* 116 */ "VOpen", - /* 117 */ "Noop", - /* 118 */ "RowKey", - /* 119 */ "Expire", - /* 120 */ "FifoRead", - /* 121 */ "Delete", - /* 122 */ "IfMemPos", - /* 123 */ "MemIncr", - /* 124 */ "Blob", + /* 89 */ "AggFinal", + /* 90 */ "Goto", + /* 91 */ "TableLock", + /* 92 */ "FifoRead", + /* 93 */ "Clear", + /* 94 */ "MoveLt", + /* 95 */ "VerifyCookie", + /* 96 */ "AggStep", + /* 97 */ "SetNumColumns", + /* 98 */ "Transaction", + /* 99 */ "VFilter", + /* 100 */ "VDestroy", + /* 101 */ "ContextPop", + /* 102 */ "Next", + /* 103 */ "IdxInsert", + /* 104 */ "Insert", + /* 105 */ "Destroy", + /* 106 */ "ReadCookie", + /* 107 */ "ForceInt", + /* 108 */ "LoadAnalysis", + /* 109 */ "Explain", + /* 110 */ "OpenPseudo", + /* 111 */ "OpenEphemeral", + /* 112 */ "Null", + /* 113 */ "Move", + /* 114 */ "Blob", + /* 115 */ "Rewind", + /* 116 */ "MoveGe", + /* 117 */ "VBegin", + /* 118 */ "VUpdate", + /* 119 */ "IfZero", + /* 120 */ "VCreate", + /* 121 */ "Found", + /* 122 */ "IfPos", + /* 123 */ "NullRow", + /* 124 */ "NotUsed_124", /* 125 */ "Real", - /* 126 */ "HexBlob", - /* 127 */ "MakeIdxRec", - /* 128 */ "Goto", - /* 129 */ "ParseSchema", - /* 130 */ "VNext", - /* 131 */ "Pop", - /* 132 */ "TableLock", - /* 133 */ "VerifyCookie", - /* 134 */ "Column", - /* 135 */ "OpenRead", - /* 136 */ "ResetCount", + /* 126 */ "NotUsed_126", + /* 127 */ "NotUsed_127", + /* 128 */ "NotUsed_128", + /* 129 */ "NotUsed_129", + /* 130 */ "NotUsed_130", + /* 131 */ "NotUsed_131", + /* 132 */ "NotUsed_132", + /* 133 */ "NotUsed_133", + /* 134 */ "NotUsed_134", + /* 135 */ "NotUsed_135", + /* 136 */ "NotUsed_136", /* 137 */ "NotUsed_137", /* 138 */ "ToText", /* 139 */ "ToBlob", /* 140 */ "ToNumeric", /* 141 */ "ToInt", @@ -14402,19 +15967,14 @@ /* ** Truncate an open file to a specified size */ int os2Truncate( sqlite3_file *id, i64 nByte ){ APIRET rc = NO_ERROR; - ULONG filePosition = 0L; os2File *pFile = (os2File*)id; OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte ); SimulateIOError( return SQLITE_IOERR_TRUNCATE ); - rc = DosSetFilePtr( pFile->h, nByte, FILE_BEGIN, &filePosition ); - if( rc != NO_ERROR ){ - return SQLITE_IOERR; - } - rc = DosSetFilePtr( pFile->h, 0L, FILE_END, &filePosition ); + rc = DosSetFileSize( pFile->h, nByte ); return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR; } #ifdef SQLITE_TEST /* @@ -14779,11 +16339,11 @@ ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. -** a database and it's journal file) that the sector size will be the +** a database and its journal file) that the sector size will be the ** same for both. */ static int os2SectorSize(sqlite3_file *id){ return SQLITE_DEFAULT_SECTOR_SIZE; } @@ -14984,11 +16544,12 @@ static const unsigned char zChars[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; int i, j; - PSZ zTempPath = ""; + char zTempPathBuf[3]; + PSZ zTempPath = (PSZ)&zTempPathBuf; if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){ if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){ if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){ ULONG ulDriveNum = 0, ulDriveMap = 0; DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ); @@ -15026,30 +16587,12 @@ sqlite3_vfs *pVfs, /* Pointer to vfs object */ const char *zRelative, /* Possibly relative input path */ int nFull, /* Size of output buffer in bytes */ char *zFull /* Output buffer */ ){ - if( strchr(zRelative, ':') ){ - sqlite3SetString( &zFull, zRelative, (char*)0 ); - }else{ - ULONG ulDriveNum = 0; - ULONG ulDriveMap = 0; - ULONG cbzBufLen = SQLITE_TEMPNAME_SIZE; - char zDrive[2]; - char *zBuff = (char*)malloc( cbzBufLen ); - if( zBuff == 0 ){ - return SQLITE_NOMEM; - } - DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap ); - if( DosQueryCurrentDir( ulDriveNum, (PBYTE)zBuff, &cbzBufLen ) == NO_ERROR ){ - sprintf( zDrive, "%c", (char)('A' + ulDriveNum - 1) ); - sqlite3SetString( &zFull, zDrive, ":\\", zBuff, - "\\", zRelative, (char*)0 ); - } - free( zBuff ); - } - return SQLITE_OK; + APIRET rc = DosQueryPathInfo( zRelative, FIL_QUERYFULLNAME, zFull, nFull ); + return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR; } #ifndef SQLITE_OMIT_LOAD_EXTENSION /* ** Interfaces for opening a shared library, finding entry points @@ -15508,11 +17051,11 @@ /* ** The DJGPP compiler environment looks mostly like Unix, but it ** lacks the fcntl() system call. So redefine fcntl() to be something ** that always succeeds. This means that locking does not occur under -** DJGPP. But it's DOS - what did you expect? +** DJGPP. But it is DOS - what did you expect? */ #ifdef __DJGPP__ # define fcntl(A,B,C) 0 #endif @@ -15947,11 +17490,11 @@ } /* ** Examines the f_fstypename entry in the statfs structure as returned by ** stat() for the file system hosting the database file, assigns the -** appropriate locking style based on it's value. These values and +** appropriate locking style based on its value. These values and ** assignments are based on Darwin/OSX behavior and have not been tested on ** other systems. */ static sqlite3LockingStyle sqlite3DetectLockingStyle( const char *filePath, @@ -16412,12 +17955,12 @@ ** Truncate an open file to a specified size */ static int unixTruncate(sqlite3_file *id, i64 nByte){ int rc; assert( id ); - rc = ftruncate(((unixFile*)id)->h, (off_t)nByte); - SimulateIOError( rc=1 ); + SimulateIOError( return SQLITE_IOERR_TRUNCATE ); + rc = ftruncate(((unixFile*)id)->h, (off_t)nByte); if( rc ){ return SQLITE_IOERR_TRUNCATE; }else{ return SQLITE_OK; } @@ -17415,11 +18958,11 @@ ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. -** a database and it's journal file) that the sector size will be the +** a database and its journal file) that the sector size will be the ** same for both. */ static int unixSectorSize(sqlite3_file *id){ return SQLITE_DEFAULT_SECTOR_SIZE; } @@ -17892,14 +19435,16 @@ if( !S_ISDIR(buf.st_mode) ) continue; if( access(azDirs[i], 07) ) continue; zDir = azDirs[i]; break; } + if( strlen(zDir) - sizeof(SQLITE_TEMP_FILE_PREFIX) - 17 <=0 ){ + return SQLITE_ERROR; + } do{ assert( pVfs->mxPathname==MAX_PATHNAME ); - assert( nBuf>=MAX_PATHNAME ); - sqlite3_snprintf(MAX_PATHNAME-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir); + sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir); j = strlen(zBuf); sqlite3Randomness(15, &zBuf[j]); for(i=0; i<15; i++, j++){ zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; } @@ -17931,20 +19476,20 @@ ** current working directly has been unlinked. */ SimulateIOError( return SQLITE_ERROR ); assert( pVfs->mxPathname==MAX_PATHNAME ); - zOut[MAX_PATHNAME-1] = '\0'; + zOut[nOut-1] = '\0'; if( zPath[0]=='/' ){ - sqlite3_snprintf(MAX_PATHNAME, zOut, "%s", zPath); + sqlite3_snprintf(nOut, zOut, "%s", zPath); }else{ int nCwd; - if( getcwd(zOut, MAX_PATHNAME-1)==0 ){ + if( getcwd(zOut, nOut-1)==0 ){ return SQLITE_CANTOPEN; } nCwd = strlen(zOut); - sqlite3_snprintf(MAX_PATHNAME-nCwd, &zOut[nCwd], "/%s", zPath); + sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath); } return SQLITE_OK; #if 0 /* @@ -19277,11 +20822,11 @@ ** the specified file. This is almost always 512 bytes, but may be ** larger for some devices. ** ** SQLite code assumes this function cannot fail. It also assumes that ** if two files are created in the same file-system directory (i.e. -** a database and it's journal file) that the sector size will be the +** a database and its journal file) that the sector size will be the ** same for both. */ static int winSectorSize(sqlite3_file *id){ return SQLITE_DEFAULT_SECTOR_SIZE; } @@ -19371,12 +20916,11 @@ if( flags & SQLITE_OPEN_MAIN_DB ){ dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; }else{ dwShareMode = 0; } - if( flags & (SQLITE_OPEN_TEMP_DB | SQLITE_OPEN_TEMP_JOURNAL - | SQLITE_OPEN_SUBJOURNAL) ){ + if( flags & SQLITE_OPEN_DELETEONCLOSE ){ #if OS_WINCE dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN; #else dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_HIDDEN @@ -19572,11 +21116,11 @@ return SQLITE_NOMEM; } } for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){} zTempPath[i] = 0; - sqlite3_snprintf(pVfs->mxPathname-30, zBuf, + sqlite3_snprintf(nBuf-30, zBuf, "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath); j = strlen(zBuf); sqlite3Randomness(20, &zBuf[j]); for(i=0; i<20; i++, j++){ zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ]; @@ -19847,11 +21391,11 @@ ** is separate from the database file. The pager also implements file ** locking to prevent two processes from writing the same database ** file simultaneously, or one process from reading the database while ** another is writing. ** -** @(#) $Id: pager.c,v 1.394 2007/11/05 15:30:13 danielk1977 Exp $ +** @(#) $Id: pager.c,v 1.404 2008/01/22 21:30:53 drh Exp $ */ #ifndef SQLITE_OMIT_DISKIO /* ** Macros for troubleshooting. Normally turned off @@ -19873,13 +21417,13 @@ /* ** The following two macros are used within the PAGERTRACEX() macros above ** to print out file-descriptors. ** -** PAGERID() takes a pointer to a Pager struct as it's argument. The +** PAGERID() takes a pointer to a Pager struct as its argument. The ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file -** struct as it's argument. +** struct as its argument. */ #define PAGERID(p) ((int)(p->fd)) #define FILEHANDLEID(fd) ((int)fd) /* @@ -19971,11 +21515,11 @@ ** Additionally, if memory-management is enabled, all unreferenced pages ** are stored in a global LRU list (global variable sqlite3LruPageList). ** ** In both cases, the PagerLruList.pFirstSynced variable points to ** the first page in the corresponding list that does not require an -** fsync() operation before it's memory can be reclaimed. If no such +** fsync() operation before its memory can be reclaimed. If no such ** page exists, PagerLruList.pFirstSynced is set to NULL. */ typedef struct PagerLruList PagerLruList; struct PagerLruList { PgHdr *pFirst; /* First page in LRU list */ @@ -20525,12 +22069,13 @@ */ static void pager_resize_hash_table(Pager *pPager, int N){ PgHdr **aHash, *pPg; assert( N>0 && (N&(N-1))==0 ); pagerLeave(pPager); - sqlite3MallocBenignFailure((int)pPager->aHash); + sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, pPager->aHash!=0); aHash = sqlite3MallocZero( sizeof(aHash[0])*N ); + sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 0); pagerEnter(pPager); if( aHash==0 ){ /* Failure to rehash is not an error. It is only a performance hit. */ return; } @@ -21472,15 +23017,28 @@ static void pager_truncate_cache(Pager *pPager); /* ** Truncate the main file of the given pager to the number of pages ** indicated. Also truncate the cached representation of the file. +** +** Might might be the case that the file on disk is smaller than nPage. +** This can happen, for example, if we are in the middle of a transaction +** which has extended the file size and the new pages are still all held +** in cache, then an INSERT or UPDATE does a statement rollback. Some +** operating system implementations can get confused if you try to +** truncate a file to some size that is larger than it currently is, +** so detect this case and do not do the truncation. */ static int pager_truncate(Pager *pPager, int nPage){ int rc = SQLITE_OK; if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){ - rc = sqlite3OsTruncate(pPager->fd, pPager->pageSize*(i64)nPage); + i64 currentSize, newSize; + rc = sqlite3OsFileSize(pPager->fd, ¤tSize); + newSize = pPager->pageSize*(i64)nPage; + if( rc==SQLITE_OK && currentSize>newSize ){ + rc = sqlite3OsTruncate(pPager->fd, newSize); + } } if( rc==SQLITE_OK ){ pPager->dbSize = nPage; pager_truncate_cache(pPager); } @@ -21635,11 +23193,11 @@ pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){ nRec = (szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager); } /* If this is the first header read from the journal, truncate the - ** database file back to it's original size. + ** database file back to its original size. */ if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){ rc = pager_truncate(pPager, mxPg); if( rc!=SQLITE_OK ){ goto end_playback; @@ -22159,10 +23717,22 @@ *pPageSize = pPager->pageSize; return rc; } /* +** Return a pointer to the "temporary page" buffer held internally +** by the pager. This is a buffer that is big enough to hold the +** entire content of a database page. This buffer is used internally +** during rollback and will be overwritten whenever a rollback +** occurs. But other modules are free to use it too, as long as +** no rollbacks are happening. +*/ +SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){ + return pPager->pTmpSpace; +} + +/* ** Attempt to set the maximum database page count if mxPage is positive. ** Make no changes if mxPage is zero or negative. And never reduce the ** maximum page count below the current size of the database. ** ** Regardless of mxPage, return the current maximum page count. @@ -22287,11 +23857,11 @@ ** Forward declaration */ static int syncJournal(Pager*); /* -** Unlink pPg from it's hash chain. Also set the page number to 0 to indicate +** Unlink pPg from its hash chain. Also set the page number to 0 to indicate ** that the page is not part of any hash chain. This is required because the ** sqlite3PagerMovepage() routine can leave a page in the ** pNextFree/pPrevFree list that is not a part of any hash-chain. */ static void unlinkHashChain(Pager *pPager, PgHdr *pPg){ @@ -22833,10 +24403,11 @@ ** database with the same name. Just delete the journal. */ static int hasHotJournal(Pager *pPager){ sqlite3_vfs *pVfs = pPager->pVfs; if( !pPager->useJournal ) return 0; + if( !pPager->fd->pMethods ) return 0; if( !sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS) ){ return 0; } if( sqlite3OsCheckReservedLock(pPager->fd) ){ return 0; @@ -22951,10 +24522,11 @@ */ SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int nReq){ int nReleased = 0; /* Bytes of memory released so far */ sqlite3_mutex *mutex; /* The MEM2 mutex */ Pager *pPager; /* For looping over pagers */ + BusyHandler *savedBusy; /* Saved copy of the busy handler */ int rc = SQLITE_OK; /* Acquire the memory-management mutex */ mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM2); @@ -22995,11 +24567,14 @@ pPager = pPg->pPager; assert(!pPg->needSync || pPg==pPager->lru.pFirst); assert(pPg->needSync || pPg==pPager->lru.pFirstSynced); + savedBusy = pPager->pBusyHandler; + pPager->pBusyHandler = 0; rc = pager_recycle(pPager, &pRecycled); + pPager->pBusyHandler = savedBusy; assert(pRecycled==pPg || rc!=SQLITE_OK); if( rc==SQLITE_OK ){ /* We've found a page to free. At this point the page has been ** removed from the page hash-table, free-list and synced-list ** (pFirstSynced). It is still in the all pages (pAll) list. @@ -23139,11 +24714,11 @@ ** database is safe to read while this process is still rolling it ** back. ** ** Because the intermediate RESERVED lock is not requested, the ** second process will get to this point in the code and fail to - ** obtain it's own EXCLUSIVE lock on the database file. + ** obtain its own EXCLUSIVE lock on the database file. */ if( pPager->state<EXCLUSIVE_LOCK ){ rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK); if( rc!=SQLITE_OK ){ pager_unlock(pPager); @@ -24175,37 +25750,55 @@ ** ** If we have not yet actually read the content of this page (if ** the PgHdr.needRead flag is set) then this routine acts as a promise ** that we will never need to read the page content in the future. ** so the needRead flag can be cleared at this point. +** +** This routine is only called from a single place in the sqlite btree +** code (when a leaf is removed from the free-list). This allows the +** following assumptions to be made about pPg: +** +** 1. PagerDontWrite() has been called on the page, OR +** PagerWrite() has not yet been called on the page. +** +** 2. The page existed when the transaction was started. +** +** Details: DontRollback() (this routine) is only called when a leaf is +** removed from the free list. DontWrite() is called whenever a page +** becomes a free-list leaf. */ SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){ Pager *pPager = pPg->pPager; pagerEnter(pPager); assert( pPager->state>=PAGER_RESERVED ); - if( pPager->journalOpen==0 ) return; - if( pPg->alwaysRollback || pPager->alwaysRollback || MEMDB ) return; - if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){ - assert( pPager->aInJournal!=0 ); - pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7); - pPg->inJournal = 1; - pPg->needRead = 0; - if( pPager->stmtInUse ){ - pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7); - } - PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager)); - IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno)) - } - if( pPager->stmtInUse - && !pageInStatement(pPg) - && (int)pPg->pgno<=pPager->stmtSize - ){ - assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize ); - assert( pPager->aInStmt!=0 ); + + /* If the journal file is not open, or DontWrite() has been called on + ** this page (DontWrite() sets the alwaysRollback flag), then this + ** function is a no-op. + */ + if( pPager->journalOpen==0 || pPg->alwaysRollback || pPager->alwaysRollback ){ + pagerLeave(pPager); + return; + } + assert( !MEMDB ); /* For a memdb, pPager->journalOpen is always 0 */ + + /* Check that PagerWrite() has not yet been called on this page, and + ** that the page existed when the transaction started. + */ + assert( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ); + + assert( pPager->aInJournal!=0 ); + pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7); + pPg->inJournal = 1; + pPg->needRead = 0; + if( pPager->stmtInUse ){ + assert( pPager->stmtSize <= pPager->origDbSize ); pPager->aInStmt[pPg->pgno/8] |= 1<<(pPg->pgno&7); } + PAGERTRACE3("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager)); + IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno)) pagerLeave(pPager); } /* @@ -24382,11 +25975,11 @@ sync_exit: if( rc==SQLITE_IOERR_BLOCKED ){ /* pager_incr_changecounter() may attempt to obtain an exclusive * lock to spill the cache and return IOERR_BLOCKED. But since - * there is no chance the cache is inconsistent, it's + * there is no chance the cache is inconsistent, it is * better to return SQLITE_BUSY. */ rc = SQLITE_BUSY; } pagerLeave(pPager); @@ -24434,10 +26027,11 @@ assert( !pHist->pStmt ); } #endif pPager->pStmt = 0; pPager->state = PAGER_SHARED; + pagerLeave(pPager); return SQLITE_OK; } assert( pPager->journalOpen || !pPager->dirtyCache ); assert( pPager->state==PAGER_SYNCED || !pPager->dirtyCache ); rc = pager_end_transaction(pPager); @@ -24797,15 +26391,15 @@ assert( pPg->inJournal || (int)pgno>pPager->origDbSize ); assert( pPg->dirty ); assert( pPager->needSync ); } - /* Unlink pPg from it's hash-chain */ + /* Unlink pPg from its hash-chain */ unlinkHashChain(pPager, pPg); /* If the cache contains a page with page-number pgno, remove it - ** from it's hash chain. Also, if the PgHdr.needSync was set for + ** from its hash chain. Also, if the PgHdr.needSync was set for ** page pgno before the 'move' operation, it needs to be retained ** for the page moved there. */ pPg->needSync = 0; pPgOld = pager_lookup(pPager, pgno); @@ -24844,18 +26438,31 @@ ** sync()ed before any data is written to database file page needSyncPgno. ** Currently, no such page exists in the page-cache and the ** Pager.aInJournal bit has been set. This needs to be remedied by loading ** the page into the pager-cache and setting the PgHdr.needSync flag. ** + ** If the attempt to load the page into the page-cache fails, (due + ** to a malloc() or IO failure), clear the bit in the aInJournal[] + ** array. Otherwise, if the page is loaded and written again in + ** this transaction, it may be written to the database file before + ** it is synced into the journal file. This way, it may end up in + ** the journal file twice, but that is not a problem. + ** ** The sqlite3PagerGet() call may cause the journal to sync. So make ** sure the Pager.needSync flag is set too. */ int rc; PgHdr *pPgHdr; assert( pPager->needSync ); rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr); - if( rc!=SQLITE_OK ) return rc; + if( rc!=SQLITE_OK ){ + if( pPager->aInJournal && (int)needSyncPgno<=pPager->origDbSize ){ + pPager->aInJournal[needSyncPgno/8] &= ~(1<<(needSyncPgno&7)); + } + pagerLeave(pPager); + return rc; + } pPager->needSync = 1; pPgHdr->needSync = 1; pPgHdr->inJournal = 1; makeDirty(pPgHdr); sqlite3PagerUnref(pPgHdr); @@ -24902,11 +26509,11 @@ pPager->exclusiveMode = eMode; } return (int)pPager->exclusiveMode; } -#ifdef SQLITE_DEBUG +#ifdef SQLITE_TEST /* ** Print a listing of all referenced pages and their ref count. */ SQLITE_PRIVATE void sqlite3PagerRefdump(Pager *pPager){ PgHdr *pPg; @@ -24932,11 +26539,11 @@ ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** -** $Id: btmutex.c,v 1.7 2007/08/30 01:19:59 drh Exp $ +** $Id: btmutex.c,v 1.9 2008/01/23 12:52:41 drh Exp $ ** ** This file contains code used to implement mutexes on Btree objects. ** This code really belongs in btree.c. But btree.c is getting too ** big and we want to break it down some. This packaged seemed like ** a good breakout. @@ -24952,11 +26559,11 @@ ** 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. ** ************************************************************************* -** $Id: btreeInt.h,v 1.13 2007/08/30 01:19:59 drh Exp $ +** $Id: btreeInt.h,v 1.15 2007/12/21 04:47:26 danielk1977 Exp $ ** ** This file implements a external (disk-based) database using BTrees. ** For a detailed discussion of BTrees, refer to ** ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3: @@ -25263,17 +26870,17 @@ ** in the referenced BtShared that point back to this Btree since those ** cursors have to do go through this Btree to find their BtShared and ** they often do so without holding sqlite3.mutex. */ struct Btree { - sqlite3 *pSqlite; /* The database connection holding this btree */ + sqlite3 *db; /* The database connection holding this btree */ BtShared *pBt; /* Sharable content of this btree */ u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */ - u8 sharable; /* True if we can share pBt with other pSqlite */ - u8 locked; /* True if pSqlite currently has pBt locked */ + u8 sharable; /* True if we can share pBt with another db */ + u8 locked; /* True if db currently has pBt locked */ int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */ - Btree *pNext; /* List of other sharable Btrees from the same pSqlite */ + Btree *pNext; /* List of other sharable Btrees from the same db */ Btree *pPrev; /* Back pointer of the same list */ }; /* ** Btree.inTrans may take one of the following values. @@ -25303,10 +26910,11 @@ ** The pSchema field may be set once under BtShared.mutex and ** thereafter is unchanged as long as nRef>0. */ struct BtShared { Pager *pPager; /* The page cache */ + sqlite3 *db; /* Database connection currently using this Btree */ BtCursor *pCursor; /* A list of all open cursors */ MemPage *pPage1; /* First page of the database */ u8 inStmt; /* True if we are in a statement subtransaction */ u8 readOnly; /* True if the underlying file is readonly */ u8 maxEmbedFrac; /* Maximum payload as % of total page size */ @@ -25322,20 +26930,21 @@ u16 usableSize; /* Number of usable bytes on each page */ int maxLocal; /* Maximum local payload in non-LEAFDATA tables */ int minLocal; /* Minimum local payload in non-LEAFDATA tables */ int maxLeaf; /* Maximum local payload in a LEAFDATA table */ int minLeaf; /* Minimum local payload in a LEAFDATA table */ - BusyHandler *pBusyHandler; /* Callback for when there is lock contention */ u8 inTransaction; /* Transaction state */ int nTransaction; /* Number of open transactions (read + write) */ void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */ void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */ sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */ + BusyHandler busyHdr; /* The busy handler for this btree */ #ifndef SQLITE_OMIT_SHARED_CACHE int nRef; /* Number of references to this structure */ BtShared *pNext; /* Next on a list of sharable BtShared structs */ BtLock *pLock; /* List of locks held on this shared-btree struct */ + Btree *pExclusive; /* Btree with an EXCLUSIVE lock on the whole db */ #endif }; /* ** An instance of the following structure is used to hold information @@ -25361,11 +26970,11 @@ ** The entry is identified by its MemPage and the index in ** MemPage.aCell[] of the entry. ** ** When a single database file can shared by two more database connections, ** but cursors cannot be shared. Each cursor is associated with a -** particular database connection identified BtCursor.pBtree.pSqlite. +** particular database connection identified BtCursor.pBtree.db. ** ** Fields in this structure are accessed under the BtShared.mutex ** found at self->pBt->mutex. */ struct BtCursor { @@ -25615,25 +27224,26 @@ ** connected by pNext and pPrev should be in sorted order by ** Btree.pBt value. All elements of the list should belong to ** the same connection. Only shared Btrees are on the list. */ assert( p->pNext==0 || p->pNext->pBt>p->pBt ); assert( p->pPrev==0 || p->pPrev->pBt<p->pBt ); - assert( p->pNext==0 || p->pNext->pSqlite==p->pSqlite ); - assert( p->pPrev==0 || p->pPrev->pSqlite==p->pSqlite ); + assert( p->pNext==0 || p->pNext->db==p->db ); + assert( p->pPrev==0 || p->pPrev->db==p->db ); assert( p->sharable || (p->pNext==0 && p->pPrev==0) ); /* Check for locking consistency */ assert( !p->locked || p->wantToLock>0 ); assert( p->sharable || p->wantToLock==0 ); /* We should already hold a lock on the database connection */ - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); if( !p->sharable ) return; p->wantToLock++; if( p->locked ) return; +#ifndef SQLITE_MUTEX_NOOP /* In most cases, we should be able to acquire the lock we ** want without having to go throught the ascending lock ** procedure that follows. Just be sure not to block. */ if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){ @@ -25661,10 +27271,11 @@ if( pLater->wantToLock ){ sqlite3_mutex_enter(pLater->pBt->mutex); pLater->locked = 1; } } +#endif /* SQLITE_MUTEX_NOOP */ } /* ** Exit the recursive mutex on a Btree. */ @@ -25847,11 +27458,11 @@ /* Some basic sanity checking */ assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt ); assert( !p->locked || p->wantToLock>0 ); /* We should already hold a lock on the database connection */ - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); p->wantToLock++; if( !p->locked && p->sharable ){ sqlite3_mutex_enter(p->pBt->mutex); p->locked = 1; @@ -25870,11 +27481,11 @@ assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt ); assert( p->locked || !p->sharable ); assert( p->wantToLock>0 ); /* We should already hold a lock on the database connection */ - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); p->wantToLock--; if( p->wantToLock==0 && p->locked ){ sqlite3_mutex_leave(p->pBt->mutex); p->locked = 0; @@ -25896,11 +27507,11 @@ ** 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. ** ************************************************************************* -** $Id: btree.c,v 1.430 2007/11/05 15:30:13 danielk1977 Exp $ +** $Id: btree.c,v 1.438 2008/01/31 14:54:44 drh Exp $ ** ** This file implements a external (disk-based) database using BTrees. ** See the header comment on "btreeInt.h" for additional information. ** Including a description of file format and an overview of operation. */ @@ -25989,10 +27600,17 @@ /* This is a no-op if the shared-cache is not enabled */ if( !p->sharable ){ return SQLITE_OK; } + /* If some other connection is holding an exclusive lock, the + ** requested lock may not be obtained. + */ + if( pBt->pExclusive && pBt->pExclusive!=p ){ + return SQLITE_LOCKED; + } + /* This (along with lockTable()) is where the ReadUncommitted flag is ** dealt with. If the caller is querying for a read-lock and the flag is ** set, it is unconditionally granted - even if there are write-locks ** on the table. If a write-lock is requested, the ReadUncommitted flag ** is not considered. @@ -26004,12 +27622,12 @@ ** To summarize: If the ReadUncommitted flag is set, then read cursors do ** not create or respect table locks. The locking procedure for a ** write-cursor does not change. */ if( - !p->pSqlite || - 0==(p->pSqlite->flags&SQLITE_ReadUncommitted) || + !p->db || + 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK || iTab==MASTER_ROOT ){ for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ if( pIter->pBtree!=p && pIter->iTable==iTab && @@ -26049,12 +27667,12 @@ ** return early without adding an entry to the BtShared.pLock list. See ** comment in function queryTableLock() for more info on handling ** the ReadUncommitted flag. */ if( - (p->pSqlite) && - (p->pSqlite->flags&SQLITE_ReadUncommitted) && + (p->db) && + (p->db->flags&SQLITE_ReadUncommitted) && (eLock==READ_LOCK) && iTable!=MASTER_ROOT ){ return SQLITE_OK; } @@ -26098,23 +27716,29 @@ /* ** Release all the table locks (locks obtained via calls to the lockTable() ** procedure) held by Btree handle p. */ static void unlockAllTables(Btree *p){ - BtLock **ppIter = &p->pBt->pLock; + BtShared *pBt = p->pBt; + BtLock **ppIter = &pBt->pLock; assert( sqlite3BtreeHoldsMutex(p) ); assert( p->sharable || 0==*ppIter ); while( *ppIter ){ BtLock *pLock = *ppIter; + assert( pBt->pExclusive==0 || pBt->pExclusive==pLock->pBtree ); if( pLock->pBtree==p ){ *ppIter = pLock->pNext; sqlite3_free(pLock); }else{ ppIter = &pLock->pNext; } + } + + if( pBt->pExclusive==p ){ + pBt->pExclusive = 0; } } #endif /* SQLITE_OMIT_SHARED_CACHE */ static void releasePage(MemPage *pPage); /* Forward reference */ @@ -26236,11 +27860,11 @@ ** saved position info stored by saveCursorPosition(), so there can be ** at most one effective restoreOrClearCursorPosition() call after each ** saveCursorPosition(). ** ** If the second argument argument - doSeek - is false, then instead of -** returning the cursor to it's saved position, any saved position is deleted +** returning the cursor to its saved position, any saved position is deleted ** and the cursor state set to CURSOR_INVALID. */ SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){ int rc; assert( cursorHoldsMutex(pCur) ); @@ -26563,12 +28187,11 @@ assert( sqlite3PagerIswriteable(pPage->pDbPage) ); assert( pPage->pBt!=0 ); assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE ); assert( pPage->nOverflow==0 ); assert( sqlite3_mutex_held(pPage->pBt->mutex) ); - temp = sqlite3_malloc( pPage->pBt->pageSize ); - if( temp==0 ) return SQLITE_NOMEM; + temp = sqlite3PagerTempSpace(pPage->pBt->pPager); data = pPage->aData; hdr = pPage->hdrOffset; cellOffset = pPage->cellOffset; nCell = pPage->nCell; assert( nCell==get2byte(&data[hdr+3]) ); @@ -26591,11 +28214,10 @@ data[hdr+1] = 0; data[hdr+2] = 0; data[hdr+7] = 0; addr = cellOffset+2*nCell; memset(&data[addr], 0, brk-addr); - sqlite3_free(temp); return SQLITE_OK; } /* ** Allocate nByte bytes of space on a page. @@ -26987,10 +28609,20 @@ sqlite3BtreeInitPage(pPage, pPage->pParent); } } /* +** Invoke the busy handler for a btree. +*/ +static int sqlite3BtreeInvokeBusyHandler(void *pArg, int n){ + BtShared *pBt = (BtShared*)pArg; + assert( pBt->db ); + assert( sqlite3_mutex_held(pBt->db->mutex) ); + return sqlite3InvokeBusyHandler(&pBt->db->busyHandler); +} + +/* ** Open a database file. ** ** zFilename is the name of the database file. If zFilename is NULL ** a new database with a random name is created. This randomly named ** database file will be deleted when sqlite3BtreeClose() is called. @@ -26997,11 +28629,11 @@ ** If zFilename is ":memory:" then an in-memory database is created ** that is automatically destroyed when it is closed. */ SQLITE_PRIVATE int sqlite3BtreeOpen( const char *zFilename, /* Name of the file containing the BTree database */ - sqlite3 *pSqlite, /* Associated database handle */ + sqlite3 *db, /* Associated database handle */ Btree **ppBtree, /* Pointer to new Btree object written here */ int flags, /* Options */ int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */ ){ sqlite3_vfs *pVfs; /* The VFS to use for this btree */ @@ -27022,38 +28654,38 @@ #else const int isMemdb = zFilename && !strcmp(zFilename, ":memory:"); #endif #endif - assert( pSqlite!=0 ); - assert( sqlite3_mutex_held(pSqlite->mutex) ); - - pVfs = pSqlite->pVfs; + assert( db!=0 ); + assert( sqlite3_mutex_held(db->mutex) ); + + pVfs = db->pVfs; p = sqlite3MallocZero(sizeof(Btree)); if( !p ){ return SQLITE_NOMEM; } p->inTrans = TRANS_NONE; - p->pSqlite = pSqlite; + p->db = db; #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO) /* ** If this Btree is a candidate for shared cache, try to find an ** existing BtShared object that we can share with */ if( (flags & BTREE_PRIVATE)==0 && isMemdb==0 - && (pSqlite->flags & SQLITE_Vtab)==0 + && (db->flags & SQLITE_Vtab)==0 && zFilename && zFilename[0] ){ if( sqlite3SharedCacheEnabled ){ int nFullPathname = pVfs->mxPathname+1; char *zFullPathname = (char *)sqlite3_malloc(nFullPathname); sqlite3_mutex *mutexShared; p->sharable = 1; - if( pSqlite ){ - pSqlite->flags |= SQLITE_SharedCache; + if( db ){ + db->flags |= SQLITE_SharedCache; } if( !zFullPathname ){ sqlite3_free(p); return SQLITE_NOMEM; } @@ -27099,18 +28731,21 @@ pBt = sqlite3MallocZero( sizeof(*pBt) ); if( pBt==0 ){ rc = SQLITE_NOMEM; goto btree_open_out; } + pBt->busyHdr.xFunc = sqlite3BtreeInvokeBusyHandler; + pBt->busyHdr.pArg = pBt; rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename, EXTRA_SIZE, flags, vfsFlags); if( rc==SQLITE_OK ){ rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader); } if( rc!=SQLITE_OK ){ goto btree_open_out; } + sqlite3PagerSetBusyhandler(pBt->pPager, &pBt->busyHdr); p->pBt = pBt; sqlite3PagerSetDestructor(pBt->pPager, pageDestructor); sqlite3PagerSetReiniter(pBt->pPager, pageReinit); pBt->pCursor = 0; @@ -27161,11 +28796,11 @@ mutexShared = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); if( SQLITE_THREADSAFE ){ pBt->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); if( pBt->mutex==0 ){ rc = SQLITE_NOMEM; - pSqlite->mallocFailed = 0; + db->mallocFailed = 0; goto btree_open_out; } } sqlite3_mutex_enter(mutexShared); pBt->pNext = sqlite3SharedCacheList; @@ -27181,12 +28816,12 @@ ** The list is kept in ascending order by pBt address. */ if( p->sharable ){ int i; Btree *pSib; - for(i=0; i<pSqlite->nDb; i++){ - if( (pSib = pSqlite->aDb[i].pBt)!=0 && pSib->sharable ){ + for(i=0; i<db->nDb; i++){ + if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){ while( pSib->pPrev ){ pSib = pSib->pPrev; } if( p->pBt<pSib->pBt ){ p->pNext = pSib; p->pPrev = 0; pSib->pPrev = p; @@ -27266,12 +28901,13 @@ SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){ BtShared *pBt = p->pBt; BtCursor *pCur; /* Close all cursors opened via this handle. */ - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); - sqlite3BtreeEnter(p); + assert( sqlite3_mutex_held(p->db->mutex) ); + sqlite3BtreeEnter(p); + pBt->db = p->db; pCur = pBt->pCursor; while( pCur ){ BtCursor *pTmp = pCur; pCur = pCur->pNext; if( pTmp->pBtree==p ){ @@ -27316,23 +28952,10 @@ sqlite3_free(p); return SQLITE_OK; } /* -** Change the busy handler callback function. -*/ -SQLITE_PRIVATE int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){ - BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); - sqlite3BtreeEnter(p); - pBt->pBusyHandler = pHandler; - sqlite3PagerSetBusyhandler(pBt->pPager, pHandler); - sqlite3BtreeLeave(p); - return SQLITE_OK; -} - -/* ** Change the limit on the number of pages allowed in the cache. ** ** The maximum number of cache pages is set to the absolute ** value of mxPage. If mxPage is negative, the pager will ** operate asynchronously - it will not stop to do fsync()s @@ -27345,11 +28968,11 @@ ** Synchronous is on by default so database corruption is not ** normally a worry. */ SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){ BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetCachesize(pBt->pPager, mxPage); sqlite3BtreeLeave(p); return SQLITE_OK; } @@ -27363,11 +28986,11 @@ ** probability of damage to near zero but with a write performance reduction. */ #ifndef SQLITE_OMIT_PAGER_PRAGMAS SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){ BtShared *pBt = p->pBt; - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync); sqlite3BtreeLeave(p); return SQLITE_OK; } @@ -27378,11 +29001,11 @@ ** words, return TRUE if no sync() occurs on the disk files. */ SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){ BtShared *pBt = p->pBt; int rc; - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); assert( pBt && pBt->pPager ); rc = sqlite3PagerNosync(pBt->pPager); sqlite3BtreeLeave(p); return rc; @@ -27621,16 +29244,19 @@ */ static void unlockBtreeIfUnused(BtShared *pBt){ assert( sqlite3_mutex_held(pBt->mutex) ); if( pBt->inTransaction==TRANS_NONE && pBt->pCursor==0 && pBt->pPage1!=0 ){ if( sqlite3PagerRefcount(pBt->pPager)>=1 ){ + assert( pBt->pPage1->aData ); +#if 0 if( pBt->pPage1->aData==0 ){ MemPage *pPage = pBt->pPage1; pPage->aData = sqlite3PagerGetData(pPage->pDbPage); pPage->pBt = pBt; pPage->pgno = 1; } +#endif releasePage(pBt->pPage1); } pBt->pPage1 = 0; pBt->inStmt = 0; } @@ -27711,10 +29337,11 @@ SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){ BtShared *pBt = p->pBt; int rc = SQLITE_OK; sqlite3BtreeEnter(p); + pBt->db = p->db; btreeIntegrity(p); /* If the btree is already in a write-transaction, or it ** is already in a read-transaction and a read-transaction ** is requested, this is a no-op. @@ -27736,10 +29363,22 @@ if( pBt->inTransaction==TRANS_WRITE && wrflag ){ rc = SQLITE_BUSY; goto trans_begun; } +#ifndef SQLITE_OMIT_SHARED_CACHE + if( wrflag>1 ){ + BtLock *pIter; + for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){ + if( pIter->pBtree!=p ){ + rc = SQLITE_BUSY; + goto trans_begun; + } + } + } +#endif + do { if( pBt->pPage1==0 ){ rc = lockBtree(pBt); } @@ -27758,20 +29397,26 @@ if( wrflag ) pBt->inStmt = 0; }else{ unlockBtreeIfUnused(pBt); } }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE && - sqlite3InvokeBusyHandler(pBt->pBusyHandler) ); + sqlite3BtreeInvokeBusyHandler(pBt, 0) ); if( rc==SQLITE_OK ){ if( p->inTrans==TRANS_NONE ){ pBt->nTransaction++; } p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ); if( p->inTrans>pBt->inTransaction ){ pBt->inTransaction = p->inTrans; } +#ifndef SQLITE_OMIT_SHARED_CACHE + if( wrflag>1 ){ + assert( !pBt->pExclusive ); + pBt->pExclusive = p; + } +#endif } trans_begun: btreeIntegrity(p); @@ -27909,11 +29554,11 @@ assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ); assert( sqlite3_mutex_held(pBt->mutex) ); assert( pDbPage->pBt==pBt ); - /* Move page iDbPage from it's current location to page number iFreePage */ + /* Move page iDbPage from its current location to page number iFreePage */ TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", iDbPage, iFreePage, iPtrPage, eType)); rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage); if( rc!=SQLITE_OK ){ return rc; @@ -28084,10 +29729,11 @@ SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE ); if( !pBt->autoVacuum ){ rc = SQLITE_DONE; }else{ invalidateAllOverflowCache(pBt); @@ -28200,10 +29846,11 @@ int rc = SQLITE_OK; if( p->inTrans==TRANS_WRITE ){ BtShared *pBt = p->pBt; Pgno nTrunc = 0; sqlite3BtreeEnter(p); + pBt->db = p->db; #ifndef SQLITE_OMIT_AUTOVACUUM if( pBt->autoVacuum ){ rc = autoVacuumCommit(pBt, &nTrunc); if( rc!=SQLITE_OK ){ sqlite3BtreeLeave(p); @@ -28233,10 +29880,11 @@ */ SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){ BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; btreeIntegrity(p); /* If the handle has a write-transaction open, commit the shared-btrees ** transaction and set the shared state to TRANS_READ. */ @@ -28353,10 +30001,11 @@ int rc; BtShared *pBt = p->pBt; MemPage *pPage1; sqlite3BtreeEnter(p); + pBt->db = p->db; rc = saveAllCursors(pBt, 0, 0); #ifndef SQLITE_OMIT_SHARED_CACHE if( rc!=SQLITE_OK ){ /* This is a horrible situation. An IO or malloc() error occured whilst ** trying to save cursor positions. If this is an automatic rollback (as @@ -28428,10 +30077,11 @@ */ SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){ rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; }else{ assert( pBt->inTransaction==TRANS_WRITE ); rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager); @@ -28448,10 +30098,11 @@ */ SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; if( pBt->inStmt && !pBt->readOnly ){ rc = sqlite3PagerStmtCommit(pBt->pPager); }else{ rc = SQLITE_OK; } @@ -28470,10 +30121,11 @@ */ SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){ int rc = SQLITE_OK; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; if( pBt->inStmt && !pBt->readOnly ){ rc = sqlite3PagerStmtRollback(pBt->pPager); assert( countWriteCursors(pBt)==0 ); pBt->inStmt = 0; } @@ -28613,10 +30265,11 @@ void *pArg, /* First arg to xCompare() */ BtCursor **ppCur /* Write new cursor here */ ){ int rc; sqlite3BtreeEnter(p); + p->pBt->db = p->db; rc = btreeCursor(p, iTable, wrFlag, xCmp, pArg, ppCur); sqlite3BtreeLeave(p); return rc; } @@ -28628,10 +30281,11 @@ SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){ BtShared *pBt = pCur->pBt; Btree *pBtree = pCur->pBtree; sqlite3BtreeEnter(pBtree); + pBt->db = pBtree->db; clearCursorPosition(pCur); if( pCur->pPrev ){ pCur->pPrev->pNext = pCur->pNext; }else{ pBt->pCursor = pCur->pNext; @@ -28774,11 +30428,11 @@ ** ** If an error occurs an SQLite error code is returned. Otherwise: ** ** Unless pPgnoNext is NULL, the page number of the next overflow ** page in the linked list is written to *pPgnoNext. If page ovfl -** is the last page in it's linked list, *pPgnoNext is set to zero. +** is the last page in its linked list, *pPgnoNext is set to zero. ** ** If ppPage is not NULL, *ppPage is set to the MemPage* handle ** for page ovfl. The underlying pager page may have been requested ** with the noContent flag set, so the page data accessable via ** this handle may not be trusted. @@ -29362,11 +31016,11 @@ */ SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){ int rc; assert( cursorHoldsMutex(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ if( pCur->eState==CURSOR_INVALID ){ assert( pCur->pPage->nCell==0 ); *pRes = 1; @@ -29386,11 +31040,11 @@ */ SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){ int rc; assert( cursorHoldsMutex(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); rc = moveToRoot(pCur); if( rc==SQLITE_OK ){ if( CURSOR_INVALID==pCur->eState ){ assert( pCur->pPage->nCell==0 ); *pRes = 1; @@ -29439,11 +31093,11 @@ int *pRes /* Search result flag */ ){ int rc; assert( cursorHoldsMutex(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); rc = moveToRoot(pCur); if( rc ){ return rc; } assert( pCur->pPage ); @@ -29566,12 +31220,12 @@ /* ** Return the database connection handle for a cursor. */ SQLITE_PRIVATE sqlite3 *sqlite3BtreeCursorDb(const BtCursor *pCur){ - assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); - return pCur->pBtree->pSqlite; + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); + return pCur->pBtree->db; } /* ** Advance the cursor to the next entry in the database. If ** successful then set *pRes=0. If the cursor @@ -29941,10 +31595,11 @@ ** becomes a new pointer-map page, the second is used by the caller. */ TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno)); assert( *pPgno!=PENDING_BYTE_PAGE(pBt) ); (*pPgno)++; + if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; } } if( pBt->nTrunc ){ pBt->nTrunc = *pPgno; } #endif @@ -31097,14 +32752,14 @@ pCell -= 4; pTemp = &aSpace[iSpace]; iSpace += sz; assert( iSpace<=pBt->pageSize*5 ); /* Obscure case for non-leaf-data trees: If the cell at pCell was - ** previously stored on a leaf node, and it's reported size was 4 + ** previously stored on a leaf node, and its reported size was 4 ** bytes, then it may actually be smaller than this ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of - ** any cell). But it's important to pass the correct size to + ** any cell). But it is important to pass the correct size to ** insertCell(), so reparse the cell now. ** ** Note that this can never happen in an SQLite data file, as all ** cells are at least 4 bytes. It only happens in b-trees used ** to evaluate "IN (SELECT ...)" and similar clauses. @@ -31388,18 +33043,18 @@ ** pointing to non-existant pages or cells. */ static int checkReadLocks(Btree *pBtree, Pgno pgnoRoot, BtCursor *pExclude){ BtCursor *p; BtShared *pBt = pBtree->pBt; - sqlite3 *db = pBtree->pSqlite; + sqlite3 *db = pBtree->db; assert( sqlite3BtreeHoldsMutex(pBtree) ); for(p=pBt->pCursor; p; p=p->pNext){ if( p==pExclude ) continue; if( p->eState!=CURSOR_VALID ) continue; if( p->pgnoRoot!=pgnoRoot ) continue; if( p->wrFlag==0 ){ - sqlite3 *dbOther = p->pBtree->pSqlite; + sqlite3 *dbOther = p->pBtree->db; if( dbOther==0 || (dbOther!=db && (dbOther->flags & SQLITE_ReadUncommitted)==0) ){ return SQLITE_LOCKED; } }else if( p->pPage->pgno!=p->pgnoRoot ){ @@ -31552,11 +33207,11 @@ (rc = sqlite3PagerWrite(pPage->pDbPage))!=0 ){ return rc; } - /* Locate the cell within it's page and leave pCell pointing to the + /* Locate the cell within its page and leave pCell pointing to the ** data. The clearCell() call frees any overflow pages associated with the ** cell. The cell itself is still intact. */ pCell = findCell(pPage, pCur->idx); if( !pPage->leaf ){ @@ -31575,22 +33230,20 @@ ** next Cell after the one to be deleted is guaranteed to exist and ** to be a leaf so we can use it. */ BtCursor leafCur; unsigned char *pNext; - int szNext; /* The compiler warning is wrong: szNext is always - ** initialized before use. Adding an extra initialization - ** to silence the compiler slows down the code. */ int notUsed; unsigned char *tempCell = 0; assert( !pPage->leafData ); sqlite3BtreeGetTempCursor(pCur, &leafCur); rc = sqlite3BtreeNext(&leafCur, ¬Used); if( rc==SQLITE_OK ){ rc = sqlite3PagerWrite(leafCur.pPage->pDbPage); } if( rc==SQLITE_OK ){ + int szNext; TRACE(("DELETE: table=%d delete internal from %d replace from leaf %d\n", pCur->pgnoRoot, pPage->pgno, leafCur.pPage->pgno)); dropCell(pPage, pCur->idx, cellSizePtr(pPage, pCell)); pNext = findCell(leafCur.pPage, leafCur.idx); szNext = cellSizePtr(leafCur.pPage, pNext); @@ -31597,21 +33250,21 @@ assert( MX_CELL_SIZE(pBt)>=szNext+4 ); tempCell = sqlite3_malloc( MX_CELL_SIZE(pBt) ); if( tempCell==0 ){ rc = SQLITE_NOMEM; } - } - if( rc==SQLITE_OK ){ - rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0); - } - if( rc==SQLITE_OK ){ - put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild); - rc = balance(pPage, 0); - } - if( rc==SQLITE_OK ){ - dropCell(leafCur.pPage, leafCur.idx, szNext); - rc = balance(leafCur.pPage, 0); + if( rc==SQLITE_OK ){ + rc = insertCell(pPage, pCur->idx, pNext-4, szNext+4, tempCell, 0); + } + if( rc==SQLITE_OK ){ + put4byte(findOverflowCell(pPage, pCur->idx), pgnoChild); + rc = balance(pPage, 0); + } + if( rc==SQLITE_OK ){ + dropCell(leafCur.pPage, leafCur.idx, szNext); + rc = balance(leafCur.pPage, 0); + } } sqlite3_free(tempCell); sqlite3BtreeReleaseTempCursor(&leafCur); }else{ TRACE(("DELETE: table=%d delete from leaf %d\n", @@ -31678,11 +33331,11 @@ pgnoRoot++; /* The new root-page may not be allocated on a pointer-map page, or the ** PENDING_BYTE page. */ - if( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || + while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) || pgnoRoot==PENDING_BYTE_PAGE(pBt) ){ pgnoRoot++; } assert( pgnoRoot>=3 ); @@ -31768,10 +33421,11 @@ return SQLITE_OK; } SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){ int rc; sqlite3BtreeEnter(p); + p->pBt->db = p->db; rc = btreeCreateTable(p, piTable, flags); sqlite3BtreeLeave(p); return rc; } @@ -31832,10 +33486,11 @@ */ SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){ int rc; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; if( p->inTrans!=TRANS_WRITE ){ rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; }else if( (rc = checkReadLocks(p, iTable, 0))!=SQLITE_OK ){ /* nothing to do */ }else if( SQLITE_OK!=(rc = saveAllCursors(pBt, iTable, 0)) ){ @@ -31975,10 +33630,11 @@ return rc; } SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){ int rc; sqlite3BtreeEnter(p); + p->pBt->db = p->db; rc = btreeDropTable(p, iTable, piMoved); sqlite3BtreeLeave(p); return rc; } @@ -31998,10 +33654,11 @@ int rc; unsigned char *pP1; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; /* Reading a meta-data value requires a read-lock on page 1 (and hence ** the sqlite_master table. We grab this lock regardless of whether or ** not the SQLITE_ReadUncommitted flag is set (the table rooted at page ** 1 is treated as a special case by queryTableLock() and lockTable()). @@ -32043,10 +33700,11 @@ BtShared *pBt = p->pBt; unsigned char *pP1; int rc; assert( idx>=1 && idx<=15 ); sqlite3BtreeEnter(p); + pBt->db = p->db; if( p->inTrans!=TRANS_WRITE ){ rc = pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR; }else{ assert( pBt->pPage1!=0 ); pP1 = pBt->pPage1->aData; @@ -32072,11 +33730,13 @@ */ SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){ /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call ** restoreOrClearCursorPosition() here. */ - MemPage *pPage = pCur->pPage; + MemPage *pPage; + restoreOrClearCursorPosition(pCur); + pPage = pCur->pPage; assert( cursorHoldsMutex(pCur) ); assert( pPage->pBt==pCur->pBt ); return pPage ? pPage->aData[pPage->hdrOffset] : 0; } @@ -32431,10 +34091,11 @@ int nRef; IntegrityCk sCheck; BtShared *pBt = p->pBt; sqlite3BtreeEnter(p); + pBt->db = p->db; nRef = sqlite3PagerRefcount(pBt->pPager); if( lockBtreeWithRetry(p)!=SQLITE_OK ){ sqlite3BtreeLeave(p); return sqlite3StrDup("Unable to acquire a read lock on the database"); } @@ -32457,11 +34118,11 @@ sCheck.anRef = sqlite3_malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) ); if( !sCheck.anRef ){ unlockBtreeIfUnused(pBt); *pnErr = 1; sqlite3BtreeLeave(p); - return sqlite3MPrintf(p->pSqlite, "Unable to malloc %d bytes", + return sqlite3MPrintf(p->db, "Unable to malloc %d bytes", (sCheck.nPage+1)*sizeof(sCheck.anRef[0])); } for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; } i = PENDING_BYTE_PAGE(pBt); if( i<=sCheck.nPage ){ @@ -32574,10 +34235,13 @@ int rc = SQLITE_OK; Pgno i, nPage, nToPage, iSkip; BtShared *pBtTo = pTo->pBt; BtShared *pBtFrom = pFrom->pBt; + pBtTo->db = pTo->db; + pBtFrom->db = pFrom->db; + if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){ return SQLITE_ERROR; } if( pBtTo->pCursor ) return SQLITE_BUSY; @@ -32636,11 +34300,11 @@ /* ** Return non-zero if a transaction is active. */ SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){ - assert( p==0 || sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( p==0 || sqlite3_mutex_held(p->db->mutex) ); return (p && (p->inTrans==TRANS_WRITE)); } /* ** Return non-zero if a statement transaction is active. @@ -32652,17 +34316,17 @@ /* ** Return non-zero if a read (or write) transaction is active. */ SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){ - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); return (p && (p->inTrans!=TRANS_NONE)); } /* ** This function returns a pointer to a blob of memory associated with -** a single shared-btree. The memory is used by client code for it's own +** a single shared-btree. The memory is used by client code for its own ** purposes (for example, to store a high-level schema associated with ** the shared-btree). The btree layer manages reference counting issues. ** ** The first time this is called on a shared-btree, nBytes bytes of memory ** are allocated, zeroed, and returned to the caller. For each subsequent @@ -32689,11 +34353,11 @@ ** Return true if another user of the same shared btree as the argument ** handle holds an exclusive lock on the sqlite_master table. */ SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){ int rc; - assert( sqlite3_mutex_held(p->pSqlite->mutex) ); + assert( sqlite3_mutex_held(p->db->mutex) ); sqlite3BtreeEnter(p); rc = (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK); sqlite3BtreeLeave(p); return rc; } @@ -32726,11 +34390,11 @@ ** Only the data content may only be modified, it is not possible ** to change the length of the data stored. */ SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){ assert( cursorHoldsMutex(pCsr) ); - assert( sqlite3_mutex_held(pCsr->pBtree->pSqlite->mutex) ); + assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) ); assert(pCsr->isIncrblobHandle); if( pCsr->eState>=CURSOR_REQUIRESEEK ){ if( pCsr->eState==CURSOR_FAULT ){ return pCsr->skip; }else{ @@ -32768,11 +34432,11 @@ ** accessPayload() (the worker function for sqlite3BtreeData() and ** sqlite3BtreePutData()). */ SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){ assert( cursorHoldsMutex(pCur) ); - assert( sqlite3_mutex_held(pCur->pBtree->pSqlite->mutex) ); + assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) ); assert(!pCur->isIncrblobHandle); assert(!pCur->aOverflow); pCur->isIncrblobHandle = 1; } #endif @@ -33180,10 +34844,42 @@ p->xDel = 0; } } /* +** Convert a 64-bit IEEE double into a 64-bit signed integer. +** If the double is too large, return 0x8000000000000000. +** +** Most systems appear to do this simply by assigning +** variables and without the extra range tests. But +** there are reports that windows throws an expection +** if the floating point value is out of range. (See ticket #2880.) +** Because we do not completely understand the problem, we will +** take the conservative approach and always do range tests +** before attempting the conversion. +*/ +static i64 doubleToInt64(double r){ + /* + ** Many compilers we encounter do not define constants for the + ** minimum and maximum 64-bit integers, or they define them + ** inconsistently. And many do not understand the "LL" notation. + ** So we define our own static constants here using nothing + ** larger than a 32-bit integer constant. + */ + static const i64 maxInt = (((i64)0x7fffffff)<<32)|0xffffffff; + static const i64 minInt = ((i64)0x80000000)<<32; + + if( r<(double)minInt ){ + return minInt; + }else if( r>(double)maxInt ){ + return minInt; + }else{ + return (i64)r; + } +} + +/* ** Return some kind of integer value which is the best we can do ** at representing the value that *pMem describes as an integer. ** If pMem is an integer, then the value is exact. If pMem is ** a floating-point then the value returned is the integer part. ** If pMem is a string or blob, then we make an attempt to convert @@ -33196,11 +34892,11 @@ assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); flags = pMem->flags; if( flags & MEM_Int ){ return pMem->u.i; }else if( flags & MEM_Real ){ - return (i64)pMem->r; + return doubleToInt64(pMem->r); }else if( flags & (MEM_Str|MEM_Blob) ){ i64 value; pMem->flags |= MEM_Str; if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8) || sqlite3VdbeMemNulTerminate(pMem) ){ @@ -33246,12 +34942,13 @@ ** MEM_Int if we can. */ SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){ assert( pMem->flags & MEM_Real ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); - pMem->u.i = pMem->r; - if( ((double)pMem->u.i)==pMem->r ){ + + pMem->u.i = doubleToInt64(pMem->r); + if( pMem->r==(double)pMem->u.i ){ pMem->flags |= MEM_Int; } } /* @@ -33286,11 +34983,11 @@ i64 i; assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ); assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 ); assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); r1 = sqlite3VdbeRealValue(pMem); - i = (i64)r1; + i = doubleToInt64(r1); r2 = (double)i; if( r1==r2 ){ sqlite3VdbeMemIntegerify(pMem); }else{ pMem->r = r1; @@ -33366,15 +35063,16 @@ return 0; } /* ** Make an shallow copy of pFrom into pTo. Prior contents of -** pTo are overwritten. The pFrom->z field is not duplicated. If +** pTo are freed. The pFrom->z field is not duplicated. If ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z ** and flags gets srcType (either MEM_Ephem or MEM_Static). */ SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){ + sqlite3VdbeMemRelease(pTo); memcpy(pTo, pFrom, sizeof(*pFrom)-sizeof(pFrom->zShort)); pTo->xDel = 0; if( pTo->flags & (MEM_Str|MEM_Blob) ){ pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short|MEM_Ephem); assert( srcType==MEM_Ephem || srcType==MEM_Static ); @@ -33386,13 +35084,10 @@ ** Make a full copy of pFrom into pTo. Prior contents of pTo are ** freed before the copy is made. */ SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){ int rc; - if( pTo->flags & MEM_Dyn ){ - sqlite3VdbeMemRelease(pTo); - } sqlite3VdbeMemShallowCopy(pTo, pFrom, MEM_Ephem); if( pTo->flags & MEM_Ephem ){ rc = sqlite3VdbeMemMakeWriteable(pTo); }else{ rc = SQLITE_OK; @@ -33402,16 +35097,13 @@ /* ** Transfer the contents of pFrom to pTo. Any existing value in pTo is ** freed. If pFrom contains ephemeral data, a copy is made. ** -** pFrom contains an SQL NULL when this routine returns. SQLITE_NOMEM -** might be returned if pFrom held ephemeral data and we were unable -** to allocate enough space to make a copy. -*/ -SQLITE_PRIVATE int sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ - int rc; +** pFrom contains an SQL NULL when this routine returns. +*/ +SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){ assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) ); assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) ); assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db ); if( pTo->flags & MEM_Dyn ){ sqlite3VdbeMemRelease(pTo); @@ -33420,16 +35112,10 @@ if( pFrom->flags & MEM_Short ){ pTo->z = pTo->zShort; } pFrom->flags = MEM_Null; pFrom->xDel = 0; - if( pTo->flags & MEM_Ephem ){ - rc = sqlite3VdbeMemMakeWriteable(pTo); - }else{ - rc = SQLITE_OK; - } - return rc; } /* ** Change the value of a Mem to be a string or a BLOB. */ @@ -33693,11 +35379,11 @@ } return SQLITE_OK; } -#ifndef NDEBUG +#if 0 /* ** Perform various checks on the memory cell pMem. An assert() will ** fail if pMem is internally inconsistent. */ SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){ @@ -33804,11 +35490,11 @@ /* ** Create a new sqlite3_value object, containing the value of pExpr. ** ** This only works for very simple expressions that consist of one constant -** token (i.e. "5", "5.1", "NULL", "'a string'"). If the expression can +** token (i.e. "5", "5.1", "'a string'"). If the expression can ** be converted directly into a value, then the value is allocated and ** a pointer written to *ppVal. The caller is responsible for deallocating ** the value by passing it to sqlite3ValueFree() later on. If the expression ** cannot be converted to a value, then *ppVal is set to NULL. */ @@ -33847,17 +35533,19 @@ } } #ifndef SQLITE_OMIT_BLOB_LITERAL else if( op==TK_BLOB ){ int nVal; + 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]=='\'' ); pVal = sqlite3ValueNew(db); - zVal = sqlite3StrNDup((char*)pExpr->token.z+1, pExpr->token.n-1); - if( !zVal || !pVal ) goto no_mem; - sqlite3Dequote(zVal); - nVal = strlen(zVal)/2; - sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal), nVal,0,sqlite3_free); - sqlite3_free(zVal); + nVal = pExpr->token.n - 3; + zVal = (char*)pExpr->token.z + 2; + sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2, + 0, sqlite3_free); } #endif *ppVal = pVal; return SQLITE_OK; @@ -34036,17 +35724,17 @@ ** ** p Pointer to the VDBE ** ** op The opcode for this instruction ** -** p1, p2 First two of the three possible operands. +** p1, p2, p3 Operands ** ** Use the sqlite3VdbeResolveLabel() function to fix an address and -** the sqlite3VdbeChangeP3() function to change the value of the P3 +** the sqlite3VdbeChangeP4() function to change the value of the P4 ** operand. */ -SQLITE_PRIVATE int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){ +SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){ int i; VdbeOp *pOp; i = p->nOp; assert( p->magic==VDBE_MAGIC_INIT ); @@ -34059,25 +35747,44 @@ p->nOp++; pOp = &p->aOp[i]; pOp->opcode = op; pOp->p1 = p1; pOp->p2 = p2; - pOp->p3 = 0; - pOp->p3type = P3_NOTUSED; + pOp->p3 = p3; + pOp->p4.p = 0; + pOp->p4type = P4_NOTUSED; p->expired = 0; #ifdef SQLITE_DEBUG if( sqlite3_vdbe_addop_trace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]); #endif return i; } - -/* -** Add an opcode that includes the p3 value. -*/ -SQLITE_PRIVATE int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){ - int addr = sqlite3VdbeAddOp(p, op, p1, p2); - sqlite3VdbeChangeP3(p, addr, zP3, p3type); +SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){ + return sqlite3VdbeAddOp3(p, op, 0, 0, 0); +} +SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){ + return sqlite3VdbeAddOp3(p, op, p1, 0, 0); +} +SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){ + return sqlite3VdbeAddOp3(p, op, p1, p2, 0); +} + + +/* +** Add an opcode that includes the p4 value as a pointer. +*/ +SQLITE_PRIVATE int sqlite3VdbeAddOp4( + Vdbe *p, /* Add the opcode to this VM */ + int op, /* The new opcode */ + int p1, /* The P1 operand */ + int p2, /* The P2 operand */ + int p3, /* The P3 operand */ + const char *zP4, /* The P4 operand */ + int p4type /* P4 operand type */ +){ + int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3); + sqlite3VdbeChangeP4(p, addr, zP4, p4type); return addr; } /* ** Create a new symbolic label for an instruction that has yet to be @@ -34121,83 +35828,46 @@ p->aLabel[j] = p->nOp; } } /* -** Return non-zero if opcode 'op' is guarenteed not to push more values -** onto the VDBE stack than it pops off. -*/ -static int opcodeNoPush(u8 op){ - /* The 10 NOPUSH_MASK_n constants are defined in the automatically - ** generated header file opcodes.h. Each is a 16-bit bitmask, one - ** bit corresponding to each opcode implemented by the virtual - ** machine in vdbe.c. The bit is true if the word "no-push" appears - ** in a comment on the same line as the "case OP_XXX:" in - ** sqlite3VdbeExec() in vdbe.c. - ** - ** If the bit is true, then the corresponding opcode is guarenteed not - ** to grow the stack when it is executed. Otherwise, it may grow the - ** stack by at most one entry. - ** - ** NOPUSH_MASK_0 corresponds to opcodes 0 to 15. NOPUSH_MASK_1 contains - ** one bit for opcodes 16 to 31, and so on. - ** - ** 16-bit bitmasks (rather than 32-bit) are specified in opcodes.h - ** because the file is generated by an awk program. Awk manipulates - ** all numbers as floating-point and we don't want to risk a rounding - ** error if someone builds with an awk that uses (for example) 32-bit - ** IEEE floats. - */ - static const u32 masks[5] = { - NOPUSH_MASK_0 + (((unsigned)NOPUSH_MASK_1)<<16), - NOPUSH_MASK_2 + (((unsigned)NOPUSH_MASK_3)<<16), - NOPUSH_MASK_4 + (((unsigned)NOPUSH_MASK_5)<<16), - NOPUSH_MASK_6 + (((unsigned)NOPUSH_MASK_7)<<16), - NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16) - }; - assert( op<32*5 ); - return (masks[op>>5] & (1<<(op&0x1F))); -} - -#ifndef NDEBUG -SQLITE_PRIVATE int sqlite3VdbeOpcodeNoPush(u8 op){ - return opcodeNoPush(op); -} -#endif - -/* -** Loop through the program looking for P2 values that are negative. -** Each such value is a label. Resolve the label by setting the P2 -** value to its correct non-zero value. +** Loop through the program looking for P2 values that are negative +** on jump instructions. Each such value is a label. Resolve the +** label by setting the P2 value to its correct non-zero value. ** ** This routine is called once after all opcodes have been inserted. ** ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array. ** -** The integer *pMaxStack is set to the maximum number of vdbe stack -** entries that static analysis reveals this program might need. -** ** This routine also does the following optimization: It scans for -** Halt instructions where P1==SQLITE_CONSTRAINT or P2==OE_Abort or for -** IdxInsert instructions where P2!=0. If no such instruction is -** found, then every Statement instruction is changed to a Noop. In -** this way, we avoid creating the statement journal file unnecessarily. -*/ -static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs, int *pMaxStack){ - int i; - int nMaxArgs = 0; - int nMaxStack = p->nOp; +** instructions that might cause a statement rollback. Such instructions +** are: +** +** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort. +** * OP_Destroy +** * OP_VUpdate +** * OP_VRename +** +** If no such instruction is found, then every Statement instruction +** is changed to a Noop. In this way, we avoid creating the statement +** journal file unnecessarily. +*/ +static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){ + int i; + int nMaxArgs = 0; Op *pOp; int *aLabel = p->aLabel; int doesStatementRollback = 0; int hasStatementBegin = 0; for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){ u8 opcode = pOp->opcode; - if( opcode==OP_Function || opcode==OP_AggStep + if( opcode==OP_Function ){ + if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5; + }else if( opcode==OP_AggStep #ifndef SQLITE_OMIT_VIRTUALTABLE || opcode==OP_VUpdate #endif ){ if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2; @@ -34206,34 +35876,33 @@ if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){ doesStatementRollback = 1; } }else if( opcode==OP_Statement ){ hasStatementBegin = 1; + }else if( opcode==OP_Destroy ){ + doesStatementRollback = 1; #ifndef SQLITE_OMIT_VIRTUALTABLE }else if( opcode==OP_VUpdate || opcode==OP_VRename ){ doesStatementRollback = 1; }else if( opcode==OP_VFilter ){ int n; assert( p->nOp - i >= 3 ); - assert( pOp[-2].opcode==OP_Integer ); - n = pOp[-2].p1; + assert( pOp[-1].opcode==OP_Integer ); + n = pOp[-1].p1; if( n>nMaxArgs ) nMaxArgs = n; #endif } - if( opcodeNoPush(opcode) ){ - nMaxStack--; - } - - if( pOp->p2>=0 ) continue; - assert( -1-pOp->p2<p->nLabel ); - pOp->p2 = aLabel[-1-pOp->p2]; + + if( sqlite3VdbeOpcodeHasProperty(opcode, OPFLG_JUMP) && pOp->p2<0 ){ + assert( -1-pOp->p2<p->nLabel ); + pOp->p2 = aLabel[-1-pOp->p2]; + } } sqlite3_free(p->aLabel); p->aLabel = 0; *pMaxFuncArgs = nMaxArgs; - *pMaxStack = nMaxStack; /* If we never rollback a statement transaction, then statement ** transactions are not needed. So change every OP_Statement ** opcode into an OP_Noop. This avoid a call to sqlite3OsOpenExclusive() ** which can be expensive on some platforms. @@ -34275,13 +35944,19 @@ for(i=0; i<nOp; i++, pIn++){ int p2 = pIn->p2; VdbeOp *pOut = &p->aOp[i+addr]; pOut->opcode = pIn->opcode; pOut->p1 = pIn->p1; - pOut->p2 = p2<0 ? addr + ADDR(p2) : p2; + if( p2<0 && sqlite3VdbeOpcodeHasProperty(pOut->opcode, OPFLG_JUMP) ){ + pOut->p2 = addr + ADDR(p2); + }else{ + pOut->p2 = p2; + } pOut->p3 = pIn->p3; - pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED; + pOut->p4type = P4_NOTUSED; + pOut->p4.p = 0; + pOut->p5 = 0; #ifdef SQLITE_DEBUG if( sqlite3_vdbe_addop_trace ){ sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]); } #endif @@ -34307,14 +35982,35 @@ /* ** Change the value of the P2 operand for a specific instruction. ** This routine is useful for setting a jump destination. */ SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){ - assert( val>=0 ); assert( p==0 || p->magic==VDBE_MAGIC_INIT ); if( p && addr>=0 && p->nOp>addr && p->aOp ){ p->aOp[addr].p2 = val; + } +} + +/* +** Change the value of the P3 operand for a specific instruction. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){ + assert( p==0 || p->magic==VDBE_MAGIC_INIT ); + if( p && addr>=0 && p->nOp>addr && p->aOp ){ + p->aOp[addr].p3 = val; + } +} + +/* +** Change the value of the P5 operand for the most recently +** added operation. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){ + assert( p==0 || p->magic==VDBE_MAGIC_INIT ); + if( p && p->aOp ){ + assert( p->nOp>0 ); + p->aOp[p->nOp-1].p5 = val; } } /* ** Change the P2 operand of instruction addr so that it points to @@ -34334,36 +36030,36 @@ sqlite3_free(pDef); } } /* -** Delete a P3 value if necessary. -*/ -static void freeP3(int p3type, void *p3){ +** Delete a P4 value if necessary. +*/ +static void freeP4(int p4type, void *p3){ if( p3 ){ - switch( p3type ){ - case P3_REAL: - case P3_INT64: - case P3_MPRINTF: - case P3_DYNAMIC: - case P3_KEYINFO: - case P3_KEYINFO_HANDOFF: { + switch( p4type ){ + case P4_REAL: + case P4_INT64: + case P4_MPRINTF: + case P4_DYNAMIC: + case P4_KEYINFO: + case P4_KEYINFO_HANDOFF: { sqlite3_free(p3); break; } - case P3_VDBEFUNC: { + case P4_VDBEFUNC: { VdbeFunc *pVdbeFunc = (VdbeFunc *)p3; freeEphemeralFunction(pVdbeFunc->pFunc); sqlite3VdbeDeleteAuxData(pVdbeFunc, 0); sqlite3_free(pVdbeFunc); break; } - case P3_FUNCDEF: { + case P4_FUNCDEF: { freeEphemeralFunction((FuncDef*)p3); break; } - case P3_MEM: { + case P4_MEM: { sqlite3ValueFree((sqlite3_value*)p3); break; } } } @@ -34375,108 +36071,122 @@ */ SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){ if( p && p->aOp ){ VdbeOp *pOp = &p->aOp[addr]; while( N-- ){ - freeP3(pOp->p3type, pOp->p3); + freeP4(pOp->p4type, pOp->p4.p); memset(pOp, 0, sizeof(pOp[0])); pOp->opcode = OP_Noop; pOp++; } } } /* -** Change the value of the P3 operand for a specific instruction. +** Change the value of the P4 operand for a specific instruction. ** This routine is useful when a large program is loaded from a ** static array using sqlite3VdbeAddOpList but we want to make a ** few minor changes to the program. ** -** If n>=0 then the P3 operand is dynamic, meaning that a copy of +** If n>=0 then the P4 operand is dynamic, meaning that a copy of ** the string is made into memory obtained from sqlite3_malloc(). -** A value of n==0 means copy bytes of zP3 up to and including the -** first null byte. If n>0 then copy n+1 bytes of zP3. -** -** If n==P3_KEYINFO it means that zP3 is a pointer to a KeyInfo structure. +** A value of n==0 means copy bytes of zP4 up to and including the +** first null byte. If n>0 then copy n+1 bytes of zP4. +** +** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure. ** A copy is made of the KeyInfo structure into memory obtained from ** sqlite3_malloc, to be freed when the Vdbe is finalized. -** n==P3_KEYINFO_HANDOFF indicates that zP3 points to a KeyInfo structure +** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure ** stored in memory that the caller has obtained from sqlite3_malloc. The ** caller should not free the allocation, it will be freed when the Vdbe is ** finalized. ** -** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points +** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points ** to a string or structure that is guaranteed to exist for the lifetime of ** the Vdbe. In these cases we can just copy the pointer. ** -** If addr<0 then change P3 on the most recently inserted instruction. -*/ -SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){ +** If addr<0 then change P4 on the most recently inserted instruction. +*/ +SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){ Op *pOp; - assert( p==0 || p->magic==VDBE_MAGIC_INIT ); - if( p==0 || p->aOp==0 || p->db->mallocFailed ){ - if (n != P3_KEYINFO) { - freeP3(n, (void*)*(char**)&zP3); - } - return; - } - if( addr<0 || addr>=p->nOp ){ + assert( p!=0 ); + assert( p->magic==VDBE_MAGIC_INIT ); + if( p->aOp==0 || p->db->mallocFailed ){ + if (n != P4_KEYINFO) { + freeP4(n, (void*)*(char**)&zP4); + } + return; + } + assert( addr<p->nOp ); + if( addr<0 ){ addr = p->nOp - 1; if( addr<0 ) return; } pOp = &p->aOp[addr]; - freeP3(pOp->p3type, pOp->p3); - pOp->p3 = 0; - if( zP3==0 ){ - pOp->p3 = 0; - pOp->p3type = P3_NOTUSED; - }else if( n==P3_KEYINFO ){ + freeP4(pOp->p4type, pOp->p4.p); + pOp->p4.p = 0; + if( n==P4_INT32 ){ + pOp->p4.i = (int)zP4; + pOp->p4type = n; + }else if( zP4==0 ){ + pOp->p4.p = 0; + pOp->p4type = P4_NOTUSED; + }else if( n==P4_KEYINFO ){ KeyInfo *pKeyInfo; int nField, nByte; - nField = ((KeyInfo*)zP3)->nField; + nField = ((KeyInfo*)zP4)->nField; nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField; pKeyInfo = sqlite3_malloc( nByte ); - pOp->p3 = (char*)pKeyInfo; + pOp->p4.pKeyInfo = pKeyInfo; if( pKeyInfo ){ - unsigned char *aSortOrder; - memcpy(pKeyInfo, zP3, nByte); + memcpy(pKeyInfo, zP4, nByte); + /* In the current implementation, P4_KEYINFO is only ever used on + ** KeyInfo structures that have no aSortOrder component. Elements + ** with an aSortOrder always use P4_KEYINFO_HANDOFF. So we do not + ** need to bother with duplicating the aSortOrder. */ + assert( pKeyInfo->aSortOrder==0 ); +#if 0 aSortOrder = pKeyInfo->aSortOrder; if( aSortOrder ){ pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField]; memcpy(pKeyInfo->aSortOrder, aSortOrder, nField); } - pOp->p3type = P3_KEYINFO; +#endif + pOp->p4type = P4_KEYINFO; }else{ p->db->mallocFailed = 1; - pOp->p3type = P3_NOTUSED; - } - }else if( n==P3_KEYINFO_HANDOFF ){ - pOp->p3 = (char*)zP3; - pOp->p3type = P3_KEYINFO; + pOp->p4type = P4_NOTUSED; + } + }else if( n==P4_KEYINFO_HANDOFF ){ + pOp->p4.p = (void*)zP4; + pOp->p4type = P4_KEYINFO; }else if( n<0 ){ - pOp->p3 = (char*)zP3; - pOp->p3type = n; - }else{ - if( n==0 ) n = strlen(zP3); - pOp->p3 = sqlite3DbStrNDup(p->db, zP3, n); - pOp->p3type = P3_DYNAMIC; - } -} - -#ifndef NDEBUG -/* -** Replace the P3 field of the most recently coded instruction with -** comment text. + pOp->p4.p = (void*)zP4; + pOp->p4type = n; + }else{ + if( n==0 ) n = strlen(zP4); + pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n); + pOp->p4type = P4_DYNAMIC; + } +} + +#ifndef NDEBUG +/* +** Change the comment on the the most recently coded instruction. */ SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){ va_list ap; assert( p->nOp>0 || p->aOp==0 ); - assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || p->db->mallocFailed ); - va_start(ap, zFormat); - sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(p->db, zFormat, ap), P3_DYNAMIC); - va_end(ap); + assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed ); + if( p->nOp ){ + char **pz = &p->aOp[p->nOp-1].zComment; + va_start(ap, zFormat); + sqlite3_free(*pz); + *pz = sqlite3VMPrintf(p->db, zFormat, ap); + va_end(ap); + } } #endif /* ** Return the opcode for a given address. @@ -34488,20 +36198,20 @@ } #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \ || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) /* -** Compute a string that describes the P3 parameter for an opcode. +** Compute a string that describes the P4 parameter for an opcode. ** Use zTemp for any required temporary buffer space. */ -static char *displayP3(Op *pOp, char *zTemp, int nTemp){ - char *zP3; +static char *displayP4(Op *pOp, char *zTemp, int nTemp){ + char *zP4 = zTemp; assert( nTemp>=20 ); - switch( pOp->p3type ){ - case P3_KEYINFO: { + switch( pOp->p4type ){ + case P4_KEYINFO: { int i, j; - KeyInfo *pKeyInfo = (KeyInfo*)pOp->p3; + KeyInfo *pKeyInfo = pOp->p4.pKeyInfo; sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField); i = strlen(zTemp); for(j=0; j<pKeyInfo->nField; j++){ CollSeq *pColl = pKeyInfo->aColl[j]; if( pColl ){ @@ -34522,52 +36232,63 @@ } } zTemp[i++] = ')'; zTemp[i] = 0; assert( i<nTemp ); - zP3 = zTemp; - break; - } - case P3_COLLSEQ: { - CollSeq *pColl = (CollSeq*)pOp->p3; + break; + } + case P4_COLLSEQ: { + CollSeq *pColl = pOp->p4.pColl; sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName); - zP3 = zTemp; - break; - } - case P3_FUNCDEF: { - FuncDef *pDef = (FuncDef*)pOp->p3; + break; + } + case P4_FUNCDEF: { + FuncDef *pDef = pOp->p4.pFunc; sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg); - zP3 = zTemp; - break; - } - case P3_INT64: { - sqlite3_snprintf(nTemp, zTemp, "%lld", *(sqlite3_int64*)pOp->p3); - zP3 = zTemp; - break; - } - case P3_REAL: { - sqlite3_snprintf(nTemp, zTemp, "%.16g", *(double*)pOp->p3); - zP3 = zTemp; - break; - } -#ifndef SQLITE_OMIT_VIRTUALTABLE - case P3_VTAB: { - sqlite3_vtab *pVtab = (sqlite3_vtab*)pOp->p3; - sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule); - zP3 = zTemp; + break; + } + case P4_INT64: { + sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64); + break; + } + case P4_INT32: { + sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i); + break; + } + case P4_REAL: { + sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal); + break; + } + case P4_MEM: { + Mem *pMem = pOp->p4.pMem; + assert( (pMem->flags & MEM_Null)==0 ); + if( pMem->flags & MEM_Str ){ + zP4 = pMem->z; + }else if( pMem->flags & MEM_Int ){ + sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i); + }else if( pMem->flags & MEM_Real ){ + sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r); + } + break; + } +#ifndef SQLITE_OMIT_VIRTUALTABLE + case P4_VTAB: { + sqlite3_vtab *pVtab = pOp->p4.pVtab; + sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule); break; } #endif default: { - zP3 = pOp->p3; - if( zP3==0 || pOp->opcode==OP_Noop ){ - zP3 = ""; - } - } - } - assert( zP3!=0 ); - return zP3; + zP4 = pOp->p4.z; + if( zP4==0 ){ + zP4 = zTemp; + zTemp[0] = 0; + } + } + } + assert( zP4!=0 ); + return zP4; } #endif /* ** Declare to the Vdbe that the BTree object at db->aDb[i] is used. @@ -34588,17 +36309,23 @@ #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG) /* ** Print a single opcode. This routine is used for debugging only. */ SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){ - char *zP3; + char *zP4; char zPtr[50]; - static const char *zFormat1 = "%4d %-13s %4d %4d %s\n"; + static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n"; if( pOut==0 ) pOut = stdout; - zP3 = displayP3(pOp, zPtr, sizeof(zPtr)); - fprintf(pOut, zFormat1, - pc, sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, zP3); + zP4 = displayP4(pOp, zPtr, sizeof(zPtr)); + fprintf(pOut, zFormat1, pc, + sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5, +#ifdef SQLITE_DEBUG + pOp->zComment ? pOp->zComment : "" +#else + "" +#endif + ); fflush(pOut); } #endif /* @@ -34606,11 +36333,11 @@ */ static void releaseMemArray(Mem *p, int N){ if( p ){ while( N-->0 ){ assert( N<2 || p[0].db==p[1].db ); - sqlite3VdbeMemRelease(p++); + sqlite3VdbeMemSetNull(p++); } } } #ifndef SQLITE_OMIT_EXPLAIN @@ -34618,31 +36345,34 @@ ** Give a listing of the program in the virtual machine. ** ** The interface is the same as sqlite3VdbeExec(). But instead of ** running the code, it invokes the callback once for each instruction. ** This feature is used to implement "EXPLAIN". +** +** When p->explain==1, each instruction is listed. When +** p->explain==2, only OP_Explain instructions are listed and these +** are shown in a different format. p->explain==2 is used to implement +** EXPLAIN QUERY PLAN. */ SQLITE_PRIVATE int sqlite3VdbeList( Vdbe *p /* The VDBE */ ){ sqlite3 *db = p->db; int i; int rc = SQLITE_OK; + Mem *pMem = p->pResultSet = &p->aMem[1]; assert( p->explain ); if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE; assert( db->magic==SQLITE_MAGIC_BUSY ); assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY ); - /* Even though this opcode does not put dynamic strings onto the - ** the stack, they may become dynamic if the user calls + /* Even though this opcode does not use dynamic strings for + ** the result, result columns may become dynamic if the user calls ** sqlite3_column_text16(), causing a translation to UTF-16 encoding. */ - if( p->pTos==&p->aStack[4] ){ - releaseMemArray(p->aStack, 5); - } - p->resOnStack = 0; + releaseMemArray(pMem, p->nMem); do{ i = p->pc++; }while( i<p->nOp && p->explain==2 && p->aOp[i].opcode!=OP_Explain ); if( i>=p->nOp ){ @@ -34652,23 +36382,24 @@ p->rc = SQLITE_INTERRUPT; rc = SQLITE_ERROR; sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(p->rc), (char*)0); }else{ Op *pOp = &p->aOp[i]; - Mem *pMem = p->aStack; - pMem->flags = MEM_Int; - pMem->type = SQLITE_INTEGER; - pMem->u.i = i; /* Program counter */ - pMem++; - - pMem->flags = MEM_Static|MEM_Str|MEM_Term; - pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ - assert( pMem->z!=0 ); - pMem->n = strlen(pMem->z); - pMem->type = SQLITE_TEXT; - pMem->enc = SQLITE_UTF8; - pMem++; + if( p->explain==1 ){ + pMem->flags = MEM_Int; + pMem->type = SQLITE_INTEGER; + pMem->u.i = i; /* Program counter */ + pMem++; + + pMem->flags = MEM_Static|MEM_Str|MEM_Term; + pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */ + assert( pMem->z!=0 ); + pMem->n = strlen(pMem->z); + pMem->type = SQLITE_TEXT; + pMem->enc = SQLITE_UTF8; + pMem++; + } pMem->flags = MEM_Int; pMem->u.i = pOp->p1; /* P1 */ pMem->type = SQLITE_INTEGER; pMem++; @@ -34676,21 +36407,46 @@ pMem->flags = MEM_Int; pMem->u.i = pOp->p2; /* P2 */ pMem->type = SQLITE_INTEGER; pMem++; - pMem->flags = MEM_Ephem|MEM_Str|MEM_Term; /* P3 */ - pMem->z = displayP3(pOp, pMem->zShort, sizeof(pMem->zShort)); + if( p->explain==1 ){ + pMem->flags = MEM_Int; + pMem->u.i = pOp->p3; /* P3 */ + pMem->type = SQLITE_INTEGER; + pMem++; + } + + pMem->flags = MEM_Ephem|MEM_Str|MEM_Term; /* P4 */ + pMem->z = displayP4(pOp, pMem->zShort, sizeof(pMem->zShort)); assert( pMem->z!=0 ); pMem->n = strlen(pMem->z); pMem->type = SQLITE_TEXT; pMem->enc = SQLITE_UTF8; - - p->nResColumn = 5 - 2*(p->explain-1); - p->pTos = pMem; - p->rc = SQLITE_OK; - p->resOnStack = 1; + pMem++; + + if( p->explain==1 ){ + pMem->flags = MEM_Str|MEM_Term|MEM_Short; + pMem->n = sprintf(pMem->zShort, "%.2x", pOp->p5); /* P5 */ + pMem->z = pMem->zShort; + pMem->type = SQLITE_TEXT; + pMem->enc = SQLITE_UTF8; + pMem++; + + pMem->flags = MEM_Null; /* Comment */ +#ifdef SQLITE_DEBUG + if( pOp->zComment ){ + pMem->flags = MEM_Str|MEM_Term; + pMem->z = pOp->zComment; + pMem->n = strlen(pMem->z); + pMem->enc = SQLITE_UTF8; + } +#endif + } + + p->nResColumn = 8 - 5*(p->explain-1); + p->rc = SQLITE_OK; rc = SQLITE_ROW; } return rc; } #endif /* SQLITE_OMIT_EXPLAIN */ @@ -34701,13 +36457,13 @@ */ SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){ int nOp = p->nOp; VdbeOp *pOp; if( nOp<1 ) return; - pOp = &p->aOp[nOp-1]; - if( pOp->opcode==OP_Noop && pOp->p3!=0 ){ - const char *z = pOp->p3; + pOp = &p->aOp[0]; + if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){ + const char *z = pOp->p4.z; while( isspace(*(u8*)z) ) z++; printf("SQL: [%s]\n", z); } } #endif @@ -34719,15 +36475,15 @@ SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){ int nOp = p->nOp; VdbeOp *pOp; if( sqlite3_io_trace==0 ) return; if( nOp<1 ) return; - pOp = &p->aOp[nOp-1]; - if( pOp->opcode==OP_Noop && pOp->p3!=0 ){ + pOp = &p->aOp[0]; + if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){ int i, j; char z[1000]; - sqlite3_snprintf(sizeof(z), z, "%s", pOp->p3); + sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z); for(i=0; isspace((unsigned char)z[i]); i++){} for(j=0; z[i]; i++){ if( isspace((unsigned char)z[i]) ){ if( z[i-1]!=' ' ){ z[j++] = ' '; @@ -34774,41 +36530,32 @@ * p->aOp[] array to save memory if called when in VDBE_MAGIC_RUN * state. */ p->magic = VDBE_MAGIC_RUN; - /* No instruction ever pushes more than a single element onto the - ** stack. And the stack never grows on successive executions of the - ** same loop. So the total number of instructions is an upper bound - ** on the maximum stack depth required. (Added later:) The - ** resolveP2Values() call computes a tighter upper bound on the - ** stack size. - ** - ** Allocation all the stack space we will ever need. - */ - if( p->aStack==0 ){ + /* + ** Allocation space for registers. + */ + if( p->aMem==0 ){ int nArg; /* Maximum number of args passed to a user function. */ - int nStack; /* Maximum number of stack entries required */ - resolveP2Values(p, &nArg, &nStack); + resolveP2Values(p, &nArg); resizeOpArray(p, p->nOp); assert( nVar>=0 ); - assert( nStack<p->nOp ); - if( isExplain ){ - nStack = 10; - } - p->aStack = sqlite3DbMallocZero(db, - nStack*sizeof(p->aStack[0]) /* aStack */ + if( isExplain && nMem<10 ){ + p->nMem = nMem = 10; + } + p->aMem = sqlite3DbMallocZero(db, + nMem*sizeof(Mem) /* aMem */ + + nVar*sizeof(Mem) /* aVar */ + nArg*sizeof(Mem*) /* apArg */ - + nVar*sizeof(Mem) /* aVar */ + nVar*sizeof(char*) /* azVar */ - + nMem*sizeof(Mem) /* aMem */ - + nCursor*sizeof(Cursor*) /* apCsr */ + + nCursor*sizeof(Cursor*) + 1 /* apCsr */ ); if( !db->mallocFailed ){ - p->aMem = &p->aStack[nStack]; - p->nMem = nMem; - p->aVar = &p->aMem[nMem]; + p->aMem--; /* aMem[] goes from 1..nMem */ + p->nMem = nMem; /* not from 0..nMem-1 */ + p->aVar = &p->aMem[nMem+1]; p->nVar = nVar; p->okVar = 0; p->apArg = (Mem**)&p->aVar[nVar]; p->azVar = (char**)&p->apArg[nArg]; p->apCsr = (Cursor**)&p->azVar[nVar]; @@ -34815,27 +36562,28 @@ p->nCursor = nCursor; for(n=0; n<nVar; n++){ p->aVar[n].flags = MEM_Null; p->aVar[n].db = db; } - for(n=0; n<nStack; n++){ - p->aStack[n].db = db; - } - } - } - for(n=0; n<p->nMem; n++){ - p->aMem[n].flags = MEM_Null; - p->aMem[n].db = db; - } - - p->pTos = &p->aStack[-1]; + for(n=1; n<=nMem; n++){ + p->aMem[n].flags = MEM_Null; + p->aMem[n].db = db; + } + } + } +#ifdef SQLITE_DEBUG + for(n=1; n<p->nMem; n++){ + assert( p->aMem[n].db==db ); + assert( p->aMem[n].flags==MEM_Null ); + } +#endif + p->pc = -1; p->rc = SQLITE_OK; p->uniqueCnt = 0; p->returnDepth = 0; p->errorAction = OE_Abort; - p->popStack = 0; p->explain |= isExplain; p->magic = VDBE_MAGIC_RUN; p->nChange = 0; p->cacheCtr = 1; p->minWriteFileFormat = 255; @@ -34868,13 +36616,13 @@ #ifndef SQLITE_OMIT_VIRTUALTABLE if( pCx->pVtabCursor ){ sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor; const sqlite3_module *pModule = pCx->pModule; p->inVtabMethod = 1; - sqlite3SafetyOff(p->db); + (void)sqlite3SafetyOff(p->db); pModule->xClose(pVtabCursor); - sqlite3SafetyOn(p->db); + (void)sqlite3SafetyOn(p->db); p->inVtabMethod = 0; } #endif sqlite3_free(pCx->pData); sqlite3_free(pCx->aType); @@ -34904,16 +36652,12 @@ ** sorters that were left open. It also deletes the values of ** variables in the aVar[] array. */ static void Cleanup(Vdbe *p){ int i; - if( p->aStack ){ - releaseMemArray(p->aStack, 1 + (p->pTos - p->aStack)); - p->pTos = &p->aStack[-1]; - } closeAllCursorsExceptActiveVtabs(p); - releaseMemArray(p->aMem, p->nMem); + releaseMemArray(&p->aMem[1], p->nMem); sqlite3VdbeFifoClear(&p->sFifo); if( p->contextStack ){ for(i=0; i<p->contextStackTop; i++){ sqlite3VdbeFifoClear(&p->contextStack[i].sFifo); } @@ -34922,11 +36666,11 @@ p->contextStack = 0; p->contextStackDepth = 0; p->contextStackTop = 0; sqlite3_free(p->zErrMsg); p->zErrMsg = 0; - p->resOnStack = 0; + p->pResultSet = 0; } /* ** Set the number of result columns that will be returned by this SQL ** statement. This is now set at compile time, rather than during @@ -34954,12 +36698,12 @@ ** Set the name of the idx'th column to be returned by the SQL statement. ** zName must be a pointer to a nul terminated string. ** ** This call must be made after a call to sqlite3VdbeSetNumCols(). ** -** If N==P3_STATIC it means that zName is a pointer to a constant static -** string and we can just copy the pointer. If it is P3_DYNAMIC, then +** If N==P4_STATIC it means that zName is a pointer to a constant static +** string and we can just copy the pointer. If it is P4_DYNAMIC, then ** the string is freed using sqlite3_free() when the vdbe is finished with ** it. Otherwise, N bytes of zName are copied. */ SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){ int rc; @@ -34967,16 +36711,16 @@ assert( idx<p->nResColumn ); assert( var<COLNAME_N ); if( p->db->mallocFailed ) return SQLITE_NOMEM; assert( p->aColName!=0 ); pColName = &(p->aColName[idx+var*p->nResColumn]); - if( N==P3_DYNAMIC || N==P3_STATIC ){ + if( N==P4_DYNAMIC || N==P4_STATIC ){ rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, SQLITE_STATIC); }else{ rc = sqlite3VdbeMemSetStr(pColName, zName, N, SQLITE_UTF8,SQLITE_TRANSIENT); } - if( rc==SQLITE_OK && N==P3_DYNAMIC ){ + if( rc==SQLITE_OK && N==P4_DYNAMIC ){ pColName->flags = (pColName->flags&(~MEM_Static))|MEM_Dyn; pColName->xDel = 0; } return rc; } @@ -35018,13 +36762,13 @@ } } /* If there are any write-transactions at all, invoke the commit hook */ if( needXcommit && db->xCommitCallback ){ - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); rc = db->xCommitCallback(db->pCommitArg); - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); if( rc ){ return SQLITE_CONSTRAINT; } } @@ -35294,11 +37038,11 @@ sqlite3BtreeMutexArrayEnter(&p->aMutex); /* Check for one of the special errors */ mrc = p->rc & 0xff; isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR - || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL ; + || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL; if( isSpecialError ){ /* This loop does static analysis of the query to see which of the ** following three categories it falls into: ** ** Read-only @@ -35468,13 +37212,13 @@ /* If the VM did not run to completion or if it encountered an ** error, then it might not have been halted properly. So halt ** it now. */ - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); sqlite3VdbeHalt(p); - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); /* If the VDBE has be run even partially, then transfer the error code ** and error message from the VDBE into the main database structure. But ** if the VDBE has just been set to run but has not actually executed any ** instructions yet, leave the main database error information unchanged. @@ -35503,11 +37247,10 @@ */ Cleanup(p); /* Save profiling information from this VDBE run. */ - assert( p->pTos<&p->aStack[p->pc<0?0:p->pc] || !p->aStack ); #ifdef VDBE_PROFILE { FILE *out = fopen("vdbe_profile.out", "a"); if( out ){ int i; @@ -35583,19 +37326,24 @@ } if( p->pNext ){ p->pNext->pPrev = p->pPrev; } if( p->aOp ){ - for(i=0; i<p->nOp; i++){ - Op *pOp = &p->aOp[i]; - freeP3(pOp->p3type, pOp->p3); + Op *pOp = p->aOp; + for(i=0; i<p->nOp; i++, pOp++){ + freeP4(pOp->p4type, pOp->p4.p); +#ifdef SQLITE_DEBUG + sqlite3_free(pOp->zComment); +#endif } sqlite3_free(p->aOp); } releaseMemArray(p->aVar, p->nVar); sqlite3_free(p->aLabel); - sqlite3_free(p->aStack); + if( p->aMem ){ + sqlite3_free(&p->aMem[1]); + } releaseMemArray(p->aColName, p->nResColumn*COLNAME_N); sqlite3_free(p->aColName); sqlite3_free(p->zSql); p->magic = VDBE_MAGIC_DEAD; sqlite3_free(p); @@ -35957,10 +37705,13 @@ ** This function compares the two table rows or index records specified by ** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero ** or positive integer if {nKey1, pKey1} is less than, equal to or ** greater than {nKey2, pKey2}. Both Key1 and Key2 must be byte strings ** composed by the OP_MakeRecord opcode of the VDBE. +** +** Key1 and Key2 do not have to contain the same number of fields. +** But if the lengths differ, Key2 must be the shorter of the two. */ SQLITE_PRIVATE int sqlite3VdbeRecordCompare( void *userData, int nKey1, const void *pKey1, int nKey2, const void *pKey2 @@ -36018,14 +37769,16 @@ ** treated as larger. */ if( rc==0 ){ if( pKeyInfo->incrKey ){ rc = -1; - }else if( d1<nKey1 ){ - rc = 1; - }else if( d2<nKey2 ){ - rc = -1; + }else if( !pKeyInfo->prefixIsEqual ){ + if( d1<nKey1 ){ + rc = 1; + }else if( d2<nKey2 ){ + rc = -1; /* Only occurs on a corrupt database file */ + } } }else if( pKeyInfo->aSortOrder && i<pKeyInfo->nField && pKeyInfo->aSortOrder[i] ){ rc = -rc; } @@ -36201,11 +37954,13 @@ int rc; if( pStmt==0 ){ rc = SQLITE_OK; }else{ Vdbe *v = (Vdbe*)pStmt; +#ifndef SQLITE_MUTEX_NOOP sqlite3_mutex *mutex = v->db->mutex; +#endif sqlite3_mutex_enter(mutex); rc = sqlite3VdbeFinalize(v); sqlite3_mutex_leave(mutex); } return rc; @@ -36238,16 +37993,18 @@ ** Set all the parameters in the compiled SQL statement to NULL. */ SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ int i; int rc = SQLITE_OK; - Vdbe *v = (Vdbe*)pStmt; - sqlite3_mutex_enter(v->db->mutex); +#ifndef SQLITE_MUTEX_NOOP + sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex; +#endif + sqlite3_mutex_enter(mutex); for(i=1; rc==SQLITE_OK && i<=sqlite3_bind_parameter_count(pStmt); i++){ rc = sqlite3_bind_null(pStmt, i); } - sqlite3_mutex_leave(v->db->mutex); + sqlite3_mutex_leave(mutex); return rc; } /**************************** sqlite3_value_ ******************************* @@ -36445,39 +38202,16 @@ if( db->activeVdbeCnt==0 ){ db->u1.isInterrupted = 0; } #ifndef SQLITE_OMIT_TRACE - /* Invoke the trace callback if there is one - */ - if( db->xTrace && !db->init.busy ){ - assert( p->nOp>0 ); - assert( p->aOp[p->nOp-1].opcode==OP_Noop ); - assert( p->aOp[p->nOp-1].p3!=0 ); - assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC ); - sqlite3SafetyOff(db); - db->xTrace(db->pTraceArg, p->aOp[p->nOp-1].p3); - if( sqlite3SafetyOn(db) ){ - p->rc = SQLITE_MISUSE; - return SQLITE_MISUSE; - } - } if( db->xProfile && !db->init.busy ){ double rNow; sqlite3OsCurrentTime(db->pVfs, &rNow); p->startTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0; } #endif - - /* Print a copy of SQL as it is executed if the SQL_TRACE pragma is turned - ** on in debugging mode. - */ -#ifdef SQLITE_DEBUG - if( (db->flags & SQLITE_SqlTrace)!=0 ){ - sqlite3DebugPrintf("SQL-trace: %s\n", p->aOp[p->nOp-1].p3); - } -#endif /* SQLITE_DEBUG */ db->activeVdbeCnt++; p->pc = 0; } #ifndef SQLITE_OMIT_EXPLAIN @@ -36494,21 +38228,18 @@ } #ifndef SQLITE_OMIT_TRACE /* Invoke the profile callback if there is one */ - if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy ){ + if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->nOp>0 + && p->aOp[0].opcode==OP_Trace && p->aOp[0].p4.z!=0 ){ double rNow; u64 elapseTime; sqlite3OsCurrentTime(db->pVfs, &rNow); elapseTime = (rNow - (int)rNow)*3600.0*24.0*1000000000.0 - p->startTime; - assert( p->nOp>0 ); - assert( p->aOp[p->nOp-1].opcode==OP_Noop ); - assert( p->aOp[p->nOp-1].p3!=0 ); - assert( p->aOp[p->nOp-1].p3type==P3_DYNAMIC ); - db->xProfile(db->pProfileArg, p->aOp[p->nOp-1].p3, elapseTime); + db->xProfile(db->pProfileArg, p->aOp[0].p4.z, elapseTime); } #endif sqlite3Error(p->db, rc, 0); p->rc = sqlite3ApiExit(p->db, p->rc); @@ -36721,11 +38452,11 @@ ** Return the number of values available from the current row of the ** currently executing statement pStmt. */ SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){ Vdbe *pVm = (Vdbe *)pStmt; - if( pVm==0 || !pVm->resOnStack ) return 0; + if( pVm==0 || pVm->pResultSet==0 ) return 0; return pVm->nResColumn; } /* @@ -36738,14 +38469,14 @@ Vdbe *pVm; int vals; Mem *pOut; pVm = (Vdbe *)pStmt; - if( pVm && pVm->resOnStack && i<pVm->nResColumn && i>=0 ){ + if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){ sqlite3_mutex_enter(pVm->db->mutex); vals = sqlite3_data_count(pStmt); - pOut = &pVm->pTos[(1-vals)+i]; + pOut = &pVm->pResultSet[i]; }else{ static const Mem nullMem = {{0}, 0.0, 0, "", 0, MEM_Null, SQLITE_NULL }; if( pVm->db ){ sqlite3_mutex_enter(pVm->db->mutex); sqlite3Error(pVm->db, SQLITE_RANGE, 0); @@ -37158,11 +38889,11 @@ int j; Op *pOp; for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){ if( pOp->opcode==OP_Variable ){ assert( pOp->p1>0 && pOp->p1<=p->nVar ); - p->azVar[pOp->p1-1] = pOp->p3; + p->azVar[pOp->p1-1] = pOp->p4.z; } } p->okVar = 1; } sqlite3_mutex_leave(p->db->mutex); @@ -37224,13 +38955,11 @@ if( pFrom->nVar!=pTo->nVar ){ return SQLITE_ERROR; } sqlite3_mutex_enter(pTo->db->mutex); for(i=0; rc==SQLITE_OK && i<pFrom->nVar; i++){ - sqlite3MallocDisallow(); - rc = sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); - sqlite3MallocAllow(); + sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]); } sqlite3_mutex_leave(pTo->db->mutex); assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); return rc; } @@ -37269,17 +38998,17 @@ ** ** The SQL parser generates a program which is then executed by ** the VDBE to do the work of the SQL statement. VDBE programs are ** similar in form to assembly language. The program consists of ** a linear sequence of operations. Each operation has an opcode -** and 3 operands. Operands P1 and P2 are integers. Operand P3 -** is a null-terminated string. The P2 operand must be non-negative. -** Opcodes will typically ignore one or more operands. Many opcodes -** ignore all three operands. -** -** Computation results are stored on a stack. Each entry on the -** stack is either an integer, a null-terminated string, a floating point +** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4 +** is a null-terminated string. Operand P5 is an unsigned character. +** Few opcodes use all 5 operands. +** +** Computation results are stored on a set of registers numbered beginning +** with 1 and going up to Vdbe.nMem. Each register can store +** either an integer, a null-terminated string, a floating point ** number, or the SQL "NULL" value. An inplicit conversion from one ** type to the other occurs as necessary. ** ** Most of the code in this file is taken up by the sqlite3VdbeExec() ** function which does the work of interpreting a VDBE program. @@ -37290,11 +39019,11 @@ ** documentation, headers files, or other derived files. The formatting ** of the code in this file is, therefore, important. See other comments ** in this file for details. If in doubt, do not deviate from existing ** commenting and indentation practices when changing or adding code. ** -** $Id: vdbe.c,v 1.654 2007/11/12 08:09:35 danielk1977 Exp $ +** $Id: vdbe.c,v 1.707 2008/01/31 19:34:52 drh Exp $ */ /* ** The following global variable is incremented every time a cursor ** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes. The test @@ -37329,27 +39058,42 @@ SQLITE_API int sqlite3_sort_count = 0; #endif /* ** The next global variable records the size of the largest MEM_Blob -** or MEM_Str that has appeared on the VDBE stack. The test procedures +** or MEM_Str that has been used by a VDBE opcode. The test procedures ** use this information to make sure that the zero-blob functionality ** is working correctly. This variable has no function other than to ** help verify the correct operation of the library. */ #ifdef SQLITE_TEST SQLITE_API int sqlite3_max_blobsize = 0; -#endif - -/* -** Release the memory associated with the given stack level. This +static void updateMaxBlobsize(Mem *p){ + if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){ + sqlite3_max_blobsize = p->n; + } +} +#endif + +/* +** Test a register to see if it exceeds the current maximum blob size. +** If it does, record the new maximum blob size. +*/ +#ifdef SQLITE_TEST +# define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P) +#else +# define UPDATE_MAX_BLOBSIZE(P) +#endif + +/* +** Release the memory associated with a register. This ** leaves the Mem.flags field in an inconsistent state. */ #define Release(P) if((P)->flags&MEM_Dyn){ sqlite3VdbeMemRelease(P); } /* -** Convert the given stack entity into a string if it isn't one +** Convert the given register into a string if it isn't one ** already. Return non-zero if a malloc() fails. */ #define Stringify(P, enc) \ if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \ { goto no_mem; } @@ -37372,16 +39116,16 @@ #define GetVarint(A,B) ((B = *(A))<=0x7f ? 1 : sqlite3GetVarint32(A, &B)) /* ** An ephemeral string value (signified by the MEM_Ephem flag) contains ** a pointer to a dynamically allocated string where some other entity -** is responsible for deallocating that string. Because the stack entry -** does not control the string, it might be deleted without the stack -** entry knowing it. +** is responsible for deallocating that string. Because the register +** does not control the string, it might be deleted without the register +** knowing it. ** ** This routine converts an ephemeral string into a dynamically allocated -** string that the stack entry itself controls. In other words, it +** string that the register itself controls. In other words, it ** converts an MEM_Ephem string into an MEM_Dyn string. */ #define Deephemeralize(P) \ if( ((P)->flags&MEM_Ephem)!=0 \ && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;} @@ -37391,14 +39135,14 @@ ** P if required. */ #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0) /* -** Argument pMem points at a memory cell that will be passed to a +** Argument pMem points at a regiser that will be passed to a ** user-defined function or returned to the user as the result of a query. ** The second argument, 'db_enc' is the text encoding used by the vdbe for -** stack variables. This routine sets the pMem->enc and pMem->type +** register variables. This routine sets the pMem->enc and pMem->type ** variables used by the sqlite3_value_*() routines. */ #define storeTypeInfo(A,B) _storeTypeInfo(A) static void _storeTypeInfo(Mem *pMem){ int flags = pMem->flags; @@ -37417,20 +39161,24 @@ pMem->type = SQLITE_BLOB; } } /* -** Pop the stack N times. -*/ -static void popStack(Mem **ppTos, int N){ - Mem *pTos = *ppTos; - while( N>0 ){ - N--; - Release(pTos); - pTos--; - } - *ppTos = pTos; +** Properties of opcodes. The OPFLG_INITIALIZER macro is +** created by mkopcodeh.awk during compilation. Data is obtained +** from the comments following the "case OP_xxxx:" statements in +** this file. +*/ +static unsigned char opcodeProperty[] = OPFLG_INITIALIZER; + +/* +** Return true if an opcode has any of the OPFLG_xxx properties +** specified by mask. +*/ +SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int opcode, int mask){ + assert( opcode>0 && opcode<sizeof(opcodeProperty) ); + return (opcodeProperty[opcode]&mask)!=0; } /* ** Allocate cursor number iCur. Return a pointer to it. Return NULL ** if we run out of memory. @@ -37623,10 +39371,43 @@ zBuf[k++] = 0; } } #endif +#ifdef SQLITE_DEBUG +/* +** Print the value of a register for tracing purposes: +*/ +static void memTracePrint(FILE *out, Mem *p){ + if( p->flags & MEM_Null ){ + fprintf(out, " NULL"); + }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ + fprintf(out, " si:%lld", p->u.i); + }else if( p->flags & MEM_Int ){ + fprintf(out, " i:%lld", p->u.i); + }else if( p->flags & MEM_Real ){ + fprintf(out, " r:%g", p->r); + }else{ + char zBuf[200]; + sqlite3VdbeMemPrettyPrint(p, zBuf); + fprintf(out, " "); + fprintf(out, "%s", zBuf); + } +} +static void registerTrace(FILE *out, int iReg, Mem *p){ + fprintf(out, "REG[%d] = ", iReg); + memTracePrint(out, p); + fprintf(out, "\n"); +} +#endif + +#ifdef SQLITE_DEBUG +# define REGISTER_TRACE(R,M) if(p->trace&&R>0)registerTrace(p->trace,R,M) +#else +# define REGISTER_TRACE(R,M) +#endif + #ifdef VDBE_PROFILE /* ** The following routine only works on pentium-class processors. ** It uses the RDTSC opcode to read the cycle count value out of the @@ -37693,45 +39474,39 @@ int pc; /* The program counter */ Op *pOp; /* Current operation */ int rc = SQLITE_OK; /* Value to return */ sqlite3 *db = p->db; /* The database */ u8 encoding = ENC(db); /* The database encoding */ - Mem *pTos; /* Top entry in the operand stack */ + Mem *pIn1, *pIn2, *pIn3; /* Input operands */ + Mem *pOut; /* Output operand */ + u8 opProperty; #ifdef VDBE_PROFILE unsigned long long start; /* CPU clock count at start of opcode */ int origPc; /* Program counter at start of opcode */ #endif #ifndef SQLITE_OMIT_PROGRESS_CALLBACK int nProgressOps = 0; /* Opcodes executed since progress callback. */ #endif -#ifndef NDEBUG - Mem *pStackLimit; -#endif - - if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE; - assert( db->magic==SQLITE_MAGIC_BUSY ); - pTos = p->pTos; + + assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */ + assert( db->magic==SQLITE_MAGIC_BUSY ); sqlite3BtreeMutexArrayEnter(&p->aMutex); if( p->rc==SQLITE_NOMEM ){ /* This happens if a malloc() inside a call to sqlite3_column_text() or ** sqlite3_column_text16() failed. */ goto no_mem; } assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY ); p->rc = SQLITE_OK; assert( p->explain==0 ); - if( p->popStack ){ - popStack(&pTos, p->popStack); - p->popStack = 0; - } - p->resOnStack = 0; + p->pResultSet = 0; db->busyHandler.nBusy = 0; CHECK_FOR_INTERRUPT; sqlite3VdbeIOTraceSql(p); #ifdef SQLITE_DEBUG - if( (p->db->flags & SQLITE_VdbeListing)!=0 - || sqlite3OsAccess(db->pVfs, "vdbe_explain", SQLITE_ACCESS_EXISTS) + if( p->pc==0 && ((p->db->flags & SQLITE_VdbeListing)!=0 + || sqlite3OsAccess(db->pVfs, "vdbe_explain", SQLITE_ACCESS_EXISTS)) ){ int i; printf("VDBE Program Listing:\n"); sqlite3VdbePrintSql(p); for(i=0; i<p->nOp; i++){ @@ -37742,11 +39517,10 @@ p->trace = stdout; } #endif for(pc=p->pc; rc==SQLITE_OK; pc++){ assert( pc>=0 && pc<p->nOp ); - assert( pTos<=&p->aStack[pc] ); if( db->mallocFailed ) goto no_mem; #ifdef VDBE_PROFILE origPc = pc; start = hwtime(); #endif @@ -37794,34 +39568,75 @@ if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; prc =db->xProgress(db->pProgressArg); if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; if( prc!=0 ){ rc = SQLITE_INTERRUPT; - goto vdbe_halt; + goto vdbe_error_halt; } nProgressOps = 0; } nProgressOps++; } #endif -#ifndef NDEBUG - /* This is to check that the return value of static function - ** opcodeNoPush() (see vdbeaux.c) returns values that match the - ** implementation of the virtual machine in this file. If - ** opcodeNoPush() returns non-zero, then the stack is guarenteed - ** not to grow when the opcode is executed. If it returns zero, then - ** the stack may grow by at most 1. - ** - ** The global wrapper function sqlite3VdbeOpcodeUsesStack() is not - ** available if NDEBUG is defined at build time. - */ - pStackLimit = pTos; - if( !sqlite3VdbeOpcodeNoPush(pOp->opcode) ){ - pStackLimit++; - } -#endif + /* Do common setup processing for any opcode that is marked + ** with the "out2-prerelease" tag. Such opcodes have a single + ** output which is specified by the P2 parameter. The P2 register + ** is initialized to a NULL. + */ + opProperty = opcodeProperty[pOp->opcode]; + if( (opProperty & OPFLG_OUT2_PRERELEASE)!=0 ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=p->nMem ); + pOut = &p->aMem[pOp->p2]; + sqlite3VdbeMemRelease(pOut); + pOut->flags = MEM_Null; + }else + + /* Do common setup for opcodes marked with one of the following + ** combinations of properties. + ** + ** in1 + ** in1 in2 + ** in1 in2 out3 + ** in1 in3 + ** + ** Variables pIn1, pIn2, and pIn3 are made to point to appropriate + ** registers for inputs. Variable pOut points to the output register. + */ + if( (opProperty & OPFLG_IN1)!=0 ){ + assert( pOp->p1>0 ); + assert( pOp->p1<=p->nMem ); + pIn1 = &p->aMem[pOp->p1]; + REGISTER_TRACE(pOp->p1, pIn1); + if( (opProperty & OPFLG_IN2)!=0 ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=p->nMem ); + pIn2 = &p->aMem[pOp->p2]; + REGISTER_TRACE(pOp->p2, pIn2); + if( (opProperty & OPFLG_OUT3)!=0 ){ + assert( pOp->p3>0 ); + assert( pOp->p3<=p->nMem ); + pOut = &p->aMem[pOp->p3]; + } + }else if( (opProperty & OPFLG_IN3)!=0 ){ + assert( pOp->p3>0 ); + assert( pOp->p3<=p->nMem ); + pIn3 = &p->aMem[pOp->p3]; + REGISTER_TRACE(pOp->p3, pIn3); + } + }else if( (opProperty & OPFLG_IN2)!=0 ){ + assert( pOp->p2>0 ); + assert( pOp->p2<=p->nMem ); + pIn2 = &p->aMem[pOp->p2]; + REGISTER_TRACE(pOp->p2, pIn2); + }else if( (opProperty & OPFLG_IN3)!=0 ){ + assert( pOp->p3>0 ); + assert( pOp->p3<=p->nMem ); + pIn3 = &p->aMem[pOp->p3]; + REGISTER_TRACE(pOp->p3, pIn3); + } switch( pOp->opcode ){ /***************************************************************************** ** What follows is a massive switch statement where each case implements a @@ -37839,14 +39654,14 @@ ** opcode and the opcodes.c file is filled with an array of strings where ** each string is the symbolic name for the corresponding opcode. If the ** case statement is followed by a comment of the form "/# same as ... #/" ** that comment is used to determine the particular value of the opcode. ** -** If a comment on the same line as the "case OP_" construction contains -** the word "no-push", then the opcode is guarenteed not to grow the -** vdbe stack when it is executed. See function opcode() in -** vdbeaux.c for details. +** Other keywords in the comment that follows each case are used to +** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[]. +** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See +** the mkopcodeh.awk script for additional information. ** ** Documentation about VDBE opcodes is generated by scanning this file ** for lines of that contain "Opcode:". That line and all subsequent ** comment lines are used in the generation of the opcode.html documentation ** file. @@ -37856,54 +39671,54 @@ ** Formatting is important to scripts that scan this file. ** Do not deviate from the formatting style currently in use. ** *****************************************************************************/ -/* Opcode: Goto * P2 * +/* Opcode: Goto * P2 * * * ** ** An unconditional jump to address P2. ** The next instruction executed will be ** the one at index P2 from the beginning of ** the program. */ -case OP_Goto: { /* no-push */ +case OP_Goto: { /* jump */ CHECK_FOR_INTERRUPT; pc = pOp->p2 - 1; break; } -/* Opcode: Gosub * P2 * +/* Opcode: Gosub * P2 * * * ** ** Push the current address plus 1 onto the return address stack ** and then jump to address P2. ** ** The return address stack is of limited depth. If too many ** OP_Gosub operations occur without intervening OP_Returns, then ** the return address stack will fill up and processing will abort ** with a fatal error. */ -case OP_Gosub: { /* no-push */ +case OP_Gosub: { /* jump */ assert( p->returnDepth<sizeof(p->returnStack)/sizeof(p->returnStack[0]) ); p->returnStack[p->returnDepth++] = pc+1; pc = pOp->p2 - 1; break; } -/* Opcode: Return * * * +/* Opcode: Return * * * * * ** ** Jump immediately to the next instruction after the last unreturned ** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then ** processing aborts with a fatal error. */ -case OP_Return: { /* no-push */ +case OP_Return: { assert( p->returnDepth>0 ); p->returnDepth--; pc = p->returnStack[p->returnDepth] - 1; break; } -/* Opcode: Halt P1 P2 P3 +/* Opcode: Halt P1 P2 * P4 * ** ** Exit immediately. All open cursors, Fifos, etc are closed ** automatically. ** ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(), @@ -37912,23 +39727,22 @@ ** whether or not to rollback the current transaction. Do not rollback ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort, ** then back out all changes that have occurred during this execution of the ** VDBE, but do not rollback the transaction. ** -** If P3 is not null then it is an error message string. +** If P4 is not null then it is an error message string. ** ** There is an implied "Halt 0 0 0" instruction inserted at the very end of ** every program. So a jump past the last instruction of the program ** is the same as executing Halt. */ -case OP_Halt: { /* no-push */ - p->pTos = pTos; +case OP_Halt: { p->rc = pOp->p1; p->pc = pc; p->errorAction = pOp->p2; - if( pOp->p3 ){ - sqlite3SetString(&p->zErrMsg, pOp->p3, (char*)0); + if( pOp->p4.z ){ + sqlite3SetString(&p->zErrMsg, pOp->p4.z, (char*)0); } rc = sqlite3VdbeHalt(p); assert( rc==SQLITE_BUSY || rc==SQLITE_OK ); if( rc==SQLITE_BUSY ){ p->rc = rc = SQLITE_BUSY; @@ -37936,464 +39750,320 @@ rc = p->rc ? SQLITE_ERROR : SQLITE_DONE; } goto vdbe_return; } -/* Opcode: Integer P1 * * -** -** The 32-bit integer value P1 is pushed onto the stack. -*/ -case OP_Integer: { - pTos++; - pTos->flags = MEM_Int; - pTos->u.i = pOp->p1; - break; -} - -/* Opcode: Int64 * * P3 -** -** P3 is a pointer to a 64-bit integer value. -** Push that value onto the stack. -*/ -case OP_Int64: { - pTos++; - assert( pOp->p3!=0 ); - pTos->flags = MEM_Int; - memcpy(&pTos->u.i, pOp->p3, 8); - break; -} - -/* Opcode: Real * * P3 -** -** P3 is a pointer to a 64-bit floating point value. Push that value -** onto the stack. -*/ -case OP_Real: { /* same as TK_FLOAT, */ - pTos++; - pTos->flags = MEM_Real; - memcpy(&pTos->r, pOp->p3, 8); - break; -} - -/* Opcode: String8 * * P3 -** -** P3 points to a nul terminated UTF-8 string. This opcode is transformed +/* Opcode: Integer P1 P2 * * * +** +** The 32-bit integer value P1 is written into register P2. +*/ +case OP_Integer: { /* out2-prerelease */ + pOut->flags = MEM_Int; + pOut->u.i = pOp->p1; + break; +} + +/* Opcode: Int64 * P2 * P4 * +** +** P4 is a pointer to a 64-bit integer value. +** Write that value into register P2. +*/ +case OP_Int64: { /* out2-prerelease */ + assert( pOp->p4.pI64!=0 ); + pOut->flags = MEM_Int; + pOut->u.i = *pOp->p4.pI64; + break; +} + +/* Opcode: Real * P2 * P4 * +** +** P4 is a pointer to a 64-bit floating point value. +** Write that value into register P2. +*/ +case OP_Real: { /* same as TK_FLOAT, out2-prerelease */ + pOut->flags = MEM_Real; + pOut->r = *pOp->p4.pReal; + break; +} + +/* Opcode: String8 * P2 * P4 * +** +** P4 points to a nul terminated UTF-8 string. This opcode is transformed ** into an OP_String before it is executed for the first time. */ -case OP_String8: { /* same as TK_STRING */ - assert( pOp->p3!=0 ); +case OP_String8: { /* same as TK_STRING, out2-prerelease */ + assert( pOp->p4.z!=0 ); pOp->opcode = OP_String; - pOp->p1 = strlen(pOp->p3); - assert( SQLITE_MAX_SQL_LENGTH <= SQLITE_MAX_LENGTH ); - assert( pOp->p1 <= SQLITE_MAX_LENGTH ); + pOp->p1 = strlen(pOp->p4.z); #ifndef SQLITE_OMIT_UTF16 if( encoding!=SQLITE_UTF8 ){ - pTos++; - sqlite3VdbeMemSetStr(pTos, pOp->p3, -1, SQLITE_UTF8, SQLITE_STATIC); - if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pTos, encoding) ) goto no_mem; - if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pTos) ) goto no_mem; - pTos->flags &= ~(MEM_Dyn); - pTos->flags |= MEM_Static; - if( pOp->p3type==P3_DYNAMIC ){ - sqlite3_free(pOp->p3); - } - pOp->p3type = P3_DYNAMIC; - pOp->p3 = pTos->z; - pOp->p1 = pTos->n; - assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */ + sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC); + if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem; + if( SQLITE_OK!=sqlite3VdbeMemDynamicify(pOut) ) goto no_mem; + pOut->flags &= ~(MEM_Dyn); + pOut->flags |= MEM_Static; + if( pOp->p4type==P4_DYNAMIC ){ + sqlite3_free(pOp->p4.z); + } + pOp->p4type = P4_DYNAMIC; + pOp->p4.z = pOut->z; + pOp->p1 = pOut->n; + if( pOp->p1>SQLITE_MAX_LENGTH ){ + goto too_big; + } + UPDATE_MAX_BLOBSIZE(pOut); break; } #endif - /* Otherwise fall through to the next case, OP_String */ -} - -/* Opcode: String P1 * P3 -** -** The string value P3 of length P1 (bytes) is pushed onto the stack. -*/ -case OP_String: { - assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */ - pTos++; - assert( pOp->p3!=0 ); - pTos->flags = MEM_Str|MEM_Static|MEM_Term; - pTos->z = pOp->p3; - pTos->n = pOp->p1; - pTos->enc = encoding; - break; -} - -/* Opcode: Null * * * -** -** Push a NULL onto the stack. -*/ -case OP_Null: { - pTos++; - pTos->flags = MEM_Null; - pTos->n = 0; + if( pOp->p1>SQLITE_MAX_LENGTH ){ + goto too_big; + } + /* Fall through to the next case, OP_String */ +} + +/* Opcode: String P1 P2 * P4 * +** +** The string value P4 of length P1 (bytes) is stored in register P2. +*/ +case OP_String: { /* out2-prerelease */ + assert( pOp->p4.z!=0 ); + pOut->flags = MEM_Str|MEM_Static|MEM_Term; + pOut->z = pOp->p4.z; + pOut->n = pOp->p1; + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Null * P2 * * * +** +** Write a NULL into register P2. +*/ +case OP_Null: { /* out2-prerelease */ break; } #ifndef SQLITE_OMIT_BLOB_LITERAL -/* Opcode: HexBlob * * P3 -** -** P3 is an UTF-8 SQL hex encoding of a blob. The blob is pushed onto the -** vdbe stack. -** -** The first time this instruction executes, in transforms itself into a -** 'Blob' opcode with a binary blob as P3. -*/ -case OP_HexBlob: { /* same as TK_BLOB */ - pOp->opcode = OP_Blob; - pOp->p1 = strlen(pOp->p3)/2; - assert( SQLITE_MAX_SQL_LENGTH <= SQLITE_MAX_LENGTH ); +/* Opcode: Blob P1 P2 * P4 +** +** P4 points to a blob of data P1 bytes long. Store this +** blob in register P2. This instruction is not coded directly +** by the compiler. Instead, the compiler layer specifies +** an OP_HexBlob opcode, with the hex string representation of +** the blob as P4. This opcode is transformed to an OP_Blob +** the first time it is executed. +*/ +case OP_Blob: { /* out2-prerelease */ assert( pOp->p1 <= SQLITE_MAX_LENGTH ); - if( pOp->p1 ){ - char *zBlob = sqlite3HexToBlob(db, pOp->p3); - if( !zBlob ) goto no_mem; - if( pOp->p3type==P3_DYNAMIC ){ - sqlite3_free(pOp->p3); - } - pOp->p3 = zBlob; - pOp->p3type = P3_DYNAMIC; - }else{ - if( pOp->p3type==P3_DYNAMIC ){ - sqlite3_free(pOp->p3); - } - pOp->p3type = P3_STATIC; - pOp->p3 = ""; - } - - /* Fall through to the next case, OP_Blob. */ -} - -/* Opcode: Blob P1 * P3 -** -** P3 points to a blob of data P1 bytes long. Push this -** value onto the stack. This instruction is not coded directly -** by the compiler. Instead, the compiler layer specifies -** an OP_HexBlob opcode, with the hex string representation of -** the blob as P3. This opcode is transformed to an OP_Blob -** the first time it is executed. -*/ -case OP_Blob: { - pTos++; - assert( pOp->p1 <= SQLITE_MAX_LENGTH ); /* Due to SQLITE_MAX_SQL_LENGTH */ - sqlite3VdbeMemSetStr(pTos, pOp->p3, pOp->p1, 0, 0); - pTos->enc = encoding; + sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0); + pOut->enc = encoding; + UPDATE_MAX_BLOBSIZE(pOut); break; } #endif /* SQLITE_OMIT_BLOB_LITERAL */ -/* Opcode: Variable P1 * * -** -** Push the value of variable P1 onto the stack. A variable is +/* Opcode: Variable P1 P2 * * * +** +** The value of variable P1 is written into register P2. A variable is ** an unknown in the original SQL string as handed to sqlite3_compile(). ** Any occurance of the '?' character in the original SQL is considered ** a variable. Variables in the SQL string are number from left to ** right beginning with 1. The values of variables are set using the ** sqlite3_bind() API. */ -case OP_Variable: { +case OP_Variable: { /* out2-prerelease */ int j = pOp->p1 - 1; Mem *pVar; assert( j>=0 && j<p->nVar ); pVar = &p->aVar[j]; if( sqlite3VdbeMemTooBig(pVar) ){ goto too_big; } - pTos++; - sqlite3VdbeMemShallowCopy(pTos, &p->aVar[j], MEM_Static); - break; -} - -/* Opcode: Pop P1 * * -** -** P1 elements are popped off of the top of stack and discarded. -*/ -case OP_Pop: { /* no-push */ - assert( pOp->p1>=0 ); - popStack(&pTos, pOp->p1); - assert( pTos>=&p->aStack[-1] ); - break; -} - -/* Opcode: Dup P1 P2 * -** -** A copy of the P1-th element of the stack -** is made and pushed onto the top of the stack. -** The top of the stack is element 0. So the -** instruction "Dup 0 0 0" will make a copy of the -** top of the stack. -** -** If the content of the P1-th element is a dynamically -** allocated string, then a new copy of that string -** is made if P2==0. If P2!=0, then just a pointer -** to the string is copied. -** -** Also see the Pull instruction. -*/ -case OP_Dup: { - Mem *pFrom = &pTos[-pOp->p1]; - assert( pFrom<=pTos && pFrom>=p->aStack ); - pTos++; - sqlite3VdbeMemShallowCopy(pTos, pFrom, MEM_Ephem); - if( pOp->p2 ){ - Deephemeralize(pTos); - } - break; -} - -/* Opcode: Pull P1 * * -** -** The P1-th element is removed from its current location on -** the stack and pushed back on top of the stack. The -** top of the stack is element 0, so "Pull 0 0 0" is -** a no-op. "Pull 1 0 0" swaps the top two elements of -** the stack. -** -** See also the Dup instruction. -*/ -case OP_Pull: { /* no-push */ - Mem *pFrom = &pTos[-pOp->p1]; - int i; - Mem ts; - - ts = *pFrom; - Deephemeralize(pTos); - for(i=0; i<pOp->p1; i++, pFrom++){ - Deephemeralize(&pFrom[1]); - assert( (pFrom[1].flags & MEM_Ephem)==0 ); - *pFrom = pFrom[1]; - if( pFrom->flags & MEM_Short ){ - assert( pFrom->flags & (MEM_Str|MEM_Blob) ); - assert( pFrom->z==pFrom[1].zShort ); - pFrom->z = pFrom->zShort; - } - } - *pTos = ts; - if( pTos->flags & MEM_Short ){ - assert( pTos->flags & (MEM_Str|MEM_Blob) ); - assert( pTos->z==pTos[-pOp->p1].zShort ); - pTos->z = pTos->zShort; - } - break; -} - -/* Opcode: Push P1 * * -** -** Overwrite the value of the P1-th element down on the -** stack (P1==0 is the top of the stack) with the value -** of the top of the stack. Then pop the top of the stack. -*/ -case OP_Push: { /* no-push */ - Mem *pTo = &pTos[-pOp->p1]; - - assert( pTo>=p->aStack ); - sqlite3VdbeMemMove(pTo, pTos); - pTos--; - break; -} - -/* Opcode: Callback P1 * * -** -** The top P1 values on the stack represent a single result row from -** a query. This opcode causes the sqlite3_step() call to terminate + sqlite3VdbeMemShallowCopy(pOut, &p->aVar[j], MEM_Static); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Move P1 P2 * * * +** +** Move the value in register P1 over into register P2. Register P1 +** is left holding a NULL. It is an error for P1 and P2 to be the +** same register. +*/ +/* Opcode: Copy P1 P2 * * * +** +** Make a copy of register P1 into register P2. +** +** This instruction makes a deep copy of the value. A duplicate +** is made of any string or blob constant. See also OP_SCopy. +*/ +/* Opcode: SCopy P1 P2 * * * +** +** Make a shallow copy of register P1 into register P2. +** +** This instruction makes a shallow copy of the value. If the value +** is a string or blob, then the copy is only a pointer to the +** original and hence if the original changes so will the copy. +** Worse, if the original is deallocated, the copy becomes invalid. +** Thus the program must guarantee that the original will not change +** during the lifetime of the copy. Use OP_Copy to make a complete +** copy. +*/ +case OP_Move: +case OP_Copy: +case OP_SCopy: { + assert( pOp->p1>0 ); + assert( pOp->p1<=p->nMem ); + pIn1 = &p->aMem[pOp->p1]; + REGISTER_TRACE(pOp->p1, pIn1); + assert( pOp->p2>0 ); + assert( pOp->p2<=p->nMem ); + pOut = &p->aMem[pOp->p2]; + assert( pOut!=pIn1 ); + if( pOp->opcode==OP_Move ){ + sqlite3VdbeMemMove(pOut, pIn1); + }else{ + sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem); + if( pOp->opcode==OP_Copy ){ + Deephemeralize(pOut); + } + } + REGISTER_TRACE(pOp->p2, pOut); + break; +} + +/* Opcode: ResultRow P1 P2 * * * +** +** The registers P1 throught P1+P2-1 contain a single row of +** results. This opcode causes the sqlite3_step() call to terminate ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt ** structure to provide access to the top P1 values as the result -** row. When the sqlite3_step() function is run again, the top P1 -** values will be automatically popped from the stack before the next -** instruction executes. -*/ -case OP_Callback: { /* no-push */ +** row. +*/ +case OP_ResultRow: { Mem *pMem; - Mem *pFirstColumn; - assert( p->nResColumn==pOp->p1 ); - - /* Data in the pager might be moved or changed out from under us - ** in between the return from this sqlite3_step() call and the - ** next call to sqlite3_step(). So deephermeralize everything on - ** the stack. Note that ephemeral data is never stored in memory - ** cells so we do not have to worry about them. - */ - pFirstColumn = &pTos[0-pOp->p1]; - for(pMem = p->aStack; pMem<pFirstColumn; pMem++){ - Deephemeralize(pMem); - } + int i; + assert( p->nResColumn==pOp->p2 ); + assert( pOp->p1>0 ); + assert( pOp->p1+pOp->p2<=p->nMem ); /* Invalidate all ephemeral cursor row caches */ p->cacheCtr = (p->cacheCtr + 2)|1; /* Make sure the results of the current row are \000 terminated ** and have an assigned type. The results are deephemeralized as ** as side effect. */ - for(; pMem<=pTos; pMem++ ){ - sqlite3VdbeMemNulTerminate(pMem); - storeTypeInfo(pMem, encoding); - } - - /* Set up the statement structure so that it will pop the current - ** results from the stack when the statement returns. - */ - p->resOnStack = 1; + pMem = p->pResultSet = &p->aMem[pOp->p1]; + for(i=0; i<pOp->p2; i++){ + sqlite3VdbeMemNulTerminate(&pMem[i]); + storeTypeInfo(&pMem[i], encoding); + } + + /* Return SQLITE_ROW + */ p->nCallback++; - p->popStack = pOp->p1; - p->pc = pc + 1; - p->pTos = pTos; + p->pc = pc + 1; rc = SQLITE_ROW; goto vdbe_return; } -/* Opcode: Concat P1 P2 * -** -** Look at the first P1+2 elements of the stack. Append them all -** together with the lowest element first. The original P1+2 elements -** are popped from the stack if P2==0 and retained if P2==1. If -** any element of the stack is NULL, then the result is NULL. -** -** When P1==1, this routine makes a copy of the top stack element -** into memory obtained from sqlite3_malloc(). -*/ -case OP_Concat: { /* same as TK_CONCAT */ +/* Opcode: Concat P1 P2 P3 * * +** +** Add the text in register P1 onto the end of the text in +** register P2 and store the result in register P3. +** If either the P1 or P2 text are NULL then store NULL in P3. +*/ +case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */ char *zNew; i64 nByte; - int nField; - int i, j; - Mem *pTerm; - - /* Loop through the stack elements to see how long the result will be. */ - nField = pOp->p1 + 2; - pTerm = &pTos[1-nField]; - nByte = 0; - for(i=0; i<nField; i++, pTerm++){ - assert( pOp->p2==0 || (pTerm->flags&MEM_Str) ); - if( pTerm->flags&MEM_Null ){ - nByte = -1; - break; - } - ExpandBlob(pTerm); - Stringify(pTerm, encoding); - nByte += pTerm->n; - } - - if( nByte<0 ){ - /* If nByte is less than zero, then there is a NULL value on the stack. - ** In this case just pop the values off the stack (if required) and - ** push on a NULL. - */ - if( pOp->p2==0 ){ - popStack(&pTos, nField); - } - pTos++; - pTos->flags = MEM_Null; - }else{ - /* Otherwise malloc() space for the result and concatenate all the - ** stack values. - */ - if( nByte+2>SQLITE_MAX_LENGTH ){ - goto too_big; - } - zNew = sqlite3DbMallocRaw(db, nByte+2 ); - if( zNew==0 ) goto no_mem; - j = 0; - pTerm = &pTos[1-nField]; - for(i=j=0; i<nField; i++, pTerm++){ - int n = pTerm->n; - assert( pTerm->flags & (MEM_Str|MEM_Blob) ); - memcpy(&zNew[j], pTerm->z, n); - j += n; - } - zNew[j] = 0; - zNew[j+1] = 0; - assert( j==nByte ); - - if( pOp->p2==0 ){ - popStack(&pTos, nField); - } - pTos++; - pTos->n = j; - pTos->flags = MEM_Str|MEM_Dyn|MEM_Term; - pTos->xDel = 0; - pTos->enc = encoding; - pTos->z = zNew; - } - break; -} - -/* Opcode: Add * * * -** -** Pop the top two elements from the stack, add them together, -** and push the result back onto the stack. If either element -** is a string then it is converted to a double using the atof() -** function before the addition. + + if( (pIn1->flags | pIn2->flags) & MEM_Null ){ + Release(pOut); + pOut->flags = MEM_Null; + break; + } + ExpandBlob(pIn1); + Stringify(pIn1, encoding); + ExpandBlob(pIn2); + Stringify(pIn2, encoding); + nByte = pIn1->n + pIn2->n; + if( nByte>SQLITE_MAX_LENGTH ){ + goto too_big; + } + zNew = sqlite3DbMallocRaw(db, nByte+2); + if( zNew==0 ){ + goto no_mem; + } + memcpy(zNew, pIn2->z, pIn2->n); + memcpy(&zNew[pIn2->n], pIn1->z, pIn1->n); + zNew[nByte] = 0; + zNew[nByte+1] = 0; + Release(pOut); + pOut->n = nByte; + pOut->flags = MEM_Str|MEM_Dyn|MEM_Term; + pOut->xDel = 0; + pOut->enc = encoding; + pOut->z = zNew; + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Add P1 P2 P3 * * +** +** Add the value in register P1 to the value in register P2 +** and store the result in regiser P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Multiply P1 P2 P3 * * +** +** +** Multiply the value in regiser P1 by the value in regiser P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Subtract P1 P2 P3 * * +** +** Subtract the value in register P1 from the value in register P2 +** and store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Divide P1 P2 P3 * * +** +** Divide the value in register P1 by the value in register P2 +** and store the result in register P3. If the value in register P2 +** is zero, then the result is NULL. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: Remainder P1 P2 P3 * * +** +** Compute the remainder after integer division of the value in +** register P1 by the value in register P2 and store the result in P3. +** If the value in register P2 is zero the result is NULL. ** If either operand is NULL, the result is NULL. */ -/* Opcode: Multiply * * * -** -** Pop the top two elements from the stack, multiply them together, -** and push the result back onto the stack. If either element -** is a string then it is converted to a double using the atof() -** function before the multiplication. -** If either operand is NULL, the result is NULL. -*/ -/* Opcode: Subtract * * * -** -** Pop the top two elements from the stack, subtract the -** first (what was on top of the stack) from the second (the -** next on stack) -** and push the result back onto the stack. If either element -** is a string then it is converted to a double using the atof() -** function before the subtraction. -** If either operand is NULL, the result is NULL. -*/ -/* Opcode: Divide * * * -** -** Pop the top two elements from the stack, divide the -** first (what was on top of the stack) from the second (the -** next on stack) -** and push the result back onto the stack. If either element -** is a string then it is converted to a double using the atof() -** function before the division. Division by zero returns NULL. -** If either operand is NULL, the result is NULL. -*/ -/* Opcode: Remainder * * * -** -** Pop the top two elements from the stack, divide the -** first (what was on top of the stack) from the second (the -** next on stack) -** and push the remainder after division onto the stack. If either element -** is a string then it is converted to a double using the atof() -** function before the division. Division by zero returns NULL. -** If either operand is NULL, the result is NULL. -*/ -case OP_Add: /* same as TK_PLUS, no-push */ -case OP_Subtract: /* same as TK_MINUS, no-push */ -case OP_Multiply: /* same as TK_STAR, no-push */ -case OP_Divide: /* same as TK_SLASH, no-push */ -case OP_Remainder: { /* same as TK_REM, no-push */ - Mem *pNos = &pTos[-1]; +case OP_Add: /* same as TK_PLUS, in1, in2, out3 */ +case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */ +case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */ +case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */ +case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */ int flags; - assert( pNos>=p->aStack ); - flags = pTos->flags | pNos->flags; - if( (flags & MEM_Null)!=0 ){ - Release(pTos); - pTos--; - Release(pTos); - pTos->flags = MEM_Null; - }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){ + flags = pIn1->flags | pIn2->flags; + if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null; + if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){ i64 a, b; - a = pTos->u.i; - b = pNos->u.i; + a = pIn1->u.i; + b = pIn2->u.i; switch( pOp->opcode ){ case OP_Add: b += a; break; case OP_Subtract: b -= a; break; case OP_Multiply: b *= a; break; case OP_Divide: { - if( a==0 ) goto divide_by_zero; + if( a==0 ) goto arithmetic_result_is_null; /* Dividing the largest possible negative 64-bit integer (1<<63) by ** -1 returns an integer to large to store in a 64-bit data-type. On ** some architectures, the value overflows to (1<<63). On others, ** a SIGFPE is issued. The following statement normalizes this ** behaviour so that all architectures behave as if integer @@ -38402,86 +40072,79 @@ if( a==-1 && b==(((i64)1)<<63) ) a = 1; b /= a; break; } default: { - if( a==0 ) goto divide_by_zero; + if( a==0 ) goto arithmetic_result_is_null; if( a==-1 ) a = 1; b %= a; break; } } - Release(pTos); - pTos--; - Release(pTos); - pTos->u.i = b; - pTos->flags = MEM_Int; + Release(pOut); + pOut->u.i = b; + pOut->flags = MEM_Int; }else{ double a, b; - a = sqlite3VdbeRealValue(pTos); - b = sqlite3VdbeRealValue(pNos); + a = sqlite3VdbeRealValue(pIn1); + b = sqlite3VdbeRealValue(pIn2); switch( pOp->opcode ){ case OP_Add: b += a; break; case OP_Subtract: b -= a; break; case OP_Multiply: b *= a; break; case OP_Divide: { - if( a==0.0 ) goto divide_by_zero; + if( a==0.0 ) goto arithmetic_result_is_null; b /= a; break; } default: { i64 ia = (i64)a; i64 ib = (i64)b; - if( ia==0 ) goto divide_by_zero; + if( ia==0 ) goto arithmetic_result_is_null; if( ia==-1 ) ia = 1; b = ib % ia; break; } } if( sqlite3_isnan(b) ){ - goto divide_by_zero; - } - Release(pTos); - pTos--; - Release(pTos); - pTos->r = b; - pTos->flags = MEM_Real; + goto arithmetic_result_is_null; + } + Release(pOut); + pOut->r = b; + pOut->flags = MEM_Real; if( (flags & MEM_Real)==0 ){ - sqlite3VdbeIntegerAffinity(pTos); - } - } - break; - -divide_by_zero: - Release(pTos); - pTos--; - Release(pTos); - pTos->flags = MEM_Null; - break; -} - -/* Opcode: CollSeq * * P3 -** -** P3 is a pointer to a CollSeq struct. If the next call to a user function + sqlite3VdbeIntegerAffinity(pOut); + } + } + break; + +arithmetic_result_is_null: + sqlite3VdbeMemSetNull(pOut); + break; +} + +/* Opcode: CollSeq * * P4 +** +** P4 is a pointer to a CollSeq struct. If the next call to a user function ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will ** be returned. This is used by the built-in min(), max() and nullif() ** functions. ** ** The interface used by the implementation of the aforementioned functions ** to retrieve the collation sequence set by this opcode is not available ** publicly, only to user functions defined in func.c. */ -case OP_CollSeq: { /* no-push */ - assert( pOp->p3type==P3_COLLSEQ ); - break; -} - -/* Opcode: Function P1 P2 P3 -** -** Invoke a user function (P3 is a pointer to a Function structure that -** defines the function) with P2 arguments taken from the stack. Pop all -** arguments from the stack and push back the result. +case OP_CollSeq: { + assert( pOp->p4type==P4_COLLSEQ ); + break; +} + +/* Opcode: Function P1 P2 P3 P4 P5 +** +** Invoke a user function (P4 is a pointer to a Function structure that +** defines the function) with P5 arguments taken from register P2 and +** successors. The result of the function is stored in register P3. ** ** P1 is a 32-bit bitmask indicating whether or not each argument to the ** function was determined to be constant at compile time. If the first ** argument was constant then bit 0 of P1 is set. This is used to determine ** whether meta data associated with a user function argument using the @@ -38493,27 +40156,29 @@ case OP_Function: { int i; Mem *pArg; sqlite3_context ctx; sqlite3_value **apVal; - int n = pOp->p2; + int n = pOp->p5; apVal = p->apArg; assert( apVal || n==0 ); - pArg = &pTos[1-n]; + assert( n==0 || (pOp->p2>0 && pOp->p2+n<=p->nMem) ); + pArg = &p->aMem[pOp->p2]; for(i=0; i<n; i++, pArg++){ apVal[i] = pArg; storeTypeInfo(pArg, encoding); - } - - assert( pOp->p3type==P3_FUNCDEF || pOp->p3type==P3_VDBEFUNC ); - if( pOp->p3type==P3_FUNCDEF ){ - ctx.pFunc = (FuncDef*)pOp->p3; + REGISTER_TRACE(pOp->p2, pArg); + } + + assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC ); + if( pOp->p4type==P4_FUNCDEF ){ + ctx.pFunc = pOp->p4.pFunc; ctx.pVdbeFunc = 0; }else{ - ctx.pVdbeFunc = (VdbeFunc*)pOp->p3; + ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc; ctx.pFunc = ctx.pVdbeFunc->pFunc; } ctx.s.flags = MEM_Null; ctx.s.z = 0; @@ -38520,13 +40185,13 @@ ctx.s.xDel = 0; ctx.s.db = db; ctx.isError = 0; if( ctx.pFunc->needCollSeq ){ assert( pOp>p->aOp ); - assert( pOp[-1].p3type==P3_COLLSEQ ); + assert( pOp[-1].p4type==P4_COLLSEQ ); assert( pOp[-1].opcode==OP_CollSeq ); - ctx.pColl = (CollSeq *)pOp[-1].p3; + ctx.pColl = pOp[-1].p4.pColl; } if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; (*ctx.pFunc->xFunc)(&ctx, n, apVal); if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; if( db->mallocFailed ){ @@ -38540,683 +40205,583 @@ ** misusing sqlite, they have bigger problems than a leaked value. */ sqlite3VdbeMemRelease(&ctx.s); goto no_mem; } - popStack(&pTos, n); /* If any auxilary data functions have been called by this user function, ** immediately call the destructor for any non-static values. */ if( ctx.pVdbeFunc ){ sqlite3VdbeDeleteAuxData(ctx.pVdbeFunc, pOp->p1); - pOp->p3 = (char *)ctx.pVdbeFunc; - pOp->p3type = P3_VDBEFUNC; + pOp->p4.pVdbeFunc = ctx.pVdbeFunc; + pOp->p4type = P4_VDBEFUNC; } /* If the function returned an error, throw an exception */ if( ctx.isError ){ sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0); rc = SQLITE_ERROR; } - /* Copy the result of the function to the top of the stack */ + /* Copy the result of the function into register P3 */ sqlite3VdbeChangeEncoding(&ctx.s, encoding); - pTos++; - pTos->flags = 0; - sqlite3VdbeMemMove(pTos, &ctx.s); - if( sqlite3VdbeMemTooBig(pTos) ){ + assert( pOp->p3>0 && pOp->p3<=p->nMem ); + pOut = &p->aMem[pOp->p3]; + sqlite3VdbeMemMove(pOut, &ctx.s); + if( sqlite3VdbeMemTooBig(pOut) ){ goto too_big; } - break; -} - -/* Opcode: BitAnd * * * -** -** Pop the top two elements from the stack. Convert both elements -** to integers. Push back onto the stack the bit-wise AND of the -** two elements. -** If either operand is NULL, the result is NULL. -*/ -/* Opcode: BitOr * * * -** -** Pop the top two elements from the stack. Convert both elements -** to integers. Push back onto the stack the bit-wise OR of the -** two elements. -** If either operand is NULL, the result is NULL. -*/ -/* Opcode: ShiftLeft * * * -** -** Pop the top two elements from the stack. Convert both elements -** to integers. Push back onto the stack the second element shifted -** left by N bits where N is the top element on the stack. -** If either operand is NULL, the result is NULL. -*/ -/* Opcode: ShiftRight * * * -** -** Pop the top two elements from the stack. Convert both elements -** to integers. Push back onto the stack the second element shifted -** right by N bits where N is the top element on the stack. -** If either operand is NULL, the result is NULL. -*/ -case OP_BitAnd: /* same as TK_BITAND, no-push */ -case OP_BitOr: /* same as TK_BITOR, no-push */ -case OP_ShiftLeft: /* same as TK_LSHIFT, no-push */ -case OP_ShiftRight: { /* same as TK_RSHIFT, no-push */ - Mem *pNos = &pTos[-1]; + REGISTER_TRACE(pOp->p3, pOut); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: BitAnd P1 P2 P3 * * +** +** Take the bit-wise AND of the values in register P1 and P2 and +** store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: BitOr P1 P2 P3 * * +** +** Take the bit-wise OR of the values in register P1 and P2 and +** store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: ShiftLeft P1 P2 P3 * * +** +** Shift the integer value in register P2 to the left by the +** number of bits specified by the integer in regiser P1. +** Store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +/* Opcode: ShiftRight P1 P2 P3 * * +** +** Shift the integer value in register P2 to the right by the +** number of bits specified by the integer in register P1. +** Store the result in register P3. +** If either input is NULL, the result is NULL. +*/ +case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */ +case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */ +case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */ +case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */ i64 a, b; - assert( pNos>=p->aStack ); - if( (pTos->flags | pNos->flags) & MEM_Null ){ - popStack(&pTos, 2); - pTos++; - pTos->flags = MEM_Null; + if( (pIn1->flags | pIn2->flags) & MEM_Null ){ + sqlite3VdbeMemSetNull(pOut); break; } - a = sqlite3VdbeIntValue(pNos); - b = sqlite3VdbeIntValue(pTos); + a = sqlite3VdbeIntValue(pIn2); + b = sqlite3VdbeIntValue(pIn1); switch( pOp->opcode ){ case OP_BitAnd: a &= b; break; case OP_BitOr: a |= b; break; case OP_ShiftLeft: a <<= b; break; - case OP_ShiftRight: a >>= b; break; - default: /* CANT HAPPEN */ break; - } - Release(pTos); - pTos--; - Release(pTos); - pTos->u.i = a; - pTos->flags = MEM_Int; - break; -} - -/* Opcode: AddImm P1 * * -** -** Add the value P1 to whatever is on top of the stack. The result -** is always an integer. -** -** To force the top of the stack to be an integer, just add 0. -*/ -case OP_AddImm: { /* no-push */ - assert( pTos>=p->aStack ); - sqlite3VdbeMemIntegerify(pTos); - pTos->u.i += pOp->p1; - break; -} - -/* Opcode: ForceInt P1 P2 * -** -** Convert the top of the stack into an integer. If the current top of -** the stack is not numeric (meaning that is is a NULL or a string that -** does not look like an integer or floating point number) then pop the -** stack and jump to P2. If the top of the stack is numeric then + default: assert( pOp->opcode==OP_ShiftRight ); + a >>= b; break; + } + Release(pOut); + pOut->u.i = a; + pOut->flags = MEM_Int; + break; +} + +/* Opcode: AddImm P1 P2 * * * +** +** Add the constant P2 the value in register P1. +** The result is always an integer. +** +** To force any register to be an integer, just add 0. +*/ +case OP_AddImm: { /* in1 */ + sqlite3VdbeMemIntegerify(pIn1); + pIn1->u.i += pOp->p2; + break; +} + +/* Opcode: ForceInt P1 P2 P3 * * +** +** Convert value in register P1 into an integer. If the value +** in P1 is not numeric (meaning that is is a NULL or a string that +** does not look like an integer or floating point number) then +** jump to P2. If the value in P1 is numeric then ** convert it into the least integer that is greater than or equal to its -** current value if P1==0, or to the least integer that is strictly -** greater than its current value if P1==1. -*/ -case OP_ForceInt: { /* no-push */ +** current value if P3==0, or to the least integer that is strictly +** greater than its current value if P3==1. +*/ +case OP_ForceInt: { /* jump, in1 */ i64 v; - assert( pTos>=p->aStack ); - applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding); - if( (pTos->flags & (MEM_Int|MEM_Real))==0 ){ - Release(pTos); - pTos--; + applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); + if( (pIn1->flags & (MEM_Int|MEM_Real))==0 ){ pc = pOp->p2 - 1; break; } - if( pTos->flags & MEM_Int ){ - v = pTos->u.i + (pOp->p1!=0); - }else{ - /* FIX ME: should this not be assert( pTos->flags & MEM_Real ) ??? */ - sqlite3VdbeMemRealify(pTos); - v = (int)pTos->r; - if( pTos->r>(double)v ) v++; - if( pOp->p1 && pTos->r==(double)v ) v++; - } - Release(pTos); - pTos->u.i = v; - pTos->flags = MEM_Int; - break; -} - -/* Opcode: MustBeInt P1 P2 * -** -** Force the top of the stack to be an integer. If the top of the -** stack is not an integer and cannot be converted into an integer -** with out data loss, then jump immediately to P2, or if P2==0 + if( pIn1->flags & MEM_Int ){ + v = pIn1->u.i + (pOp->p3!=0); + }else{ + assert( pIn1->flags & MEM_Real ); + v = (sqlite3_int64)pIn1->r; + if( pIn1->r>(double)v ) v++; + if( pOp->p3 && pIn1->r==(double)v ) v++; + } + Release(pIn1); + pIn1->u.i = v; + pIn1->flags = MEM_Int; + break; +} + +/* Opcode: MustBeInt P1 P2 * * * +** +** Force the value in register P1 to be an integer. If the value +** in P1 is not an integer and cannot be converted into an integer +** without data loss, then jump immediately to P2, or if P2==0 ** raise an SQLITE_MISMATCH exception. -** -** If the top of the stack is not an integer and P2 is not zero and -** P1 is 1, then the stack is popped. In all other cases, the depth -** of the stack is unchanged. -*/ -case OP_MustBeInt: { /* no-push */ - assert( pTos>=p->aStack ); - applyAffinity(pTos, SQLITE_AFF_NUMERIC, encoding); - if( (pTos->flags & MEM_Int)==0 ){ +*/ +case OP_MustBeInt: { /* jump, in1 */ + applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding); + if( (pIn1->flags & MEM_Int)==0 ){ if( pOp->p2==0 ){ rc = SQLITE_MISMATCH; goto abort_due_to_error; }else{ - if( pOp->p1 ) popStack(&pTos, 1); pc = pOp->p2 - 1; } }else{ - Release(pTos); - pTos->flags = MEM_Int; - } - break; -} - -/* Opcode: RealAffinity * * * -** -** If the top of the stack is an integer, convert it to a real value. + Release(pIn1); + pIn1->flags = MEM_Int; + } + break; +} + +/* Opcode: RealAffinity P1 * * * * +** +** If register P1 holds an integer convert it to a real value. ** ** This opcode is used when extracting information from a column that ** has REAL affinity. Such column values may still be stored as ** integers, for space efficiency, but after extraction we want them ** to have only a real value. */ -case OP_RealAffinity: { /* no-push */ - assert( pTos>=p->aStack ); - if( pTos->flags & MEM_Int ){ - sqlite3VdbeMemRealify(pTos); +case OP_RealAffinity: { /* in1 */ + if( pIn1->flags & MEM_Int ){ + sqlite3VdbeMemRealify(pIn1); } break; } #ifndef SQLITE_OMIT_CAST -/* Opcode: ToText * * * -** -** Force the value on the top of the stack to be text. +/* Opcode: ToText P1 * * * * +** +** Force the value in register P1 to be text. ** If the value is numeric, convert it to a string using the ** equivalent of printf(). Blob values are unchanged and ** are afterwards simply interpreted as text. ** ** A NULL value is not changed by this routine. It remains NULL. */ -case OP_ToText: { /* same as TK_TO_TEXT, no-push */ - assert( pTos>=p->aStack ); - if( pTos->flags & MEM_Null ) break; +case OP_ToText: { /* same as TK_TO_TEXT, in1 */ + if( pIn1->flags & MEM_Null ) break; assert( MEM_Str==(MEM_Blob>>3) ); - pTos->flags |= (pTos->flags&MEM_Blob)>>3; - applyAffinity(pTos, SQLITE_AFF_TEXT, encoding); - rc = ExpandBlob(pTos); - assert( pTos->flags & MEM_Str ); - pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Blob); - break; -} - -/* Opcode: ToBlob * * * -** -** Force the value on the top of the stack to be a BLOB. + pIn1->flags |= (pIn1->flags&MEM_Blob)>>3; + applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding); + rc = ExpandBlob(pIn1); + assert( pIn1->flags & MEM_Str ); + pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob); + UPDATE_MAX_BLOBSIZE(pIn1); + break; +} + +/* Opcode: ToBlob P1 * * * * +** +** Force the value in register P1 to be a BLOB. ** If the value is numeric, convert it to a string first. ** Strings are simply reinterpreted as blobs with no change ** to the underlying data. ** ** A NULL value is not changed by this routine. It remains NULL. */ -case OP_ToBlob: { /* same as TK_TO_BLOB, no-push */ - assert( pTos>=p->aStack ); - if( pTos->flags & MEM_Null ) break; - if( (pTos->flags & MEM_Blob)==0 ){ - applyAffinity(pTos, SQLITE_AFF_TEXT, encoding); - assert( pTos->flags & MEM_Str ); - pTos->flags |= MEM_Blob; - } - pTos->flags &= ~(MEM_Int|MEM_Real|MEM_Str); - break; -} - -/* Opcode: ToNumeric * * * -** -** Force the value on the top of the stack to be numeric (either an +case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */ + if( pIn1->flags & MEM_Null ) break; + if( (pIn1->flags & MEM_Blob)==0 ){ + applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding); + assert( pIn1->flags & MEM_Str ); + pIn1->flags |= MEM_Blob; + } + pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Str); + UPDATE_MAX_BLOBSIZE(pIn1); + break; +} + +/* Opcode: ToNumeric P1 * * * * +** +** Force the value in register P1 to be numeric (either an ** integer or a floating-point number.) ** If the value is text or blob, try to convert it to an using the ** equivalent of atoi() or atof() and store 0 if no such conversion ** is possible. ** ** A NULL value is not changed by this routine. It remains NULL. */ -case OP_ToNumeric: { /* same as TK_TO_NUMERIC, no-push */ - assert( pTos>=p->aStack ); - if( (pTos->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){ - sqlite3VdbeMemNumerify(pTos); +case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */ + if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){ + sqlite3VdbeMemNumerify(pIn1); } break; } #endif /* SQLITE_OMIT_CAST */ -/* Opcode: ToInt * * * -** -** Force the value on the top of the stack to be an integer. If +/* Opcode: ToInt P1 * * * * +** +** Force the value in register P1 be an integer. If ** The value is currently a real number, drop its fractional part. ** If the value is text or blob, try to convert it to an integer using the ** equivalent of atoi() and store 0 if no such conversion is possible. ** ** A NULL value is not changed by this routine. It remains NULL. */ -case OP_ToInt: { /* same as TK_TO_INT, no-push */ - assert( pTos>=p->aStack ); - if( (pTos->flags & MEM_Null)==0 ){ - sqlite3VdbeMemIntegerify(pTos); +case OP_ToInt: { /* same as TK_TO_INT, in1 */ + if( (pIn1->flags & MEM_Null)==0 ){ + sqlite3VdbeMemIntegerify(pIn1); } break; } #ifndef SQLITE_OMIT_CAST -/* Opcode: ToReal * * * -** -** Force the value on the top of the stack to be a floating point number. +/* Opcode: ToReal P1 * * * * +** +** Force the value in register P1 to be a floating point number. ** If The value is currently an integer, convert it. ** If the value is text or blob, try to convert it to an integer using the -** equivalent of atoi() and store 0 if no such conversion is possible. +** equivalent of atoi() and store 0.0 if no such conversion is possible. ** ** A NULL value is not changed by this routine. It remains NULL. */ -case OP_ToReal: { /* same as TK_TO_REAL, no-push */ - assert( pTos>=p->aStack ); - if( (pTos->flags & MEM_Null)==0 ){ - sqlite3VdbeMemRealify(pTos); +case OP_ToReal: { /* same as TK_TO_REAL, in1 */ + if( (pIn1->flags & MEM_Null)==0 ){ + sqlite3VdbeMemRealify(pIn1); } break; } #endif /* SQLITE_OMIT_CAST */ -/* Opcode: Eq P1 P2 P3 -** -** Pop the top two elements from the stack. If they are equal, then -** jump to instruction P2. Otherwise, continue to the next instruction. -** -** If the 0x100 bit of P1 is true and either operand is NULL then take the -** jump. If the 0x100 bit of P1 is clear then fall thru if either operand -** is NULL. -** -** If the 0x200 bit of P1 is set and either operand is NULL then -** both operands are converted to integers prior to comparison. -** NULL operands are converted to zero and non-NULL operands are -** converted to 1. Thus, for example, with 0x200 set, NULL==NULL is true -** whereas it would normally be NULL. Similarly, NULL==123 is false when -** 0x200 is set but is NULL when the 0x200 bit of P1 is clear. -** -** The least significant byte of P1 (mask 0xff) must be an affinity character - +/* Opcode: Lt P1 P2 P3 P4 P5 +** +** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then +** jump to address P2. +** +** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or +** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL +** bit is clear then fall thru if either operand is NULL. +** +** If the SQLITE_NULLEQUAL bit of P5 is set then treat NULL operands +** as being equal to one another. Normally NULLs are not equal to +** anything including other NULLs. +** +** The SQLITE_AFF_MASK portion of P5 must be an affinity character - ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made -** to coerce both values -** according to the affinity before the comparison is made. If the byte is -** 0x00, then numeric affinity is used. +** to coerce both inputs according to this affinity before the +** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric +** affinity is used. Note that the affinity conversions are stored +** back into the input registers P1 and P3. So this opcode can cause +** persistent changes to registers P1 and P3. ** ** Once any conversions have taken place, and neither value is NULL, -** the values are compared. If both values are blobs, or both are text, -** then memcmp() is used to determine the results of the comparison. If -** both values are numeric, then a numeric comparison is used. If the -** two values are of different types, then they are inequal. -** -** If P2 is zero, do not jump. Instead, push an integer 1 onto the -** stack if the jump would have been taken, or a 0 if not. Push a -** NULL if either operand was NULL. -** -** If P3 is not NULL it is a pointer to a collating sequence (a CollSeq -** structure) that defines how to compare text. -*/ -/* Opcode: Ne P1 P2 P3 -** -** This works just like the Eq opcode except that the jump is taken if -** the operands from the stack are not equal. See the Eq opcode for +** the values are compared. If both values are blobs then memcmp() is +** used to determine the results of the comparison. If both values +** are text, then the appropriate collating function specified in +** P4 is used to do the comparison. If P4 is not specified then +** memcmp() is used to compare text string. If both values are +** numeric, then a numeric comparison is used. If the two values +** are of different types, then numbers are considered less than +** strings and strings are considered less than blobs. +** +** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead, +** store a boolean result (either 0, or 1, or NULL) in register P2. +*/ +/* Opcode: Ne P1 P2 P3 P4 P5 +** +** This works just like the Lt opcode except that the jump is taken if +** the operands in registers P1 and P3 are not equal. See the Lt opcode for ** additional information. */ -/* Opcode: Lt P1 P2 P3 -** -** This works just like the Eq opcode except that the jump is taken if -** the 2nd element down on the stack is less than the top of the stack. -** See the Eq opcode for additional information. -*/ -/* Opcode: Le P1 P2 P3 -** -** This works just like the Eq opcode except that the jump is taken if -** the 2nd element down on the stack is less than or equal to the -** top of the stack. See the Eq opcode for additional information. -*/ -/* Opcode: Gt P1 P2 P3 -** -** This works just like the Eq opcode except that the jump is taken if -** the 2nd element down on the stack is greater than the top of the stack. -** See the Eq opcode for additional information. -*/ -/* Opcode: Ge P1 P2 P3 -** -** This works just like the Eq opcode except that the jump is taken if -** the 2nd element down on the stack is greater than or equal to the -** top of the stack. See the Eq opcode for additional information. -*/ -case OP_Eq: /* same as TK_EQ, no-push */ -case OP_Ne: /* same as TK_NE, no-push */ -case OP_Lt: /* same as TK_LT, no-push */ -case OP_Le: /* same as TK_LE, no-push */ -case OP_Gt: /* same as TK_GT, no-push */ -case OP_Ge: { /* same as TK_GE, no-push */ - Mem *pNos; +/* Opcode: Eq P1 P2 P3 P4 P5 +** +** This works just like the Lt opcode except that the jump is taken if +** the operands in registers P1 and P3 are equal. +** See the Lt opcode for additional information. +*/ +/* Opcode: Le P1 P2 P3 P4 P5 +** +** This works just like the Lt opcode except that the jump is taken if +** the content of register P3 is less than or equal to the content of +** register P1. See the Lt opcode for additional information. +*/ +/* Opcode: Gt P1 P2 P3 P4 P5 +** +** This works just like the Lt opcode except that the jump is taken if +** the content of register P3 is greater than the content of +** register P1. See the Lt opcode for additional information. +*/ +/* Opcode: Ge P1 P2 P3 P4 P5 +** +** This works just like the Lt opcode except that the jump is taken if +** the content of register P3 is greater than or equal to the content of +** register P1. See the Lt opcode for additional information. +*/ +case OP_Eq: /* same as TK_EQ, jump, in1, in3 */ +case OP_Ne: /* same as TK_NE, jump, in1, in3 */ +case OP_Lt: /* same as TK_LT, jump, in1, in3 */ +case OP_Le: /* same as TK_LE, jump, in1, in3 */ +case OP_Gt: /* same as TK_GT, jump, in1, in3 */ +case OP_Ge: { /* same as TK_GE, jump, in1, in3 */ int flags; int res; char affinity; - - pNos = &pTos[-1]; - flags = pTos->flags|pNos->flags; - - /* If either value is a NULL P2 is not zero, take the jump if the least - ** significant byte of P1 is true. If P2 is zero, then push a NULL onto - ** the stack. - */ + Mem x1, x3; + + flags = pIn1->flags|pIn3->flags; + if( flags&MEM_Null ){ - if( (pOp->p1 & 0x200)!=0 ){ - /* The 0x200 bit of P1 means, roughly "do not treat NULL as the - ** magic SQL value it normally is - treat it as if it were another - ** integer". - ** - ** With 0x200 set, if either operand is NULL then both operands - ** are converted to integers prior to being passed down into the - ** normal comparison logic below. NULL operands are converted to - ** zero and non-NULL operands are converted to 1. Thus, for example, - ** with 0x200 set, NULL==NULL is true whereas it would normally - ** be NULL. Similarly, NULL!=123 is true. - */ - sqlite3VdbeMemSetInt64(pTos, (pTos->flags & MEM_Null)==0); - sqlite3VdbeMemSetInt64(pNos, (pNos->flags & MEM_Null)==0); - }else{ - /* If the 0x200 bit of P1 is clear and either operand is NULL then - ** the result is always NULL. The jump is taken if the 0x100 bit - ** of P1 is set. - */ - popStack(&pTos, 2); - if( pOp->p2 ){ - if( pOp->p1 & 0x100 ){ - pc = pOp->p2-1; - } - }else{ - pTos++; - pTos->flags = MEM_Null; - } - break; - } - } - - affinity = pOp->p1 & 0xFF; + if( (pOp->p5 & SQLITE_NULLEQUAL)!=0 ){ + /* + ** When SQLITE_NULLEQUAL set and either operand is NULL + ** then both operands are converted to integers prior to being + ** passed down into the normal comparison logic below. + ** NULL operands are converted to zero and non-NULL operands + ** are converted to 1. Thus, for example, with SQLITE_NULLEQUAL + ** set, NULL==NULL is true whereas it would normally NULL. + ** Similarly, NULL!=123 is true. + */ + x1.flags = MEM_Int; + x1.u.i = (pIn1->flags & MEM_Null)==0; + pIn1 = &x1; + x3.flags = MEM_Int; + x3.u.i = (pIn3->flags & MEM_Null)==0; + pIn3 = &x3; + }else{ + /* If the SQLITE_NULLEQUAL bit is clear and either operand is NULL then + ** the result is always NULL. The jump is taken if the + ** SQLITE_JUMPIFNULL bit is set. + */ + if( pOp->p5 & SQLITE_STOREP2 ){ + pOut = &p->aMem[pOp->p2]; + Release(pOut); + pOut->flags = MEM_Null; + REGISTER_TRACE(pOp->p2, pOut); + }else if( pOp->p5 & SQLITE_JUMPIFNULL ){ + pc = pOp->p2-1; + } + break; + } + } + + affinity = pOp->p5 & SQLITE_AFF_MASK; if( affinity ){ - applyAffinity(pNos, affinity, encoding); - applyAffinity(pTos, affinity, encoding); - } - - assert( pOp->p3type==P3_COLLSEQ || pOp->p3==0 ); - ExpandBlob(pNos); - ExpandBlob(pTos); - res = sqlite3MemCompare(pNos, pTos, (CollSeq*)pOp->p3); + applyAffinity(pIn1, affinity, encoding); + applyAffinity(pIn3, affinity, encoding); + } + + assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 ); + ExpandBlob(pIn1); + ExpandBlob(pIn3); + res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl); switch( pOp->opcode ){ case OP_Eq: res = res==0; break; case OP_Ne: res = res!=0; break; case OP_Lt: res = res<0; break; case OP_Le: res = res<=0; break; case OP_Gt: res = res>0; break; default: res = res>=0; break; } - popStack(&pTos, 2); - if( pOp->p2 ){ - if( res ){ - pc = pOp->p2-1; - } - }else{ - pTos++; - pTos->flags = MEM_Int; - pTos->u.i = res; - } - break; -} - -/* Opcode: And * * * -** -** Pop two values off the stack. Take the logical AND of the -** two values and push the resulting boolean value back onto the -** stack. -*/ -/* Opcode: Or * * * -** -** Pop two values off the stack. Take the logical OR of the -** two values and push the resulting boolean value back onto the -** stack. -*/ -case OP_And: /* same as TK_AND, no-push */ -case OP_Or: { /* same as TK_OR, no-push */ - Mem *pNos = &pTos[-1]; - int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */ - - assert( pNos>=p->aStack ); - if( pTos->flags & MEM_Null ){ + if( pOp->p5 & SQLITE_STOREP2 ){ + pOut = &p->aMem[pOp->p2]; + Release(pOut); + pOut->flags = MEM_Int; + pOut->u.i = res; + REGISTER_TRACE(pOp->p2, pOut); + }else if( res ){ + pc = pOp->p2-1; + } + break; +} + +/* Opcode: And P1 P2 P3 * * +** +** Take the logical AND of the values in registers P1 and P2 and +** write the result into register P3. +** +** If either P1 or P2 is 0 (false) then the result is 0 even if +** the other input is NULL. A NULL and true or two NULLs give +** a NULL output. +*/ +/* Opcode: Or P1 P2 P3 * * +** +** Take the logical OR of the values in register P1 and P2 and +** store the answer in register P3. +** +** If either P1 or P2 is nonzero (true) then the result is 1 (true) +** even if the other input is NULL. A NULL and false or two NULLs +** give a NULL output. +*/ +case OP_And: /* same as TK_AND, in1, in2, out3 */ +case OP_Or: { /* same as TK_OR, in1, in2, out3 */ + int v1, v2; /* 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */ + + if( pIn1->flags & MEM_Null ){ v1 = 2; }else{ - sqlite3VdbeMemIntegerify(pTos); - v1 = pTos->u.i==0; - } - if( pNos->flags & MEM_Null ){ + v1 = sqlite3VdbeIntValue(pIn1)!=0; + } + if( pIn2->flags & MEM_Null ){ v2 = 2; }else{ - sqlite3VdbeMemIntegerify(pNos); - v2 = pNos->u.i==0; + v2 = sqlite3VdbeIntValue(pIn2)!=0; } if( pOp->opcode==OP_And ){ - static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; + static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; v1 = and_logic[v1*3+v2]; }else{ - static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 }; + static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 }; v1 = or_logic[v1*3+v2]; } - popStack(&pTos, 2); - pTos++; + Release(pOut); if( v1==2 ){ - pTos->flags = MEM_Null; - }else{ - pTos->u.i = v1==0; - pTos->flags = MEM_Int; - } - break; -} - -/* Opcode: Negative * * * -** -** Treat the top of the stack as a numeric quantity. Replace it -** with its additive inverse. If the top of the stack is NULL -** its value is unchanged. -*/ -/* Opcode: AbsValue * * * -** -** Treat the top of the stack as a numeric quantity. Replace it -** with its absolute value. If the top of the stack is NULL -** its value is unchanged. -*/ -case OP_Negative: /* same as TK_UMINUS, no-push */ -case OP_AbsValue: { - assert( pTos>=p->aStack ); - if( (pTos->flags & (MEM_Real|MEM_Int|MEM_Null))==0 ){ - sqlite3VdbeMemNumerify(pTos); - } - if( pTos->flags & MEM_Real ){ - Release(pTos); - if( pOp->opcode==OP_Negative || pTos->r<0.0 ){ - pTos->r = -pTos->r; - } - pTos->flags = MEM_Real; - }else if( pTos->flags & MEM_Int ){ - Release(pTos); - if( pOp->opcode==OP_Negative || pTos->u.i<0 ){ - pTos->u.i = -pTos->u.i; - } - pTos->flags = MEM_Int; - } - break; -} - -/* Opcode: Not * * * -** -** Interpret the top of the stack as a boolean value. Replace it -** with its complement. If the top of the stack is NULL its value + pOut->flags = MEM_Null; + }else{ + pOut->u.i = v1; + pOut->flags = MEM_Int; + } + break; +} + +/* Opcode: Not P1 * * * * +** +** Interpret the value in register P1 as a boolean value. Replace it +** with its complement. If the value in register P1 is NULL its value ** is unchanged. */ -case OP_Not: { /* same as TK_NOT, no-push */ - assert( pTos>=p->aStack ); - if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */ - sqlite3VdbeMemIntegerify(pTos); - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos->u.i = !pTos->u.i; - pTos->flags = MEM_Int; - break; -} - -/* Opcode: BitNot * * * -** -** Interpret the top of the stack as an value. Replace it -** with its ones-complement. If the top of the stack is NULL its -** value is unchanged. -*/ -case OP_BitNot: { /* same as TK_BITNOT, no-push */ - assert( pTos>=p->aStack ); - if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */ - sqlite3VdbeMemIntegerify(pTos); - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos->u.i = ~pTos->u.i; - pTos->flags = MEM_Int; - break; -} - -/* Opcode: Noop * * * -** -** Do nothing. This instruction is often useful as a jump -** destination. -*/ -/* -** The magic Explain opcode are only inserted when explain==2 (which -** is to say when the EXPLAIN QUERY PLAN syntax is used.) -** This opcode records information from the optimizer. It is the -** the same as a no-op. This opcodesnever appears in a real VM program. -*/ -case OP_Explain: -case OP_Noop: { /* no-push */ - break; -} - -/* Opcode: If P1 P2 * -** -** Pop a single boolean from the stack. If the boolean popped is -** true, then jump to p2. Otherwise continue to the next instruction. -** An integer is false if zero and true otherwise. A string is -** false if it has zero length and true otherwise. -** -** If the value popped of the stack is NULL, then take the jump if P1 -** is true and fall through if P1 is false. -*/ -/* Opcode: IfNot P1 P2 * -** -** Pop a single boolean from the stack. If the boolean popped is -** false, then jump to p2. Otherwise continue to the next instruction. -** An integer is false if zero and true otherwise. A string is -** false if it has zero length and true otherwise. -** -** If the value popped of the stack is NULL, then take the jump if P1 -** is true and fall through if P1 is false. -*/ -case OP_If: /* no-push */ -case OP_IfNot: { /* no-push */ +case OP_Not: { /* same as TK_NOT, in1 */ + if( pIn1->flags & MEM_Null ) break; /* Do nothing to NULLs */ + sqlite3VdbeMemIntegerify(pIn1); + pIn1->u.i = !pIn1->u.i; + assert( pIn1->flags==MEM_Int ); + break; +} + +/* Opcode: BitNot P1 * * * * +** +** Interpret the content of register P1 as an integer. Replace it +** with its ones-complement. If the value is originally NULL, leave +** it unchanged. +*/ +case OP_BitNot: { /* same as TK_BITNOT, in1 */ + if( pIn1->flags & MEM_Null ) break; /* Do nothing to NULLs */ + sqlite3VdbeMemIntegerify(pIn1); + pIn1->u.i = ~pIn1->u.i; + assert( pIn1->flags==MEM_Int ); + break; +} + +/* Opcode: If P1 P2 P3 * * +** +** Jump to P2 if the value in register P1 is true. The value is +** is considered true if it is numeric and non-zero. If the value +** in P1 is NULL then take the jump if P3 is true. +*/ +/* Opcode: IfNot P1 P2 P3 * * +** +** Jump to P2 if the value in register P1 is False. The value is +** is considered true if it has a numeric value of zero. If the value +** in P1 is NULL then take the jump if P3 is true. +*/ +case OP_If: /* jump, in1 */ +case OP_IfNot: { /* jump, in1 */ int c; - assert( pTos>=p->aStack ); - if( pTos->flags & MEM_Null ){ - c = pOp->p1; + if( pIn1->flags & MEM_Null ){ + c = pOp->p3; }else{ #ifdef SQLITE_OMIT_FLOATING_POINT - c = sqlite3VdbeIntValue(pTos); -#else - c = sqlite3VdbeRealValue(pTos)!=0.0; + c = sqlite3VdbeIntValue(pIn1); +#else + c = sqlite3VdbeRealValue(pIn1)!=0.0; #endif if( pOp->opcode==OP_IfNot ) c = !c; } - Release(pTos); - pTos--; - if( c ) pc = pOp->p2-1; - break; -} - -/* Opcode: IsNull P1 P2 * -** -** Check the top of the stack and jump to P2 if the top of the stack -** is NULL. If P1 is positive, then pop P1 elements from the stack -** regardless of whether or not the jump is taken. If P1 is negative, -** pop -P1 elements from the stack only if the jump is taken and leave -** the stack unchanged if the jump is not taken. -*/ -case OP_IsNull: { /* same as TK_ISNULL, no-push */ - if( pTos->flags & MEM_Null ){ + if( c ){ pc = pOp->p2-1; - if( pOp->p1<0 ){ - popStack(&pTos, -pOp->p1); - } - } - if( pOp->p1>0 ){ - popStack(&pTos, pOp->p1); - } - break; -} - -/* Opcode: NotNull P1 P2 * -** -** Jump to P2 if the top abs(P1) values on the stack are all not NULL. -** Regardless of whether or not the jump is taken, pop the stack -** P1 times if P1 is greater than zero. But if P1 is negative, -** leave the stack unchanged. -*/ -case OP_NotNull: { /* same as TK_NOTNULL, no-push */ - int i, cnt; - cnt = pOp->p1; - if( cnt<0 ) cnt = -cnt; - assert( &pTos[1-cnt] >= p->aStack ); - for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){} - if( i>=cnt ) pc = pOp->p2-1; - if( pOp->p1>0 ) popStack(&pTos, cnt); - break; -} - -/* Opcode: SetNumColumns P1 P2 * + } + break; +} + +/* Opcode: IsNull P1 P2 P3 * * +** +** Jump to P2 if the value in register P1 is NULL. If P3 is greater +** than zero, then check all values reg(P1), reg(P1+1), +** reg(P1+2), ..., reg(P1+P3-1). +*/ +case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */ + int n = pOp->p3; + assert( pOp->p3==0 || pOp->p1>0 ); + do{ + if( (pIn1->flags & MEM_Null)!=0 ){ + pc = pOp->p2 - 1; + break; + } + pIn1++; + }while( --n > 0 ); + break; +} + +/* Opcode: NotNull P1 P2 * * * +** +** Jump to P2 if the value in register P1 is not NULL. +*/ +case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */ + if( (pIn1->flags & MEM_Null)==0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: SetNumColumns P1 P2 * * * ** ** Before the OP_Column opcode can be executed on a cursor, this ** opcode must be called to set the number of fields in the table. ** ** This opcode sets the number of columns for cursor P1 to P2. ** ** If OP_KeyAsData is to be applied to cursor P1, it must be executed ** before this op-code. */ -case OP_SetNumColumns: { /* no-push */ +case OP_SetNumColumns: { Cursor *pC; assert( (pOp->p1)<p->nCursor ); assert( p->apCsr[pOp->p1]!=0 ); pC = p->apCsr[pOp->p1]; pC->nField = pOp->p2; break; } -/* Opcode: Column P1 P2 P3 +/* Opcode: Column P1 P2 P3 P4 * ** ** Interpret the data that cursor P1 points to as a structure built using ** the MakeRecord instruction. (See the MakeRecord opcode for additional -** information about the format of the data.) Push onto the stack the value -** of the P2-th column contained in the data. If there are less that (P2+1) -** values in the record, push a NULL onto the stack. +** information about the format of the data.) Extract the P2-th column +** from this record. If there are less that (P2+1) +** values in the record, extract a NULL. +** +** The value extracted is stored in register P3. ** ** If the KeyAsData opcode has previously executed on this cursor, then the ** field might be extracted from the key rather than the data. ** -** If the column contains fewer than P2 fields, then push a NULL. Or -** if P3 is of type P3_MEM, then push the P3 value. The P3 value will -** be default value for a column that has been added using the ALTER TABLE -** ADD COLUMN command. If P3 is an ordinary string, just push a NULL. -** When P3 is a string it is really just a comment describing the value -** to be pushed, not a default value. +** If the column contains fewer than P2 fields, then extract a NULL. Or, +** if the P4 argument is a P4_MEM use the value of the P4 argument as +** the result. */ case OP_Column: { u32 payloadSize; /* Number of bytes in the record */ int p1 = pOp->p1; /* P1 value of the opcode */ int p2 = pOp->p2; /* column number to retrieve */ @@ -39227,16 +40792,18 @@ u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */ u32 nField; /* number of fields in the record */ int len; /* The length of the serialized data for the column */ int i; /* Loop counter */ char *zData; /* Part of the record being decoded */ + Mem *pDest; /* Where to write the extracted value */ Mem sMem; /* For storing the record being decoded */ sMem.flags = 0; assert( p1<p->nCursor ); - pTos++; - pTos->flags = MEM_Null; + assert( pOp->p3>0 && pOp->p3<=p->nMem ); + pDest = &p->aMem[pOp->p3]; + sqlite3VdbeMemSetNull(pDest); /* This block sets the variable payloadSize to be the total number of ** bytes in the record. ** ** zRec is set to be the complete text of the record if it is available. @@ -39244,13 +40811,11 @@ ** If the record is stored in a cursor, the complete record text ** might be available in the pC->aRow cache. Or it might not be. ** If the data is unavailable, zRec is set to NULL. ** ** We also compute the number of columns in the record. For cursors, - ** the number of columns is stored in the Cursor.nField element. For - ** records on the stack, the next entry down on the stack is an integer - ** which is the number of records. + ** the number of columns is stored in the Cursor.nField element. */ pC = p->apCsr[p1]; assert( pC!=0 ); #ifndef SQLITE_OMIT_VIRTUALTABLE assert( pC->pVtabCursor==0 ); @@ -39272,29 +40837,25 @@ payloadSize = payloadSize64; }else{ sqlite3BtreeDataSize(pCrsr, &payloadSize); } nField = pC->nField; - }else if( pC->pseudoTable ){ + }else{ + assert( pC->pseudoTable ); /* The record is the sole entry of a pseudo-table */ payloadSize = pC->nData; zRec = pC->pData; pC->cacheStatus = CACHE_STALE; assert( payloadSize==0 || zRec!=0 ); nField = pC->nField; pCrsr = 0; - }else{ - zRec = 0; - payloadSize = 0; - pCrsr = 0; - nField = 0; - } - - /* If payloadSize is 0, then just push a NULL onto the stack. */ + } + + /* If payloadSize is 0, then just store a NULL */ if( payloadSize==0 ){ - assert( pTos->flags==MEM_Null ); - break; + assert( pDest->flags==MEM_Null ); + goto op_column_out; } if( payloadSize>SQLITE_MAX_LENGTH ){ goto too_big; } @@ -39301,11 +40862,11 @@ assert( p2<nField ); /* Read and parse the table header. Store the results of the parse ** into the record header cache fields of the cursor. */ - if( pC && pC->cacheStatus==p->cacheCtr ){ + if( pC->cacheStatus==p->cacheCtr ){ aType = pC->aType; aOffset = pC->aOffset; }else{ u8 *zIdx; /* Index into header */ u8 *zEndHdr; /* Pointer to first byte after the header */ @@ -39378,12 +40939,12 @@ offset += sqlite3VdbeSerialTypeLen(aType[i]); }else{ /* If i is less that nField, then there are less fields in this ** record than SetNumColumns indicated there are columns in the ** table. Set the offset for any extra columns not present in - ** the record to 0. This tells code below to push a NULL onto the - ** stack instead of deserializing a value from the record. + ** the record to 0. This tells code below to store a NULL + ** instead of deserializing a value from the record. */ aOffset[i] = 0; } } Release(&sMem); @@ -39400,11 +40961,11 @@ } /* Get the column information. If aOffset[p2] is non-zero, then ** deserialize the value from the record. If aOffset[p2] is zero, ** then there are not enough fields in the record to satisfy the - ** request. In this case, set the value NULL or to P3 if P3 is + ** request. In this case, set the value NULL or to P4 if P4 is ** a pointer to a Mem object. */ if( aOffset[p2] ){ assert( rc==SQLITE_OK ); if( zRec ){ @@ -39415,139 +40976,113 @@ if( rc!=SQLITE_OK ){ goto op_column_out; } zData = sMem.z; } - sqlite3VdbeSerialGet((u8*)zData, aType[p2], pTos); - pTos->enc = encoding; - }else{ - if( pOp->p3type==P3_MEM ){ - sqlite3VdbeMemShallowCopy(pTos, (Mem *)(pOp->p3), MEM_Static); - }else{ - pTos->flags = MEM_Null; + sqlite3VdbeSerialGet((u8*)zData, aType[p2], pDest); + pDest->enc = encoding; + }else{ + if( pOp->p4type==P4_MEM ){ + sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static); + }else{ + assert( pDest->flags==MEM_Null ); } } /* If we dynamically allocated space to hold the data (in the ** sqlite3VdbeMemFromBtree() call above) then transfer control of that - ** dynamically allocated space over to the pTos structure. + ** dynamically allocated space over to the pDest structure. ** This prevents a memory copy. */ if( (sMem.flags & MEM_Dyn)!=0 ){ - assert( pTos->flags & MEM_Ephem ); - assert( pTos->flags & (MEM_Str|MEM_Blob) ); - assert( pTos->z==sMem.z ); + assert( pDest->flags & MEM_Ephem ); + assert( pDest->flags & (MEM_Str|MEM_Blob) ); + assert( pDest->z==sMem.z ); assert( sMem.flags & MEM_Term ); - pTos->flags &= ~MEM_Ephem; - pTos->flags |= MEM_Dyn|MEM_Term; - } - - /* pTos->z might be pointing to sMem.zShort[]. Fix that so that we + pDest->flags &= ~MEM_Ephem; + pDest->flags |= MEM_Dyn|MEM_Term; + } + + /* pDest->z might be pointing to sMem.zShort[]. Fix that so that we ** can abandon sMem */ - rc = sqlite3VdbeMemMakeWriteable(pTos); + rc = sqlite3VdbeMemMakeWriteable(pDest); op_column_out: - break; -} - -/* Opcode: MakeRecord P1 P2 P3 -** -** Convert the top abs(P1) entries of the stack into a single entry + UPDATE_MAX_BLOBSIZE(pDest); + REGISTER_TRACE(pOp->p3, pDest); + break; +} + +/* Opcode: MakeRecord P1 P2 P3 P4 * +** +** Convert P2 registers beginning with P1 into a single entry ** suitable for use as a data record in a database table or as a key ** in an index. The details of the format are irrelavant as long as ** the OP_Column opcode can decode the record later and as long as the ** sqlite3VdbeRecordCompare function will correctly compare two encoded ** records. Refer to source code comments for the details of the record ** format. ** -** The original stack entries are popped from the stack if P1>0 but -** remain on the stack if P1<0. -** -** If P2 is not zero and one or more of the entries are NULL, then jump -** to the address given by P2. This feature can be used to skip a -** uniqueness test on indices. -** -** P3 may be a string that is P1 characters long. The nth character of the +** P4 may be a string that is P1 characters long. The nth character of the ** string indicates the column affinity that should be used for the nth -** field of the index key (i.e. the first character of P3 corresponds to the -** lowest element on the stack). +** field of the index key. ** ** The mapping from character to affinity is given by the SQLITE_AFF_ ** macros defined in sqliteInt.h. ** -** If P3 is NULL then all index fields have the affinity NONE. -** -** See also OP_MakeIdxRec -*/ -/* Opcode: MakeIdxRec P1 P2 P3 -** -** This opcode works just OP_MakeRecord except that it reads an extra -** integer from the stack (thus reading a total of abs(P1+1) entries) -** and appends that extra integer to the end of the record as a varint. -** This results in an index key. -*/ -case OP_MakeIdxRec: +** If P4 is NULL then all index fields have the affinity NONE. +*/ case OP_MakeRecord: { /* Assuming the record contains N fields, the record format looks ** like this: ** ** ------------------------------------------------------------------------ ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | ** ------------------------------------------------------------------------ ** - ** Data(0) is taken from the lowest element of the stack and data(N-1) is - ** the top of the stack. + ** Data(0) is taken from register P1. Data(1) comes from register P1+1 + ** and so froth. ** ** Each type field is a varint representing the serial type of the ** corresponding data element (see sqlite3VdbeSerialType()). The ** hdr-size field is also a varint which is the offset from the beginning ** of the record to data0. */ u8 *zNewRecord; /* A buffer to hold the data for the new record */ Mem *pRec; /* The new record */ - Mem *pRowid = 0; /* Rowid appended to the new record */ u64 nData = 0; /* Number of bytes of data space */ int nHdr = 0; /* Number of bytes of header space */ u64 nByte = 0; /* Data space required for this record */ int nZero = 0; /* Number of zero bytes at the end of the record */ int nVarint; /* Number of bytes in a varint */ u32 serial_type; /* Type field */ - int containsNull = 0; /* True if any of the data fields are NULL */ - Mem *pData0; /* Bottom of the stack */ - int leaveOnStack; /* If true, leave the entries on the stack */ - int nField; /* Number of fields in the record */ - int jumpIfNull; /* Jump here if non-zero and any entries are NULL. */ - int addRowid; /* True to append a rowid column at the end */ + Mem *pData0; /* First field to be combined into the record */ + Mem *pLast; /* Last field of the record */ + int nField; /* Number of fields in the record */ char *zAffinity; /* The affinity string for the record */ int file_format; /* File format to use for encoding */ int i; /* Space used in zNewRecord[] */ char zTemp[NBFS]; /* Space to hold small records */ - leaveOnStack = ((pOp->p1<0)?1:0); - nField = pOp->p1 * (leaveOnStack?-1:1); - jumpIfNull = pOp->p2; - addRowid = pOp->opcode==OP_MakeIdxRec; - zAffinity = pOp->p3; - - pData0 = &pTos[1-nField]; - assert( pData0>=p->aStack ); - containsNull = 0; + nField = pOp->p1; + zAffinity = pOp->p4.z; + assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=p->nMem ); + pData0 = &p->aMem[nField]; + nField = pOp->p2; + pLast = &pData0[nField-1]; file_format = p->minWriteFileFormat; /* Loop through the elements that will make up the record to figure ** out how much space is required for the new record. */ - for(pRec=pData0; pRec<=pTos; pRec++){ + for(pRec=pData0; pRec<=pLast; pRec++){ int len; if( zAffinity ){ applyAffinity(pRec, zAffinity[pRec-pData0], encoding); } - if( pRec->flags&MEM_Null ){ - containsNull = 1; - } if( pRec->flags&MEM_Zero && pRec->n>0 ){ - ExpandBlob(pRec); + sqlite3VdbeMemExpandBlob(pRec); } serial_type = sqlite3VdbeSerialType(pRec, file_format); len = sqlite3VdbeSerialTypeLen(serial_type); nData += len; nHdr += sqlite3VarintLen(serial_type); @@ -39556,24 +41091,10 @@ ** We do not allow blobs with a prefix and a zero-filled tail. */ nZero += pRec->u.i; }else if( len ){ nZero = 0; } - } - - /* If we have to append a varint rowid to this record, set pRowid - ** to the value of the rowid and increase nByte by the amount of space - ** required to store it. - */ - if( addRowid ){ - pRowid = &pTos[0-nField]; - assert( pRowid>=p->aStack ); - sqlite3VdbeMemIntegerify(pRowid); - serial_type = sqlite3VdbeSerialType(pRowid, 0); - nData += sqlite3VdbeSerialTypeLen(serial_type); - nHdr += sqlite3VarintLen(serial_type); - nZero = 0; } /* Add the initial header varint and total the size */ nHdr += nVarint = sqlite3VarintLen(nHdr); if( nVarint<sqlite3VarintLen(nHdr) ){ @@ -39594,56 +41115,45 @@ zNewRecord = (u8*)zTemp; } /* Write the record */ i = sqlite3PutVarint(zNewRecord, nHdr); - for(pRec=pData0; pRec<=pTos; pRec++){ + for(pRec=pData0; pRec<=pLast; pRec++){ serial_type = sqlite3VdbeSerialType(pRec, file_format); i += sqlite3PutVarint(&zNewRecord[i], serial_type); /* serial type */ } - if( addRowid ){ - i += sqlite3PutVarint(&zNewRecord[i], sqlite3VdbeSerialType(pRowid, 0)); - } - for(pRec=pData0; pRec<=pTos; pRec++){ /* serial data */ - i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format); - } - if( addRowid ){ - i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRowid, 0); + for(pRec=pData0; pRec<=pLast; pRec++){ /* serial data */ + i += sqlite3VdbeSerialPut(&zNewRecord[i], nByte-i, pRec, file_format); } assert( i==nByte ); - /* Pop entries off the stack if required. Push the new record on. */ - if( !leaveOnStack ){ - popStack(&pTos, nField+addRowid); - } - pTos++; - pTos->n = nByte; + assert( pOp->p3>0 && pOp->p3<=p->nMem ); + pOut = &p->aMem[pOp->p3]; + Release(pOut); + pOut->n = nByte; if( nByte<=sizeof(zTemp) ){ assert( zNewRecord==(unsigned char *)zTemp ); - pTos->z = pTos->zShort; - memcpy(pTos->zShort, zTemp, nByte); - pTos->flags = MEM_Blob | MEM_Short; + pOut->z = pOut->zShort; + memcpy(pOut->zShort, zTemp, nByte); + pOut->flags = MEM_Blob | MEM_Short; }else{ assert( zNewRecord!=(unsigned char *)zTemp ); - pTos->z = (char*)zNewRecord; - pTos->flags = MEM_Blob | MEM_Dyn; - pTos->xDel = 0; + pOut->z = (char*)zNewRecord; + pOut->flags = MEM_Blob | MEM_Dyn; + pOut->xDel = 0; } if( nZero ){ - pTos->u.i = nZero; - pTos->flags |= MEM_Zero; - } - pTos->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ - - /* If a NULL was encountered and jumpIfNull is non-zero, take the jump. */ - if( jumpIfNull && containsNull ){ - pc = jumpIfNull - 1; - } - break; -} - -/* Opcode: Statement P1 * * + pOut->u.i = nZero; + pOut->flags |= MEM_Zero; + } + pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */ + REGISTER_TRACE(pOp->p3, pOut); + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Statement P1 * * * * ** ** Begin an individual statement transaction which is part of a larger ** BEGIN..COMMIT transaction. This is needed so that the statement ** can be rolled back after an error without having to roll back the ** entire transaction. The statement transaction will automatically @@ -39651,14 +41161,17 @@ ** ** The statement is begun on the database file with index P1. The main ** database file has an index of 0 and the file used for temporary tables ** has an index of 1. */ -case OP_Statement: { /* no-push */ - int i = pOp->p1; - Btree *pBt; - if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){ +case OP_Statement: { + if( db->autoCommit==0 || db->activeVdbeCnt>1 ){ + int i = pOp->p1; + Btree *pBt; + assert( i>=0 && i<db->nDb ); + assert( db->aDb[i].pBt!=0 ); + pBt = db->aDb[i].pBt; assert( sqlite3BtreeIsInTrans(pBt) ); assert( (p->btreeMask & (1<<i))!=0 ); if( !sqlite3BtreeIsInStmt(pBt) ){ rc = sqlite3BtreeBeginStmt(pBt); p->openedStatement = 1; @@ -39665,19 +41178,19 @@ } } break; } -/* Opcode: AutoCommit P1 P2 * +/* Opcode: AutoCommit P1 P2 * * * ** ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll ** back any currently active btree transactions. If there are any active ** VMs (apart from this one), then the COMMIT or ROLLBACK statement fails. ** ** This instruction causes the VM to halt. */ -case OP_AutoCommit: { /* no-push */ +case OP_AutoCommit: { u8 i = pOp->p1; u8 rollback = pOp->p2; assert( i==1 || i==0 ); assert( i==1 || rollback==0 ); @@ -39698,11 +41211,10 @@ sqlite3RollbackAll(db); db->autoCommit = 1; }else{ db->autoCommit = i; if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){ - p->pTos = pTos; p->pc = pc; db->autoCommit = 1-i; p->rc = rc = SQLITE_BUSY; goto vdbe_return; } @@ -39722,19 +41234,20 @@ rc = SQLITE_ERROR; } break; } -/* Opcode: Transaction P1 P2 * +/* Opcode: Transaction P1 P2 * * * ** ** Begin a transaction. The transaction ends when a Commit or Rollback ** opcode is encountered. Depending on the ON CONFLICT setting, the ** transaction might also be rolled back if an error is encountered. ** ** P1 is the index of the database file on which the transaction is ** started. Index 0 is the main database file and index 1 is the -** file used for temporary tables. +** file used for temporary tables. Indices of 2 or more are used for +** attached databases. ** ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is ** obtained on the database file when a write-transaction is started. No ** other process can start another write transaction while this transaction is ** underway. Starting a write transaction also creates a rollback journal. A @@ -39742,11 +41255,11 @@ ** database. If P2 is 2 or greater then an EXCLUSIVE lock is also obtained ** on the file. ** ** If P2 is zero, then a read-lock is obtained on the database file. */ -case OP_Transaction: { /* no-push */ +case OP_Transaction: { int i = pOp->p1; Btree *pBt; assert( i>=0 && i<db->nDb ); assert( (p->btreeMask & (1<<i))!=0 ); @@ -39755,43 +41268,42 @@ if( pBt ){ rc = sqlite3BtreeBeginTrans(pBt, pOp->p2); if( rc==SQLITE_BUSY ){ p->pc = pc; p->rc = rc = SQLITE_BUSY; - p->pTos = pTos; goto vdbe_return; } if( rc!=SQLITE_OK && rc!=SQLITE_READONLY /* && rc!=SQLITE_BUSY */ ){ goto abort_due_to_error; } } break; } -/* Opcode: ReadCookie P1 P2 * -** -** Read cookie number P2 from database P1 and push it onto the stack. -** P2==0 is the schema version. P2==1 is the database format. -** P2==2 is the recommended pager cache size, and so forth. P1==0 is +/* Opcode: ReadCookie P1 P2 P3 * * +** +** Read cookie number P3 from database P1 and write it into register P2. +** P3==0 is the schema version. P3==1 is the database format. +** P3==2 is the recommended pager cache size, and so forth. P1==0 is ** the main database file and P1==1 is the database file used to store ** temporary tables. ** ** If P1 is negative, then this is a request to read the size of a -** databases free-list. P2 must be set to 1 in this case. The actual +** databases free-list. P3 must be set to 1 in this case. The actual ** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1 ** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp"). ** ** There must be a read-lock on the database (either a transaction ** must be started or there must be an open cursor) before ** executing this instruction. */ -case OP_ReadCookie: { +case OP_ReadCookie: { /* out2-prerelease */ int iMeta; int iDb = pOp->p1; - int iCookie = pOp->p2; - - assert( pOp->p2<SQLITE_N_BTREE_META ); + int iCookie = pOp->p3; + + assert( pOp->p3<SQLITE_N_BTREE_META ); if( iDb<0 ){ iDb = (-1*(iDb+1)); iCookie *= -1; } assert( iDb>=0 && iDb<db->nDb ); @@ -39803,47 +41315,44 @@ ** and meta[1] to be the schema cookie. The schema layer considers ** meta[1] to be the schema cookie. So we have to shift the index ** by one in the following statement. */ rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta); - pTos++; - pTos->u.i = iMeta; - pTos->flags = MEM_Int; - break; -} - -/* Opcode: SetCookie P1 P2 * -** -** Write the top of the stack into cookie number P2 of database P1. + pOut->u.i = iMeta; + pOut->flags = MEM_Int; + break; +} + +/* Opcode: SetCookie P1 P2 P3 * * +** +** Write the content of register P3 (interpreted as an integer) +** into cookie number P2 of database P1. ** P2==0 is the schema version. P2==1 is the database format. ** P2==2 is the recommended pager cache size, and so forth. P1==0 is ** the main database file and P1==1 is the database file used to store ** temporary tables. ** ** A transaction must be started before executing this opcode. */ -case OP_SetCookie: { /* no-push */ +case OP_SetCookie: { /* in3 */ Db *pDb; assert( pOp->p2<SQLITE_N_BTREE_META ); assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( (p->btreeMask & (1<<pOp->p1))!=0 ); pDb = &db->aDb[pOp->p1]; assert( pDb->pBt!=0 ); - assert( pTos>=p->aStack ); - sqlite3VdbeMemIntegerify(pTos); + sqlite3VdbeMemIntegerify(pIn3); /* See note about index shifting on OP_ReadCookie */ - rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pTos->u.i); + rc = sqlite3BtreeUpdateMeta(pDb->pBt, 1+pOp->p2, (int)pIn3->u.i); if( pOp->p2==0 ){ /* When the schema cookie changes, record the new cookie internally */ - pDb->pSchema->schema_cookie = pTos->u.i; + pDb->pSchema->schema_cookie = pIn3->u.i; db->flags |= SQLITE_InternChanges; }else if( pOp->p2==1 ){ /* Record changes in the file format */ - pDb->pSchema->file_format = pTos->u.i; - } - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos--; + pDb->pSchema->file_format = pIn3->u.i; + } if( pOp->p1==1 ){ /* Invalidate all prepared statements whenever the TEMP database ** schema is changed. Ticket #1644 */ sqlite3ExpirePreparedStatements(db); } @@ -39864,11 +41373,11 @@ ** ** Either a transaction needs to have been started or an OP_Open needs ** to be executed (to establish a read lock) before this opcode is ** invoked. */ -case OP_VerifyCookie: { /* no-push */ +case OP_VerifyCookie: { int iMeta; Btree *pBt; assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( (p->btreeMask & (1<<pOp->p1))!=0 ); pBt = db->aDb[pOp->p1].pBt; @@ -39902,21 +41411,22 @@ rc = SQLITE_SCHEMA; } break; } -/* Opcode: OpenRead P1 P2 P3 +/* Opcode: OpenRead P1 P2 P3 P4 P5 ** ** Open a read-only cursor for the database table whose root page is -** P2 in a database file. The database file is determined by an -** integer from the top of the stack. 0 means the main database and -** 1 means the database used for temporary tables. Give the new -** cursor an identifier of P1. The P1 values need not be contiguous -** but all P1 values should be small integers. It is an error for -** P1 to be negative. -** -** If P2==0 then take the root page number from the next of the stack. +** P2 in a database file. The database file is determined by P3. +** P3==0 means the main database, P3==1 means the database used for +** temporary tables, and P3>1 means used the corresponding attached +** database. Give the new cursor an identifier of P1. The P1 +** values need not be contiguous but all P1 values should be small integers. +** It is an error for P1 to be negative. +** +** If P5!=0 then use the content of register P2 as the root page, not +** the value of P2 itself. ** ** There will be a read lock on the database whenever there is an ** open cursor. If the database was unlocked prior to this instruction ** then a read lock is acquired as part of this instruction. A read ** lock allows other processes to read the database but prohibits @@ -39923,46 +41433,42 @@ ** any other process from modifying the database. The read lock is ** released when all cursors are closed. If this instruction attempts ** to get a read lock but fails, the script terminates with an ** SQLITE_BUSY error code. ** -** The P3 value is a pointer to a KeyInfo structure that defines the -** content and collating sequence of indices. P3 is NULL for cursors +** The P4 value is a pointer to a KeyInfo structure that defines the +** content and collating sequence of indices. P4 is NULL for cursors ** that are not pointing to indices. ** ** See also OpenWrite. */ -/* Opcode: OpenWrite P1 P2 P3 +/* Opcode: OpenWrite P1 P2 P3 P4 P5 ** ** Open a read/write cursor named P1 on the table or index whose root -** page is P2. If P2==0 then take the root page number from the stack. -** -** The P3 value is a pointer to a KeyInfo structure that defines the -** content and collating sequence of indices. P3 is NULL for cursors +** page is P2. Or if P5!=0 use the content of register P2 to find the +** root page. +** +** The P4 value is a pointer to a KeyInfo structure that defines the +** content and collating sequence of indices. P4 is NULL for cursors ** that are not pointing to indices. ** ** This instruction works just like OpenRead except that it opens the cursor ** in read/write mode. For a given table, there can be one or more read-only ** cursors or a single read/write cursor but not both. ** ** See also OpenRead. */ -case OP_OpenRead: /* no-push */ -case OP_OpenWrite: { /* no-push */ +case OP_OpenRead: +case OP_OpenWrite: { int i = pOp->p1; int p2 = pOp->p2; + int iDb = pOp->p3; int wrFlag; Btree *pX; - int iDb; Cursor *pCur; Db *pDb; - assert( pTos>=p->aStack ); - sqlite3VdbeMemIntegerify(pTos); - iDb = pTos->u.i; - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos--; assert( iDb>=0 && iDb<db->nDb ); assert( (p->btreeMask & (1<<iDb))!=0 ); pDb = &db->aDb[iDb]; pX = pDb->pBt; assert( pX!=0 ); @@ -39972,30 +41478,29 @@ p->minWriteFileFormat = pDb->pSchema->file_format; } }else{ wrFlag = 0; } - if( p2<=0 ){ - assert( pTos>=p->aStack ); - sqlite3VdbeMemIntegerify(pTos); - p2 = pTos->u.i; - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos--; + if( pOp->p5 ){ + assert( p2>0 ); + assert( p2<=p->nMem ); + pIn2 = &p->aMem[p2]; + sqlite3VdbeMemIntegerify(pIn2); + p2 = pIn2->u.i; assert( p2>=2 ); } assert( i>=0 ); pCur = allocateCursor(p, i, iDb); if( pCur==0 ) goto no_mem; pCur->nullRow = 1; - if( pX==0 ) break; /* We always provide a key comparison function. If the table being ** opened is of type INTKEY, the comparision function will be ignored. */ rc = sqlite3BtreeCursor(pX, p2, wrFlag, - sqlite3VdbeRecordCompare, pOp->p3, + sqlite3VdbeRecordCompare, pOp->p4.p, &pCur->pCursor); - if( pOp->p3type==P3_KEYINFO ){ - pCur->pKeyInfo = (KeyInfo*)pOp->p3; + if( pOp->p4type==P4_KEYINFO ){ + pCur->pKeyInfo = pOp->p4.pKeyInfo; pCur->pIncrKey = &pCur->pKeyInfo->incrKey; pCur->pKeyInfo->enc = ENC(p->db); }else{ pCur->pKeyInfo = 0; pCur->pIncrKey = &pCur->bogusIncrKey; @@ -40002,11 +41507,10 @@ } switch( rc ){ case SQLITE_BUSY: { p->pc = pc; p->rc = rc = SQLITE_BUSY; - p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */ goto vdbe_return; } case SQLITE_OK: { int flags = sqlite3BtreeFlags(pCur->pCursor); /* Sanity checking. Only the lower four bits of the flags byte should @@ -40019,23 +41523,23 @@ rc = SQLITE_CORRUPT_BKPT; goto abort_due_to_error; } pCur->isTable = (flags & BTREE_INTKEY)!=0; pCur->isIndex = (flags & BTREE_ZERODATA)!=0; - /* If P3==0 it means we are expected to open a table. If P3!=0 then + /* If P4==0 it means we are expected to open a table. If P4!=0 then ** we expect to be opening an index. If this is not what happened, ** then the database is corrupt */ - if( (pCur->isTable && pOp->p3type==P3_KEYINFO) - || (pCur->isIndex && pOp->p3type!=P3_KEYINFO) ){ + if( (pCur->isTable && pOp->p4type==P4_KEYINFO) + || (pCur->isIndex && pOp->p4type!=P4_KEYINFO) ){ rc = SQLITE_CORRUPT_BKPT; goto abort_due_to_error; } break; } case SQLITE_EMPTY: { - pCur->isTable = pOp->p3type!=P3_KEYINFO; + pCur->isTable = pOp->p4type!=P4_KEYINFO; pCur->isIndex = !pCur->isTable; rc = SQLITE_OK; break; } default: { @@ -40043,29 +41547,29 @@ } } break; } -/* Opcode: OpenEphemeral P1 P2 P3 +/* Opcode: OpenEphemeral P1 P2 * P4 * ** ** Open a new cursor P1 to a transient table. ** The cursor is always opened read/write even if ** the main database is read-only. The transient or virtual ** table is deleted automatically when the cursor is closed. ** ** P2 is the number of columns in the virtual table. -** The cursor points to a BTree table if P3==0 and to a BTree index -** if P3 is not 0. If P3 is not NULL, it points to a KeyInfo structure +** The cursor points to a BTree table if P4==0 and to a BTree index +** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure ** that defines the format of keys in the index. ** ** This opcode was once called OpenTemp. But that created ** confusion because the term "temp table", might refer either ** to a TEMP table at the SQL level, or to a table opened by ** this opcode. Then this opcode was call OpenVirtual. But ** that created confusion with the whole virtual-table idea. */ -case OP_OpenEphemeral: { /* no-push */ +case OP_OpenEphemeral: { int i = pOp->p1; Cursor *pCx; static const int openFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | @@ -40086,19 +41590,19 @@ /* If a transient index is required, create it by calling ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before ** opening it. If a transient table is required, just use the ** automatically created table with root-page 1 (an INTKEY table). */ - if( pOp->p3 ){ + if( pOp->p4.pKeyInfo ){ int pgno; - assert( pOp->p3type==P3_KEYINFO ); + assert( pOp->p4type==P4_KEYINFO ); rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_ZERODATA); if( rc==SQLITE_OK ){ assert( pgno==MASTER_ROOT+1 ); rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, sqlite3VdbeRecordCompare, - pOp->p3, &pCx->pCursor); - pCx->pKeyInfo = (KeyInfo*)pOp->p3; + pOp->p4.z, &pCx->pCursor); + pCx->pKeyInfo = pOp->p4.pKeyInfo; pCx->pKeyInfo->enc = ENC(p->db); pCx->pIncrKey = &pCx->pKeyInfo->incrKey; } pCx->isTable = 0; }else{ @@ -40110,11 +41614,11 @@ pCx->nField = pOp->p2; pCx->isIndex = !pCx->isTable; break; } -/* Opcode: OpenPseudo P1 * * +/* Opcode: OpenPseudo P1 * * * * ** ** Open a new cursor that points to a fake table that contains a single ** row of data. Any attempt to write a second row of data causes the ** first row to be deleted. All data is deleted when the cursor is ** closed. @@ -40122,11 +41626,11 @@ ** A pseudo-table created by this opcode is useful for holding the ** NEW or OLD tables in a trigger. Also used to hold the a single ** row output from the sorter so that the row can be decomposed into ** individual columns using the OP_Column opcode. */ -case OP_OpenPseudo: { /* no-push */ +case OP_OpenPseudo: { int i = pOp->p1; Cursor *pCx; assert( i>=0 ); pCx = allocateCursor(p, i, -1); if( pCx==0 ) goto no_mem; @@ -40136,101 +41640,104 @@ pCx->isTable = 1; pCx->isIndex = 0; break; } -/* Opcode: Close P1 * * +/* Opcode: Close P1 * * * * ** ** Close a cursor previously opened as P1. If P1 is not ** currently open, this instruction is a no-op. */ -case OP_Close: { /* no-push */ - int i = pOp->p1; - if( i>=0 && i<p->nCursor ){ - sqlite3VdbeFreeCursor(p, p->apCsr[i]); - p->apCsr[i] = 0; - } - break; -} - -/* Opcode: MoveGe P1 P2 * -** -** Pop the top of the stack and use its value as a key. Reposition +case OP_Close: { + int i = pOp->p1; + assert( i>=0 && i<p->nCursor ); + sqlite3VdbeFreeCursor(p, p->apCsr[i]); + p->apCsr[i] = 0; + break; +} + +/* Opcode: MoveGe P1 P2 P3 * * +** +** Use the value in register P3 as a key. Reposition ** cursor P1 so that it points to the smallest entry that is greater -** than or equal to the key that was popped ffrom the stack. +** than or equal to the key in register P3. ** If there are no records greater than or equal to the key and P2 ** is not zero, then jump to P2. ** +** A special feature of this opcode (and different from the +** related OP_MoveGt, OP_MoveLt, and OP_MoveLe) is that if P2 is +** zero and P1 is an SQL table (a b-tree with integer keys) then +** the seek is deferred until it is actually needed. It might be +** the case that the cursor is never accessed. By deferring the +** seek, we avoid unnecessary seeks. +** ** See also: Found, NotFound, Distinct, MoveLt, MoveGt, MoveLe */ -/* Opcode: MoveGt P1 P2 * -** -** Pop the top of the stack and use its value as a key. Reposition +/* Opcode: MoveGt P1 P2 P3 * * +** +** Use the value in register P3 as a key. Reposition ** cursor P1 so that it points to the smallest entry that is greater -** than the key from the stack. -** If there are no records greater than the key and P2 is not zero, +** than the key in register P3. +** If there are no records greater than the key ** then jump to P2. ** ** See also: Found, NotFound, Distinct, MoveLt, MoveGe, MoveLe */ -/* Opcode: MoveLt P1 P2 * -** -** Pop the top of the stack and use its value as a key. Reposition +/* Opcode: MoveLt P1 P2 P3 * * +** +** Use the value in register P3 as a key. Reposition ** cursor P1 so that it points to the largest entry that is less -** than the key from the stack. -** If there are no records less than the key and P2 is not zero, +** than the key in register P3. +** If there are no records less than the key ** then jump to P2. ** ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLe */ -/* Opcode: MoveLe P1 P2 * -** -** Pop the top of the stack and use its value as a key. Reposition +/* Opcode: MoveLe P1 P2 P3 * * +** +** Use the value in register P3 as a key. Reposition ** cursor P1 so that it points to the largest entry that is less than -** or equal to the key that was popped from the stack. -** If there are no records less than or eqal to the key and P2 is not zero, +** or equal to the key. +** If there are no records less than or eqal to the key ** then jump to P2. ** ** See also: Found, NotFound, Distinct, MoveGt, MoveGe, MoveLt */ -case OP_MoveLt: /* no-push */ -case OP_MoveLe: /* no-push */ -case OP_MoveGe: /* no-push */ -case OP_MoveGt: { /* no-push */ - int i = pOp->p1; - Cursor *pC; - - assert( pTos>=p->aStack ); +case OP_MoveLt: /* jump, in3 */ +case OP_MoveLe: /* jump, in3 */ +case OP_MoveGe: /* jump, in3 */ +case OP_MoveGt: { /* jump, in3 */ + int i = pOp->p1; + Cursor *pC; + assert( i>=0 && i<p->nCursor ); pC = p->apCsr[i]; assert( pC!=0 ); if( pC->pCursor!=0 ){ int res, oc; oc = pOp->opcode; pC->nullRow = 0; *pC->pIncrKey = oc==OP_MoveGt || oc==OP_MoveLe; if( pC->isTable ){ - i64 iKey; - sqlite3VdbeMemIntegerify(pTos); - iKey = intToKey(pTos->u.i); - if( pOp->p2==0 && pOp->opcode==OP_MoveGe ){ + i64 iKey = sqlite3VdbeIntValue(pIn3); + if( pOp->p2==0 ){ + assert( pOp->opcode==OP_MoveGe ); pC->movetoTarget = iKey; - pC->deferredMoveto = 1; - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos--; + pC->rowidIsValid = 0; + pC->deferredMoveto = 1; break; } rc = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)iKey, 0, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } - pC->lastRowid = pTos->u.i; + pC->lastRowid = iKey; pC->rowidIsValid = res==0; }else{ - assert( pTos->flags & MEM_Blob ); - ExpandBlob(pTos); - rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res); + assert( pIn3->flags & MEM_Blob ); + ExpandBlob(pIn3); + rc = sqlite3BtreeMoveto(pC->pCursor, pIn3->z, pIn3->n, 0, &res); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } pC->rowidIsValid = 0; } @@ -40259,86 +41766,64 @@ ** see if this is the case. */ res = sqlite3BtreeEof(pC->pCursor); } } + assert( pOp->p2>0 ); if( res ){ - if( pOp->p2>0 ){ - pc = pOp->p2 - 1; - }else{ - pC->nullRow = 1; - } - } - } - Release(pTos); - pTos--; - break; -} - -/* Opcode: Distinct P1 P2 * -** -** Use the top of the stack as a record created using MakeRecord. P1 is a -** cursor on a table that declared as an index. If that table contains an -** entry that matches the top of the stack fall thru. If the top of the stack -** matches no entry in P1 then jump to P2. -** -** The cursor is left pointing at the matching entry if it exists. The -** record on the top of the stack is not popped. -** -** This instruction is similar to NotFound except that this operation -** does not pop the key from the stack. -** -** The instruction is used to implement the DISTINCT operator on SELECT -** statements. The P1 table is not a true index but rather a record of -** all results that have produced so far. -** -** See also: Found, NotFound, MoveTo, IsUnique, NotExists -*/ -/* Opcode: Found P1 P2 * -** -** Top of the stack holds a blob constructed by MakeRecord. P1 is an index. -** If an entry that matches the top of the stack exists in P1 then -** jump to P2. If the top of the stack does not match any entry in P1 + pc = pOp->p2 - 1; + } + } + break; +} + +/* Opcode: Found P1 P2 P3 * * +** +** Register P3 holds a blob constructed by MakeRecord. P1 is an index. +** If an entry that matches the value in register p3 exists in P1 then +** jump to P2. If the P3 value does not match any entry in P1 ** then fall thru. The P1 cursor is left pointing at the matching entry -** if it exists. The blob is popped off the top of the stack. +** if it exists. ** ** This instruction is used to implement the IN operator where the -** left-hand side is a SELECT statement. P1 is not a true index but -** is instead a temporary index that holds the results of the SELECT -** statement. This instruction just checks to see if the left-hand side -** of the IN operator (stored on the top of the stack) exists in the -** result of the SELECT statement. -** -** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists -*/ -/* Opcode: NotFound P1 P2 * -** -** The top of the stack holds a blob constructed by MakeRecord. P1 is +** left-hand side is a SELECT statement. P1 may be a true index, or it +** may be a temporary index that holds the results of the SELECT +** statement. This instruction is also used to implement the +** DISTINCT keyword in SELECT statements. +** +** This instruction checks if index P1 contains a record for which +** the first N serialised values exactly match the N serialised values +** in the record in register P3, where N is the total number of values in +** the P3 record (the P3 record is a prefix of the P1 record). +** +** See also: NotFound, MoveTo, IsUnique, NotExists +*/ +/* Opcode: NotFound P1 P2 P3 * * +** +** Register P3 holds a blob constructed by MakeRecord. P1 is ** an index. If no entry exists in P1 that matches the blob then jump ** to P2. If an entry does existing, fall through. The cursor is left -** pointing to the entry that matches. The blob is popped from the stack. -** -** The difference between this operation and Distinct is that -** Distinct does not pop the key from the stack. -** -** See also: Distinct, Found, MoveTo, NotExists, IsUnique -*/ -case OP_Distinct: /* no-push */ -case OP_NotFound: /* no-push */ -case OP_Found: { /* no-push */ +** pointing to the entry that matches. +** +** See also: Found, MoveTo, NotExists, IsUnique +*/ +case OP_NotFound: /* jump, in3 */ +case OP_Found: { /* jump, in3 */ int i = pOp->p1; int alreadyExists = 0; Cursor *pC; - assert( pTos>=p->aStack ); assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); if( (pC = p->apCsr[i])->pCursor!=0 ){ int res; assert( pC->isTable==0 ); - assert( pTos->flags & MEM_Blob ); - Stringify(pTos, encoding); - rc = sqlite3BtreeMoveto(pC->pCursor, pTos->z, pTos->n, 0, &res); + assert( pIn3->flags & MEM_Blob ); + if( pOp->opcode==OP_Found ){ + pC->pKeyInfo->prefixIsEqual = 1; + } + rc = sqlite3BtreeMoveto(pC->pCursor, pIn3->z, pIn3->n, 0, &res); + pC->pKeyInfo->prefixIsEqual = 0; if( rc!=SQLITE_OK ){ break; } alreadyExists = (res==0); pC->deferredMoveto = 0; @@ -40347,23 +41832,18 @@ if( pOp->opcode==OP_Found ){ if( alreadyExists ) pc = pOp->p2 - 1; }else{ if( !alreadyExists ) pc = pOp->p2 - 1; } - if( pOp->opcode!=OP_Distinct ){ - Release(pTos); - pTos--; - } - break; -} - -/* Opcode: IsUnique P1 P2 * -** -** The top of the stack is an integer record number. Call this -** record number R. The next on the stack is an index key created -** using MakeIdxRec. Call it K. This instruction pops R from the -** stack but it leaves K unchanged. + break; +} + +/* Opcode: IsUnique P1 P2 P3 P4 * +** +** The P3 register contains an integer record number. Call this +** record number R. The P4 register contains an index key created +** using MakeIdxRec. Call it K. ** ** P1 is an index. So it has no data and its key consists of a ** record generated by OP_MakeRecord where the last field is the ** rowid of the entry that the index refers to. ** @@ -40370,29 +41850,30 @@ ** This instruction asks if there is an entry in P1 where the ** fields matches K but the rowid is different from R. ** If there is no such entry, then there is an immediate ** jump to P2. If any entry does exist where the index string ** matches K but the record number is not R, then the record -** number for that entry is pushed onto the stack and control +** number for that entry is written into P3 and control ** falls through to the next instruction. ** -** See also: Distinct, NotFound, NotExists, Found -*/ -case OP_IsUnique: { /* no-push */ - int i = pOp->p1; - Mem *pNos = &pTos[-1]; +** See also: NotFound, NotExists, Found +*/ +case OP_IsUnique: { /* jump, in3 */ + int i = pOp->p1; Cursor *pCx; BtCursor *pCrsr; + Mem *pK; i64 R; /* Pop the value R off the top of the stack */ - assert( pNos>=p->aStack ); - sqlite3VdbeMemIntegerify(pTos); - R = pTos->u.i; - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos--; + assert( pOp->p4type==P4_INT32 ); + assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem ); + pK = &p->aMem[pOp->p4.i]; + sqlite3VdbeMemIntegerify(pIn3); + R = pIn3->u.i; + assert( (pIn3->flags & MEM_Dyn)==0 ); assert( i>=0 && i<p->nCursor ); pCx = p->apCsr[i]; assert( pCx!=0 ); pCrsr = pCx->pCursor; if( pCrsr!=0 ){ @@ -40403,14 +41884,13 @@ int len; /* Number of bytes in K without the rowid at the end */ int szRowid; /* Size of the rowid column at the end of zKey */ /* Make sure K is a string and make zKey point to K */ - assert( pNos->flags & MEM_Blob ); - Stringify(pNos, encoding); - zKey = pNos->z; - nKey = pNos->n; + assert( pK->flags & MEM_Blob ); + zKey = pK->z; + nKey = pK->n; szRowid = sqlite3VdbeIdxRowidLen((u8*)zKey); len = nKey-szRowid; /* Search for an entry in P1 where all but the last four bytes match K. @@ -40448,50 +41928,48 @@ if( v==R ){ pc = pOp->p2 - 1; break; } - /* The final varint of the key is different from R. Push it onto - ** the stack. (The record number of an entry that violates a UNIQUE - ** constraint.) - */ - pTos++; - pTos->u.i = v; - pTos->flags = MEM_Int; - } - break; -} - -/* Opcode: NotExists P1 P2 * -** -** Use the top of the stack as a integer key. If a record with that key -** does not exist in table of P1, then jump to P2. If the record -** does exist, then fall thru. The cursor is left pointing to the -** record if it exists. The integer key is popped from the stack. + /* The final varint of the key is different from R. Store it back + ** into register R3. (The record number of an entry that violates + ** a UNIQUE constraint.) + */ + pIn3->u.i = v; + assert( pIn3->flags==MEM_Int ); + } + break; +} + +/* Opcode: NotExists P1 P2 P3 * * +** +** Use the content of register P3 as a integer key. If a record +** with that key does not exist in table of P1, then jump to P2. +** If the record does exist, then fall thru. The cursor is left +** pointing to the record if it exists. ** ** The difference between this operation and NotFound is that this ** operation assumes the key is an integer and that P1 is a table whereas ** NotFound assumes key is a blob constructed from MakeRecord and ** P1 is an index. ** -** See also: Distinct, Found, MoveTo, NotFound, IsUnique -*/ -case OP_NotExists: { /* no-push */ - int i = pOp->p1; - Cursor *pC; - BtCursor *pCrsr; - assert( pTos>=p->aStack ); +** See also: Found, MoveTo, NotFound, IsUnique +*/ +case OP_NotExists: { /* jump, in3 */ + int i = pOp->p1; + Cursor *pC; + BtCursor *pCrsr; assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){ int res; u64 iKey; - assert( pTos->flags & MEM_Int ); + assert( pIn3->flags & MEM_Int ); assert( p->apCsr[i]->isTable ); - iKey = intToKey(pTos->u.i); + iKey = intToKey(pIn3->u.i); rc = sqlite3BtreeMoveto(pCrsr, 0, iKey, 0,&res); - pC->lastRowid = pTos->u.i; + pC->lastRowid = pIn3->u.i; pC->rowidIsValid = res==0; pC->nullRow = 0; pC->cacheStatus = CACHE_STALE; /* res might be uninitialized if rc!=SQLITE_OK. But if rc!=SQLITE_OK ** processing is about to abort so we really do not care whether or not @@ -40498,51 +41976,48 @@ ** the following jump is taken. (In other words, do not stress over ** the error that valgrind sometimes shows on the next statement when ** running ioerr.test and similar failure-recovery test scripts.) */ if( res!=0 ){ pc = pOp->p2 - 1; - pC->rowidIsValid = 0; - } - } - Release(pTos); - pTos--; - break; -} - -/* Opcode: Sequence P1 * * -** -** Push an integer onto the stack which is the next available -** sequence number for cursor P1. The sequence number on the -** cursor is incremented after the push. -*/ -case OP_Sequence: { - int i = pOp->p1; - assert( pTos>=p->aStack ); + assert( pC->rowidIsValid==0 ); + } + } + break; +} + +/* Opcode: Sequence P1 P2 * * * +** +** Find the next available sequence number for cursor P1. +** Write the sequence number into register P2. +** The sequence number on the cursor is incremented after this +** instruction. +*/ +case OP_Sequence: { /* out2-prerelease */ + int i = pOp->p1; assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); - pTos++; - pTos->u.i = p->apCsr[i]->seqCount++; - pTos->flags = MEM_Int; - break; -} - - -/* Opcode: NewRowid P1 P2 * + pOut->u.i = p->apCsr[i]->seqCount++; + pOut->flags = MEM_Int; + break; +} + + +/* Opcode: NewRowid P1 P2 P3 * * ** ** Get a new integer record number (a.k.a "rowid") used as the key to a table. ** The record number is not previously used as a key in the database -** table that cursor P1 points to. The new record number is pushed -** onto the stack. -** -** If P2>0 then P2 is a memory cell that holds the largest previously +** table that cursor P1 points to. The new record number is written +** written to register P2. +** +** If P3>0 then P3 is a register that holds the largest previously ** generated record number. No new record numbers are allowed to be less ** than this value. When this value reaches its maximum, a SQLITE_FULL -** error is generated. The P2 memory cell is updated with the generated -** record number. This P2 mechanism is used to help implement the +** error is generated. The P3 register is updated with the generated +** record number. This P3 mechanism is used to help implement the ** AUTOINCREMENT feature. */ -case OP_NewRowid: { +case OP_NewRowid: { /* out2-prerelease */ int i = pOp->p1; i64 v = 0; Cursor *pC; assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); @@ -40621,16 +42096,17 @@ } } } #ifndef SQLITE_OMIT_AUTOINCREMENT - if( pOp->p2 ){ + if( pOp->p3 ){ Mem *pMem; - assert( pOp->p2>0 && pOp->p2<p->nMem ); /* P2 is a valid memory cell */ - pMem = &p->aMem[pOp->p2]; + assert( pOp->p3>0 && pOp->p3<=p->nMem ); /* P3 is a valid memory cell */ + pMem = &p->aMem[pOp->p3]; + REGISTER_TRACE(pOp->p3, pMem); sqlite3VdbeMemIntegerify(pMem); - assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P2) holds an integer */ + assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */ if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){ rc = SQLITE_FULL; goto abort_due_to_error; } if( v<pMem->u.i+1 ){ @@ -40646,27 +42122,25 @@ }else{ pC->nextRowidValid = 0; } } if( pC->useRandomRowid ){ - assert( pOp->p2==0 ); /* SQLITE_FULL must have occurred prior to this */ + assert( pOp->p3==0 ); /* SQLITE_FULL must have occurred prior to this */ v = db->priorNewRowid; cnt = 0; do{ - if( v==0 || cnt>2 ){ + if( cnt==0 && (v&0xffffff)==v ){ + v++; + }else{ sqlite3Randomness(sizeof(v), &v); if( cnt<5 ) v &= 0xffffff; - }else{ - unsigned char r; - sqlite3Randomness(1, &r); - v += r + 1; } if( v==0 ) continue; x = intToKey(v); rx = sqlite3BtreeMoveto(pC->pCursor, 0, (u64)x, 0, &res); cnt++; - }while( cnt<1000 && rx==SQLITE_OK && res==0 ); + }while( cnt<100 && rx==SQLITE_OK && res==0 ); db->priorNewRowid = v; if( rx==SQLITE_OK && res==0 ){ rc = SQLITE_FULL; goto abort_due_to_error; } @@ -40673,108 +42147,114 @@ } pC->rowidIsValid = 0; pC->deferredMoveto = 0; pC->cacheStatus = CACHE_STALE; } - pTos++; - pTos->u.i = v; - pTos->flags = MEM_Int; - break; -} - -/* Opcode: Insert P1 P2 P3 + pOut->flags = MEM_Int; + pOut->u.i = v; + break; +} + +/* Opcode: Insert P1 P2 P3 P4 P5 ** ** Write an entry into the table of cursor P1. A new entry is ** created if it doesn't already exist or the data for an existing -** entry is overwritten. The data is the value on the top of the -** stack. The key is the next value down on the stack. The key must -** be an integer. The stack is popped twice by this instruction. -** -** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is -** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P2 is set, +** entry is overwritten. The data is the value stored register +** number P2. The key is stored in register P3. The key must +** be an integer. +** +** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is +** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set, ** then rowid is stored for subsequent return by the -** sqlite3_last_insert_rowid() function (otherwise it's unmodified). -** -** Parameter P3 may point to a string containing the table-name, or +** sqlite3_last_insert_rowid() function (otherwise it is unmodified). +** +** Parameter P4 may point to a string containing the table-name, or ** may be NULL. If it is not NULL, then the update-hook ** (sqlite3.xUpdateCallback) is invoked following a successful insert. +** +** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically +** allocated, then ownership of P2 is transferred to the pseudo-cursor +** and register P2 becomes ephemeral. If the cursor is changed, the +** value of register P2 will then change. Make sure this does not +** cause any problems.) ** ** This instruction only works on tables. The equivalent instruction ** for indices is OP_IdxInsert. */ -case OP_Insert: { /* no-push */ - Mem *pNos = &pTos[-1]; +case OP_Insert: { + Mem *pData = &p->aMem[pOp->p2]; + Mem *pKey = &p->aMem[pOp->p3]; + + i64 iKey; /* The integer ROWID or key for the record to be inserted */ int i = pOp->p1; Cursor *pC; - assert( pNos>=p->aStack ); assert( i>=0 && i<p->nCursor ); - assert( p->apCsr[i]!=0 ); - if( ((pC = p->apCsr[i])->pCursor!=0 || pC->pseudoTable) ){ - i64 iKey; /* The integer ROWID or key for the record to be inserted */ - - assert( pNos->flags & MEM_Int ); + pC = p->apCsr[i]; + assert( pC!=0 ); + assert( pC->pCursor!=0 || pC->pseudoTable ); + assert( pKey->flags & MEM_Int ); + assert( pC->isTable ); + REGISTER_TRACE(pOp->p2, pData); + REGISTER_TRACE(pOp->p3, pKey); + + iKey = intToKey(pKey->u.i); + if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++; + if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = pKey->u.i; + if( pC->nextRowidValid && pKey->u.i>=pC->nextRowid ){ + pC->nextRowidValid = 0; + } + if( pData->flags & MEM_Null ){ + pData->z = 0; + pData->n = 0; + }else{ + assert( pData->flags & (MEM_Blob|MEM_Str) ); + } + if( pC->pseudoTable ){ + sqlite3_free(pC->pData); + pC->iKey = iKey; + pC->nData = pData->n; + if( pData->flags & MEM_Dyn ){ + pC->pData = pData->z; + pData->flags &= ~MEM_Dyn; + pData->flags |= MEM_Ephem; + }else{ + pC->pData = sqlite3_malloc( pC->nData+2 ); + if( !pC->pData ) goto no_mem; + memcpy(pC->pData, pData->z, pC->nData); + pC->pData[pC->nData] = 0; + pC->pData[pC->nData+1] = 0; + } + pC->nullRow = 0; + }else{ + int nZero; + if( pData->flags & MEM_Zero ){ + nZero = pData->u.i; + }else{ + nZero = 0; + } + rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey, + pData->z, pData->n, nZero, + pOp->p5 & OPFLAG_APPEND); + } + + pC->rowidIsValid = 0; + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; + + /* Invoke the update-hook if required. */ + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ + const char *zDb = db->aDb[pC->iDb].zName; + const char *zTbl = pOp->p4.z; + int op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); assert( pC->isTable ); - iKey = intToKey(pNos->u.i); - - if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++; - if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->u.i; - if( pC->nextRowidValid && pNos->u.i>=pC->nextRowid ){ - pC->nextRowidValid = 0; - } - if( pTos->flags & MEM_Null ){ - pTos->z = 0; - pTos->n = 0; - }else{ - assert( pTos->flags & (MEM_Blob|MEM_Str) ); - } - if( pC->pseudoTable ){ - sqlite3_free(pC->pData); - pC->iKey = iKey; - pC->nData = pTos->n; - if( pTos->flags & MEM_Dyn ){ - pC->pData = pTos->z; - pTos->flags = MEM_Null; - }else{ - pC->pData = sqlite3_malloc( pC->nData+2 ); - if( !pC->pData ) goto no_mem; - memcpy(pC->pData, pTos->z, pC->nData); - pC->pData[pC->nData] = 0; - pC->pData[pC->nData+1] = 0; - } - pC->nullRow = 0; - }else{ - int nZero; - if( pTos->flags & MEM_Zero ){ - nZero = pTos->u.i; - }else{ - nZero = 0; - } - rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey, - pTos->z, pTos->n, nZero, - pOp->p2 & OPFLAG_APPEND); - } - - pC->rowidIsValid = 0; - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - - /* Invoke the update-hook if required. */ - if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){ - const char *zDb = db->aDb[pC->iDb].zName; - const char *zTbl = pOp->p3; - int op = ((pOp->p2 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT); - assert( pC->isTable ); - db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey); - assert( pC->iDb>=0 ); - } - } - popStack(&pTos, 2); - - break; -} - -/* Opcode: Delete P1 P2 P3 + db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey); + assert( pC->iDb>=0 ); + } + break; +} + +/* Opcode: Delete P1 P2 * P4 * ** ** Delete the record at which the P1 cursor is currently pointing. ** ** The cursor will be left pointing at either the next or the previous ** record in the table. If it is left pointing at the next record, then @@ -40782,50 +42262,49 @@ ** a record from within an Next loop. ** ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is ** incremented (otherwise not). ** -** If P1 is a pseudo-table, then this instruction is a no-op. -*/ -case OP_Delete: { /* no-push */ +** P1 must not be pseudo-table. It has to be a real table with +** multiple rows. +** +** If P4 is not NULL, then it is the name of the table that P1 is +** pointing to. The update hook will be invoked, if it exists. +** If P4 is not NULL then the P1 cursor must have been positioned +** using OP_NotFound prior to invoking this opcode. +*/ +case OP_Delete: { int i = pOp->p1; + i64 iKey; Cursor *pC; + assert( i>=0 && i<p->nCursor ); pC = p->apCsr[i]; assert( pC!=0 ); - if( pC->pCursor!=0 ){ - i64 iKey; - - /* If the update-hook will be invoked, set iKey to the rowid of the - ** row being deleted. - */ - if( db->xUpdateCallback && pOp->p3 ){ - assert( pC->isTable ); - if( pC->rowidIsValid ){ - iKey = pC->lastRowid; - }else{ - rc = sqlite3BtreeKeySize(pC->pCursor, &iKey); - if( rc ){ - goto abort_due_to_error; - } - iKey = keyToInt(iKey); - } - } - - rc = sqlite3VdbeCursorMoveto(pC); - if( rc ) goto abort_due_to_error; - rc = sqlite3BtreeDelete(pC->pCursor); - pC->nextRowidValid = 0; - pC->cacheStatus = CACHE_STALE; - - /* Invoke the update-hook if required. */ - if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p3 ){ - const char *zDb = db->aDb[pC->iDb].zName; - const char *zTbl = pOp->p3; - db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey); - assert( pC->iDb>=0 ); - } + assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */ + + /* If the update-hook will be invoked, set iKey to the rowid of the + ** row being deleted. + */ + if( db->xUpdateCallback && pOp->p4.z ){ + assert( pC->isTable ); + assert( pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */ + iKey = pC->lastRowid; + } + + rc = sqlite3VdbeCursorMoveto(pC); + if( rc ) goto abort_due_to_error; + rc = sqlite3BtreeDelete(pC->pCursor); + pC->nextRowidValid = 0; + pC->cacheStatus = CACHE_STALE; + + /* Invoke the update-hook if required. */ + if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){ + const char *zDb = db->aDb[pC->iDb].zName; + const char *zTbl = pOp->p4.z; + db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey); + assert( pC->iDb>=0 ); } if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++; break; } @@ -40834,140 +42313,131 @@ ** This opcode resets the VMs internal change counter to 0. If P1 is true, ** then the value of the change counter is copied to the database handle ** change counter (returned by subsequent calls to sqlite3_changes()) ** before it is reset. This is used by trigger programs. */ -case OP_ResetCount: { /* no-push */ +case OP_ResetCount: { if( pOp->p1 ){ sqlite3VdbeSetChanges(db, p->nChange); } p->nChange = 0; break; } -/* Opcode: RowData P1 * * -** -** Push onto the stack the complete row data for cursor P1. -** There is no interpretation of the data. It is just copied -** onto the stack exactly as it is found in the database file. -** -** If the cursor is not pointing to a valid row, a NULL is pushed -** onto the stack. -*/ -/* Opcode: RowKey P1 * * -** -** Push onto the stack the complete row key for cursor P1. -** There is no interpretation of the key. It is just copied -** onto the stack exactly as it is found in the database file. -** -** If the cursor is not pointing to a valid row, a NULL is pushed -** onto the stack. -*/ -case OP_RowKey: -case OP_RowData: { +/* Opcode: RowData P1 P2 * * * +** +** Write into register P2 the complete row data for cursor P1. +** There is no interpretation of the data. +** It is just copied onto the P2 register exactly as +** it is found in the database file. +** +** If the P1 cursor must be pointing to a valid row (not a NULL row) +** of a real table, not a pseudo-table. +*/ +/* Opcode: RowKey P1 P2 * * * +** +** Write into register P2 the complete row key for cursor P1. +** There is no interpretation of the data. +** The key is copied onto the P3 register exactly as +** it is found in the database file. +** +** If the P1 cursor must be pointing to a valid row (not a NULL row) +** of a real table, not a pseudo-table. +*/ +case OP_RowKey: /* out2-prerelease */ +case OP_RowData: { /* out2-prerelease */ int i = pOp->p1; Cursor *pC; + BtCursor *pCrsr; u32 n; /* Note that RowKey and RowData are really exactly the same instruction */ - pTos++; assert( i>=0 && i<p->nCursor ); pC = p->apCsr[i]; assert( pC->isTable || pOp->opcode==OP_RowKey ); assert( pC->isIndex || pOp->opcode==OP_RowData ); assert( pC!=0 ); - if( pC->nullRow ){ - pTos->flags = MEM_Null; - }else if( pC->pCursor!=0 ){ - BtCursor *pCrsr = pC->pCursor; - rc = sqlite3VdbeCursorMoveto(pC); - if( rc ) goto abort_due_to_error; - if( pC->nullRow ){ - pTos->flags = MEM_Null; - break; - }else if( pC->isIndex ){ - i64 n64; - assert( !pC->isTable ); - sqlite3BtreeKeySize(pCrsr, &n64); - if( n64>SQLITE_MAX_LENGTH ){ - goto too_big; - } - n = n64; - }else{ - sqlite3BtreeDataSize(pCrsr, &n); - } + assert( pC->nullRow==0 ); + assert( pC->pseudoTable==0 ); + assert( pC->pCursor!=0 ); + pCrsr = pC->pCursor; + rc = sqlite3VdbeCursorMoveto(pC); + if( rc ) goto abort_due_to_error; + if( pC->isIndex ){ + i64 n64; + assert( !pC->isTable ); + sqlite3BtreeKeySize(pCrsr, &n64); + if( n64>SQLITE_MAX_LENGTH ){ + goto too_big; + } + n = n64; + }else{ + sqlite3BtreeDataSize(pCrsr, &n); if( n>SQLITE_MAX_LENGTH ){ goto too_big; } - pTos->n = n; - if( n<=NBFS ){ - pTos->flags = MEM_Blob | MEM_Short; - pTos->z = pTos->zShort; - }else{ - char *z = sqlite3_malloc( n ); - if( z==0 ) goto no_mem; - pTos->flags = MEM_Blob | MEM_Dyn; - pTos->xDel = 0; - pTos->z = z; - } - if( pC->isIndex ){ - rc = sqlite3BtreeKey(pCrsr, 0, n, pTos->z); - }else{ - rc = sqlite3BtreeData(pCrsr, 0, n, pTos->z); - } - }else if( pC->pseudoTable ){ - pTos->n = pC->nData; - assert( pC->nData<=SQLITE_MAX_LENGTH ); - pTos->z = pC->pData; - pTos->flags = MEM_Blob|MEM_Ephem; - }else{ - pTos->flags = MEM_Null; - } - pTos->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ - break; -} - -/* Opcode: Rowid P1 * * -** -** Push onto the stack an integer which is the key of the table entry that -** P1 is currently point to. -*/ -case OP_Rowid: { + } + pOut->n = n; + if( n<=NBFS ){ + pOut->flags = MEM_Blob | MEM_Short; + pOut->z = pOut->zShort; + }else{ + char *z = sqlite3_malloc( n ); + if( z==0 ) goto no_mem; + pOut->flags = MEM_Blob | MEM_Dyn; + pOut->xDel = 0; + pOut->z = z; + } + if( pC->isIndex ){ + rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z); + }else{ + rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z); + } + pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */ + UPDATE_MAX_BLOBSIZE(pOut); + break; +} + +/* Opcode: Rowid P1 P2 * * * +** +** Store in register P2 an integer which is the key of the table entry that +** P1 is currently point to. If p2==0 then push the integer. +*/ +case OP_Rowid: { /* out2-prerelease */ int i = pOp->p1; Cursor *pC; i64 v; assert( i>=0 && i<p->nCursor ); pC = p->apCsr[i]; assert( pC!=0 ); rc = sqlite3VdbeCursorMoveto(pC); if( rc ) goto abort_due_to_error; - pTos++; if( pC->rowidIsValid ){ v = pC->lastRowid; }else if( pC->pseudoTable ){ v = keyToInt(pC->iKey); - }else if( pC->nullRow || pC->pCursor==0 ){ - pTos->flags = MEM_Null; + }else if( pC->nullRow ){ + /* Leave the rowid set to a NULL */ break; }else{ assert( pC->pCursor!=0 ); sqlite3BtreeKeySize(pC->pCursor, &v); v = keyToInt(v); } - pTos->u.i = v; - pTos->flags = MEM_Int; - break; -} - -/* Opcode: NullRow P1 * * + pOut->u.i = v; + pOut->flags = MEM_Int; + break; +} + +/* Opcode: NullRow P1 * * * * ** ** Move the cursor P1 to a null row. Any OP_Column operations -** that occur while the cursor is on the null row will always push -** a NULL onto the stack. -*/ -case OP_NullRow: { /* no-push */ +** that occur while the cursor is on the null row will always +** write a NULL. +*/ +case OP_NullRow: { int i = pOp->p1; Cursor *pC; assert( i>=0 && i<p->nCursor ); pC = p->apCsr[i]; @@ -40975,43 +42445,41 @@ pC->nullRow = 1; pC->rowidIsValid = 0; break; } -/* Opcode: Last P1 P2 * +/* Opcode: Last P1 P2 * * * ** ** The next use of the Rowid or Column or Next instruction for P1 ** will refer to the last entry in the database table or index. ** If the table or index is empty and P2>0, then jump immediately to P2. ** If P2 is 0 or if the table or index is not empty, fall through ** to the following instruction. */ -case OP_Last: { /* no-push */ +case OP_Last: { /* jump */ int i = pOp->p1; Cursor *pC; BtCursor *pCrsr; + int res; assert( i>=0 && i<p->nCursor ); pC = p->apCsr[i]; assert( pC!=0 ); - if( (pCrsr = pC->pCursor)!=0 ){ - int res; - rc = sqlite3BtreeLast(pCrsr, &res); - pC->nullRow = res; - pC->deferredMoveto = 0; - pC->cacheStatus = CACHE_STALE; - if( res && pOp->p2>0 ){ - pc = pOp->p2 - 1; - } - }else{ - pC->nullRow = 0; - } - break; -} - - -/* Opcode: Sort P1 P2 * + pCrsr = pC->pCursor; + assert( pCrsr!=0 ); + rc = sqlite3BtreeLast(pCrsr, &res); + pC->nullRow = res; + pC->deferredMoveto = 0; + pC->cacheStatus = CACHE_STALE; + if( res && pOp->p2>0 ){ + pc = pOp->p2 - 1; + } + break; +} + + +/* Opcode: Sort P1 P2 * * * ** ** This opcode does exactly the same thing as OP_Rewind except that ** it increments an undocumented global variable used for testing. ** ** Sorting is accomplished by writing records into a sorting index, @@ -41019,26 +42487,26 @@ ** end. We use the OP_Sort opcode instead of OP_Rewind to do the ** rewinding so that the global variable will be incremented and ** regression tests can determine whether or not the optimizer is ** correctly optimizing out sorts. */ -case OP_Sort: { /* no-push */ +case OP_Sort: { /* jump */ #ifdef SQLITE_TEST sqlite3_sort_count++; sqlite3_search_count--; #endif /* Fall through into OP_Rewind */ } -/* Opcode: Rewind P1 P2 * +/* Opcode: Rewind P1 P2 * * * ** ** The next use of the Rowid or Column or Next instruction for P1 ** will refer to the first entry in the database table or index. ** If the table or index is empty and P2>0, then jump immediately to P2. ** If P2 is 0 or if the table or index is not empty, fall through ** to the following instruction. */ -case OP_Rewind: { /* no-push */ +case OP_Rewind: { /* jump */ int i = pOp->p1; Cursor *pC; BtCursor *pCrsr; int res; @@ -41052,268 +42520,243 @@ pC->cacheStatus = CACHE_STALE; }else{ res = 1; } pC->nullRow = res; - if( res && pOp->p2>0 ){ + assert( pOp->p2>0 && pOp->p2<p->nOp ); + if( res ){ pc = pOp->p2 - 1; } break; } -/* Opcode: Next P1 P2 * +/* Opcode: Next P1 P2 * * * ** ** Advance cursor P1 so that it points to the next key/data pair in its ** table or index. If there are no more key/value pairs then fall through ** to the following instruction. But if the cursor advance was successful, ** jump immediately to P2. ** +** The P1 cursor must be for a real table, not a pseudo-table. +** ** See also: Prev */ -/* Opcode: Prev P1 P2 * +/* Opcode: Prev P1 P2 * * * ** ** Back up cursor P1 so that it points to the previous key/data pair in its ** table or index. If there is no previous key/value pairs then fall through ** to the following instruction. But if the cursor backup was successful, ** jump immediately to P2. -*/ -case OP_Prev: /* no-push */ -case OP_Next: { /* no-push */ +** +** The P1 cursor must be for a real table, not a pseudo-table. +*/ +case OP_Prev: /* jump */ +case OP_Next: { /* jump */ Cursor *pC; BtCursor *pCrsr; + int res; CHECK_FOR_INTERRUPT; assert( pOp->p1>=0 && pOp->p1<p->nCursor ); pC = p->apCsr[pOp->p1]; if( pC==0 ){ break; /* See ticket #2273 */ } - if( (pCrsr = pC->pCursor)!=0 ){ - int res; - if( pC->nullRow ){ - res = 1; - }else{ - assert( pC->deferredMoveto==0 ); - rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) : - sqlite3BtreePrevious(pCrsr, &res); - pC->nullRow = res; - pC->cacheStatus = CACHE_STALE; - } + pCrsr = pC->pCursor; + assert( pCrsr ); + if( pC->nullRow ){ + res = 1; + }else{ + assert( pC->deferredMoveto==0 ); + rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(pCrsr, &res) : + sqlite3BtreePrevious(pCrsr, &res); + pC->nullRow = res; + pC->cacheStatus = CACHE_STALE; if( res==0 ){ pc = pOp->p2 - 1; #ifdef SQLITE_TEST sqlite3_search_count++; #endif } - }else{ - pC->nullRow = 1; } pC->rowidIsValid = 0; break; } -/* Opcode: IdxInsert P1 P2 * -** -** The top of the stack holds a SQL index key made using either the -** MakeIdxRec or MakeRecord instructions. This opcode writes that key +/* Opcode: IdxInsert P1 P2 P3 * * +** +** Register P2 holds a SQL index key made using the +** MakeIdxRec instructions. This opcode writes that key ** into the index P1. Data for the entry is nil. ** -** P2 is a flag that provides a hint to the b-tree layer that this +** P3 is a flag that provides a hint to the b-tree layer that this ** insert is likely to be an append. ** ** This instruction only works for indices. The equivalent instruction ** for tables is OP_Insert. */ -case OP_IdxInsert: { /* no-push */ +case OP_IdxInsert: { /* in2 */ int i = pOp->p1; Cursor *pC; BtCursor *pCrsr; - assert( pTos>=p->aStack ); assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); - assert( pTos->flags & MEM_Blob ); + assert( pIn2->flags & MEM_Blob ); if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){ assert( pC->isTable==0 ); - rc = ExpandBlob(pTos); + rc = ExpandBlob(pIn2); if( rc==SQLITE_OK ){ - int nKey = pTos->n; - const char *zKey = pTos->z; - rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p2); + int nKey = pIn2->n; + const char *zKey = pIn2->z; + rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3); assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; } } - Release(pTos); - pTos--; - break; -} - -/* Opcode: IdxDelete P1 * * -** -** The top of the stack is an index key built using the either the -** MakeIdxRec or MakeRecord opcodes. -** This opcode removes that entry from the index. -*/ -case OP_IdxDelete: { /* no-push */ + break; +} + +/* Opcode: IdxDelete P1 P2 * * * +** +** The content of register P2 is an index key built using the either the +** MakeIdxRec opcode. Removes that entry from the index. +*/ +case OP_IdxDelete: { /* in2 */ int i = pOp->p1; Cursor *pC; BtCursor *pCrsr; - assert( pTos>=p->aStack ); - assert( pTos->flags & MEM_Blob ); + assert( pIn2->flags & MEM_Blob ); assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){ int res; - rc = sqlite3BtreeMoveto(pCrsr, pTos->z, pTos->n, 0, &res); + rc = sqlite3BtreeMoveto(pCrsr, pIn2->z, pIn2->n, 0, &res); if( rc==SQLITE_OK && res==0 ){ rc = sqlite3BtreeDelete(pCrsr); } assert( pC->deferredMoveto==0 ); pC->cacheStatus = CACHE_STALE; } - Release(pTos); - pTos--; - break; -} - -/* Opcode: IdxRowid P1 * * -** -** Push onto the stack an integer which is the last entry in the record at + break; +} + +/* Opcode: IdxRowid P1 P2 * * * +** +** Write into register P2 an integer which is the last entry in the record at ** the end of the index key pointed to by cursor P1. This integer should be ** the rowid of the table entry to which this index entry points. ** ** See also: Rowid, MakeIdxRec. */ -case OP_IdxRowid: { +case OP_IdxRowid: { /* out2-prerelease */ int i = pOp->p1; BtCursor *pCrsr; Cursor *pC; assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); - pTos++; - pTos->flags = MEM_Null; if( (pCrsr = (pC = p->apCsr[i])->pCursor)!=0 ){ i64 rowid; assert( pC->deferredMoveto==0 ); assert( pC->isTable==0 ); - if( pC->nullRow ){ - pTos->flags = MEM_Null; - }else{ + if( !pC->nullRow ){ rc = sqlite3VdbeIdxRowid(pCrsr, &rowid); if( rc!=SQLITE_OK ){ goto abort_due_to_error; } - pTos->flags = MEM_Int; - pTos->u.i = rowid; - } - } - break; -} - -/* Opcode: IdxGT P1 P2 * -** -** The top of the stack is an index entry that omits the ROWID. Compare -** the top of stack against the index that P1 is currently pointing to. + pOut->flags = MEM_Int; + pOut->u.i = rowid; + } + } + break; +} + +/* Opcode: IdxGE P1 P2 P3 * P5 +** +** The value in register P3 is an index entry that omits the ROWID. Compare +** this value against the index that P1 is currently pointing to. ** Ignore the ROWID on the P1 index. ** -** The top of the stack might have fewer columns that P1. -** -** If the P1 index entry is greater than the top of the stack -** then jump to P2. Otherwise fall through to the next instruction. -** In either case, the stack is popped once. -*/ -/* Opcode: IdxGE P1 P2 P3 -** -** The top of the stack is an index entry that omits the ROWID. Compare -** the top of stack against the index that P1 is currently pointing to. -** Ignore the ROWID on the P1 index. -** -** If the P1 index entry is greater than or equal to the top of the stack -** then jump to P2. Otherwise fall through to the next instruction. -** In either case, the stack is popped once. -** -** If P3 is the "+" string (or any other non-NULL string) then the -** index taken from the top of the stack is temporarily increased by -** an epsilon prior to the comparison. This make the opcode work -** like IdxGT except that if the key from the stack is a prefix of +** If the P1 index entry is greater than or equal to the value in +** register P3 then jump to P2. Otherwise fall through to the next +** instruction. +** +** If P5 is non-zero then the value in register P3 is temporarily +** increased by an epsilon prior to the comparison. This make the opcode work +** like IdxGT except that if the key from register P3 is a prefix of ** the key in the cursor, the result is false whereas it would be ** true with IdxGT. */ -/* Opcode: IdxLT P1 P2 P3 -** -** The top of the stack is an index entry that omits the ROWID. Compare -** the top of stack against the index that P1 is currently pointing to. +/* Opcode: IdxLT P1 P2 P3 * P5 +** +** The value in register P3 is an index entry that omits the ROWID. Compare +** the this value against the index that P1 is currently pointing to. ** Ignore the ROWID on the P1 index. ** -** If the P1 index entry is less than the top of the stack +** If the P1 index entry is less than the register P3 value ** then jump to P2. Otherwise fall through to the next instruction. -** In either case, the stack is popped once. -** -** If P3 is the "+" string (or any other non-NULL string) then the -** index taken from the top of the stack is temporarily increased by +** +** If P5 is non-zero then the +** index taken from register P3 is temporarily increased by ** an epsilon prior to the comparison. This makes the opcode work ** like IdxLE. */ -case OP_IdxLT: /* no-push */ -case OP_IdxGT: /* no-push */ -case OP_IdxGE: { /* no-push */ +case OP_IdxLT: /* jump, in3 */ +case OP_IdxGE: { /* jump, in3 */ int i= pOp->p1; Cursor *pC; assert( i>=0 && i<p->nCursor ); assert( p->apCsr[i]!=0 ); - assert( pTos>=p->aStack ); if( (pC = p->apCsr[i])->pCursor!=0 ){ int res; - assert( pTos->flags & MEM_Blob ); /* Created using OP_MakeRecord */ + assert( pIn3->flags & MEM_Blob ); /* Created using OP_MakeRecord */ assert( pC->deferredMoveto==0 ); - ExpandBlob(pTos); - *pC->pIncrKey = pOp->p3!=0; - assert( pOp->p3==0 || pOp->opcode!=OP_IdxGT ); - rc = sqlite3VdbeIdxKeyCompare(pC, pTos->n, (u8*)pTos->z, &res); + ExpandBlob(pIn3); + assert( pOp->p5==0 || pOp->p5==1 ); + *pC->pIncrKey = pOp->p5; + rc = sqlite3VdbeIdxKeyCompare(pC, pIn3->n, (u8*)pIn3->z, &res); *pC->pIncrKey = 0; if( rc!=SQLITE_OK ){ break; } if( pOp->opcode==OP_IdxLT ){ res = -res; - }else if( pOp->opcode==OP_IdxGE ){ + }else{ + assert( pOp->opcode==OP_IdxGE ); res++; } if( res>0 ){ pc = pOp->p2 - 1 ; } } - Release(pTos); - pTos--; - break; -} - -/* Opcode: Destroy P1 P2 * + break; +} + +/* Opcode: Destroy P1 P2 P3 * * ** ** Delete an entire database table or index whose root page in the database ** file is given by P1. ** -** The table being destroyed is in the main database file if P2==0. If -** P2==1 then the table to be clear is in the auxiliary database file +** The table being destroyed is in the main database file if P3==0. If +** P3==1 then the table to be clear is in the auxiliary database file ** that is used to store tables create using CREATE TEMPORARY TABLE. ** ** If AUTOVACUUM is enabled then it is possible that another root page ** might be moved into the newly deleted root page in order to keep all ** root pages contiguous at the beginning of the database. The former ** value of the root page that moved - its value before the move occurred - -** is pushed onto the stack. If no page movement was required (because -** the table being dropped was already the last one in the database) then -** a zero is pushed onto the stack. If AUTOVACUUM is disabled -** then a zero is pushed onto the stack. +** is stored in register P2. If no page +** movement was required (because the table being dropped was already +** the last one in the database) then a zero is stored in register P2. +** If AUTOVACUUM is disabled then a zero is stored in register P2. ** ** See also: Clear */ -case OP_Destroy: { +case OP_Destroy: { /* out2-prerelease */ int iMoved; int iCnt; #ifndef SQLITE_OMIT_VIRTUALTABLE Vdbe *pVdbe; iCnt = 0; @@ -41325,20 +42768,21 @@ #else iCnt = db->activeVdbeCnt; #endif if( iCnt>1 ){ rc = SQLITE_LOCKED; - }else{ + p->errorAction = OE_Abort; + }else{ + int iDb = pOp->p3; assert( iCnt==1 ); - assert( (p->btreeMask & (1<<pOp->p2))!=0 ); - rc = sqlite3BtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1, &iMoved); - pTos++; - pTos->flags = MEM_Int; - pTos->u.i = iMoved; + assert( (p->btreeMask & (1<<iDb))!=0 ); + rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved); + pOut->flags = MEM_Int; + pOut->u.i = iMoved; #ifndef SQLITE_OMIT_AUTOVACUUM if( rc==SQLITE_OK && iMoved!=0 ){ - sqlite3RootPageMoved(&db->aDb[pOp->p2], iMoved, pOp->p1); + sqlite3RootPageMoved(&db->aDb[iDb], iMoved, pOp->p1); } #endif } break; } @@ -41353,73 +42797,40 @@ ** P2==1 then the table to be clear is in the auxiliary database file ** that is used to store tables create using CREATE TEMPORARY TABLE. ** ** See also: Destroy */ -case OP_Clear: { /* no-push */ - - /* For consistency with the way other features of SQLite operate - ** with a truncate, we will also skip the update callback. - */ -#if 0 - Btree *pBt = db->aDb[pOp->p2].pBt; - if( db->xUpdateCallback && pOp->p3 ){ - const char *zDb = db->aDb[pOp->p2].zName; - const char *zTbl = pOp->p3; - BtCursor *pCur = 0; - int fin = 0; - - rc = sqlite3BtreeCursor(pBt, pOp->p1, 0, 0, 0, &pCur); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - for( - rc=sqlite3BtreeFirst(pCur, &fin); - rc==SQLITE_OK && !fin; - rc=sqlite3BtreeNext(pCur, &fin) - ){ - i64 iKey; - rc = sqlite3BtreeKeySize(pCur, &iKey); - if( rc ){ - break; - } - iKey = keyToInt(iKey); - db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, iKey); - } - sqlite3BtreeCloseCursor(pCur); - if( rc!=SQLITE_OK ){ - goto abort_due_to_error; - } - } -#endif +case OP_Clear: { assert( (p->btreeMask & (1<<pOp->p2))!=0 ); rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1); break; } -/* Opcode: CreateTable P1 * * -** -** Allocate a new table in the main database file if P2==0 or in the -** auxiliary database file if P2==1. Push the page number -** for the root page of the new table onto the stack. +/* Opcode: CreateTable P1 P2 * * * +** +** Allocate a new table in the main database file if P1==0 or in the +** auxiliary database file if P1==1 or in an attached database if +** P1>1. Write the root page number of the new table into +** register P2 ** ** The difference between a table and an index is this: A table must ** have a 4-byte integer key and can have arbitrary data. An index ** has an arbitrary key but no data. ** ** See also: CreateIndex */ -/* Opcode: CreateIndex P1 * * -** -** Allocate a new index in the main database file if P2==0 or in the -** auxiliary database file if P2==1. Push the page number of the -** root page of the new index onto the stack. +/* Opcode: CreateIndex P1 P2 * * * +** +** Allocate a new index in the main database file if P1==0 or in the +** auxiliary database file if P1==1 or in an attached database if +** P1>1. Write the root page number of the new table into +** register P2. ** ** See documentation on OP_CreateTable for additional information. */ -case OP_CreateIndex: -case OP_CreateTable: { +case OP_CreateIndex: /* out2-prerelease */ +case OP_CreateTable: { /* out2-prerelease */ int pgno; int flags; Db *pDb; assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( (p->btreeMask & (1<<pOp->p1))!=0 ); @@ -41430,33 +42841,30 @@ flags = BTREE_LEAFDATA|BTREE_INTKEY; }else{ flags = BTREE_ZERODATA; } rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags); - pTos++; - if( rc==SQLITE_OK ){ - pTos->u.i = pgno; - pTos->flags = MEM_Int; - }else{ - pTos->flags = MEM_Null; - } - break; -} - -/* Opcode: ParseSchema P1 P2 P3 + if( rc==SQLITE_OK ){ + pOut->u.i = pgno; + pOut->flags = MEM_Int; + } + break; +} + +/* Opcode: ParseSchema P1 P2 * P4 * ** ** Read and parse all entries from the SQLITE_MASTER table of database P1 -** that match the WHERE clause P3. P2 is the "force" flag. Always do +** that match the WHERE clause P4. P2 is the "force" flag. Always do ** the parsing if P2 is true. If P2 is false, then this routine is a ** no-op if the schema is not currently loaded. In other words, if P2 ** is false, the SQLITE_MASTER table is only parsed if the rest of the ** schema is already loaded into the symbol table. ** ** This opcode invokes the parser to create a new virtual machine, ** then runs the new virtual machine. It is thus a reentrant opcode. */ -case OP_ParseSchema: { /* no-push */ +case OP_ParseSchema: { char *zSql; int iDb = pOp->p1; const char *zMaster; InitData initData; @@ -41468,176 +42876,169 @@ initData.db = db; initData.iDb = pOp->p1; initData.pzErrMsg = &p->zErrMsg; zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s", - db->aDb[iDb].zName, zMaster, pOp->p3); + db->aDb[iDb].zName, zMaster, pOp->p4.z); if( zSql==0 ) goto no_mem; - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); assert( db->init.busy==0 ); db->init.busy = 1; assert( !db->mallocFailed ); rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0); if( rc==SQLITE_ABORT ) rc = initData.rc; sqlite3_free(zSql); db->init.busy = 0; - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); if( rc==SQLITE_NOMEM ){ goto no_mem; } break; } #if !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) -/* Opcode: LoadAnalysis P1 * * +/* Opcode: LoadAnalysis P1 * * * * ** ** Read the sqlite_stat1 table for database P1 and load the content ** of that table into the internal index hash table. This will cause ** the analysis to be used when preparing all subsequent queries. */ -case OP_LoadAnalysis: { /* no-push */ +case OP_LoadAnalysis: { int iDb = pOp->p1; assert( iDb>=0 && iDb<db->nDb ); rc = sqlite3AnalysisLoad(db, iDb); break; } #endif /* !defined(SQLITE_OMIT_ANALYZE) && !defined(SQLITE_OMIT_PARSER) */ -/* Opcode: DropTable P1 * P3 +/* Opcode: DropTable P1 * * P4 * +** +** Remove the internal (in-memory) data structures that describe +** the table named P4 in database P1. This is called after a table +** is dropped in order to keep the internal representation of the +** schema consistent with what is on disk. +*/ +case OP_DropTable: { + sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z); + break; +} + +/* Opcode: DropIndex P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe -** the table named P3 in database P1. This is called after a table +** the index named P4 in database P1. This is called after an index ** is dropped in order to keep the internal representation of the ** schema consistent with what is on disk. */ -case OP_DropTable: { /* no-push */ - sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p3); - break; -} - -/* Opcode: DropIndex P1 * P3 +case OP_DropIndex: { + sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z); + break; +} + +/* Opcode: DropTrigger P1 * * P4 * ** ** Remove the internal (in-memory) data structures that describe -** the index named P3 in database P1. This is called after an index +** the trigger named P4 in database P1. This is called after a trigger ** is dropped in order to keep the internal representation of the ** schema consistent with what is on disk. */ -case OP_DropIndex: { /* no-push */ - sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p3); - break; -} - -/* Opcode: DropTrigger P1 * P3 -** -** Remove the internal (in-memory) data structures that describe -** the trigger named P3 in database P1. This is called after a trigger -** is dropped in order to keep the internal representation of the -** schema consistent with what is on disk. -*/ -case OP_DropTrigger: { /* no-push */ - sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p3); +case OP_DropTrigger: { + sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z); break; } #ifndef SQLITE_OMIT_INTEGRITY_CHECK -/* Opcode: IntegrityCk P1 P2 * -** -** Do an analysis of the currently open database. Push onto the -** stack the text of an error message describing any problems. -** If no problems are found, push a NULL onto the stack. -** -** P1 is the address of a memory cell that contains the maximum -** number of allowed errors. At most mem[P1] errors will be reported. -** In other words, the analysis stops as soon as mem[P1] errors are -** seen. Mem[P1] is updated with the number of errors remaining. +/* Opcode: IntegrityCk P1 P2 P3 * P5 +** +** Do an analysis of the currently open database. Store in +** register P1 the text of an error message describing any problems. +** If no problems are found, store a NULL in register P1. +** +** The register P3 contains the maximum number of allowed errors. +** At most reg(P3) errors will be reported. +** In other words, the analysis stops as soon as reg(P1) errors are +** seen. Reg(P1) is updated with the number of errors remaining. ** ** The root page numbers of all tables in the database are integer -** values on the stack. This opcode pulls as many integers as it -** can off of the stack and uses those numbers as the root pages. -** -** If P2 is not zero, the check is done on the auxiliary database +** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables +** total. +** +** If P5 is not zero, the check is done on the auxiliary database ** file, not the main database file. ** ** This opcode is used to implement the integrity_check pragma. */ case OP_IntegrityCk: { - int nRoot; - int *aRoot; - int j; - int nErr; - char *z; - Mem *pnErr; - - for(nRoot=0; &pTos[-nRoot]>=p->aStack; nRoot++){ - if( (pTos[-nRoot].flags & MEM_Int)==0 ) break; - } + int nRoot; /* Number of tables to check. (Number of root pages.) */ + int *aRoot; /* Array of rootpage numbers for tables to be checked */ + int j; /* Loop counter */ + int nErr; /* Number of errors reported */ + char *z; /* Text of the error report */ + Mem *pnErr; /* Register keeping track of errors remaining */ + + nRoot = pOp->p2; assert( nRoot>0 ); aRoot = sqlite3_malloc( sizeof(int)*(nRoot+1) ); if( aRoot==0 ) goto no_mem; - j = pOp->p1; - assert( j>=0 && j<p->nMem ); - pnErr = &p->aMem[j]; + assert( pOp->p3>0 && pOp->p3<=p->nMem ); + pnErr = &p->aMem[pOp->p3]; assert( (pnErr->flags & MEM_Int)!=0 ); + assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 ); + pIn1 = &p->aMem[pOp->p1]; for(j=0; j<nRoot; j++){ - aRoot[j] = (pTos-j)->u.i; + aRoot[j] = sqlite3VdbeIntValue(&pIn1[j]); } aRoot[j] = 0; - popStack(&pTos, nRoot); - pTos++; - assert( pOp->p2>=0 && pOp->p2<db->nDb ); - assert( (p->btreeMask & (1<<pOp->p2))!=0 ); - z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot, + assert( pOp->p5<db->nDb ); + assert( (p->btreeMask & (1<<pOp->p5))!=0 ); + z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot, pnErr->u.i, &nErr); pnErr->u.i -= nErr; + sqlite3VdbeMemSetNull(pIn1); if( nErr==0 ){ assert( z==0 ); - pTos->flags = MEM_Null; - }else{ - pTos->z = z; - pTos->n = strlen(z); - pTos->flags = MEM_Str | MEM_Dyn | MEM_Term; - pTos->xDel = 0; - } - pTos->enc = SQLITE_UTF8; - sqlite3VdbeChangeEncoding(pTos, encoding); + }else{ + pIn1->z = z; + pIn1->n = strlen(z); + pIn1->flags = MEM_Str | MEM_Dyn | MEM_Term; + pIn1->xDel = 0; + } + pIn1->enc = SQLITE_UTF8; + UPDATE_MAX_BLOBSIZE(pIn1); + sqlite3VdbeChangeEncoding(pIn1, encoding); sqlite3_free(aRoot); break; } #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ -/* Opcode: FifoWrite * * * -** -** Write the integer on the top of the stack -** into the Fifo. -*/ -case OP_FifoWrite: { /* no-push */ - assert( pTos>=p->aStack ); - sqlite3VdbeMemIntegerify(pTos); - if( sqlite3VdbeFifoPush(&p->sFifo, pTos->u.i)==SQLITE_NOMEM ){ +/* Opcode: FifoWrite P1 * * * * +** +** Write the integer from register P1 into the Fifo. +*/ +case OP_FifoWrite: { /* in1 */ + if( sqlite3VdbeFifoPush(&p->sFifo, sqlite3VdbeIntValue(pIn1))==SQLITE_NOMEM ){ goto no_mem; } - assert( (pTos->flags & MEM_Dyn)==0 ); - pTos--; - break; -} - -/* Opcode: FifoRead * P2 * -** -** Attempt to read a single integer from the Fifo -** and push it onto the stack. If the Fifo is empty -** push nothing but instead jump to P2. -*/ -case OP_FifoRead: { - i64 v; + break; +} + +/* Opcode: FifoRead P1 P2 * * * +** +** Attempt to read a single integer from the Fifo. Store that +** integer in register P1. +** +** If the Fifo is empty jump to P2. +*/ +case OP_FifoRead: { /* jump */ CHECK_FOR_INTERRUPT; - if( sqlite3VdbeFifoPop(&p->sFifo, &v)==SQLITE_DONE ){ - pc = pOp->p2 - 1; - }else{ - pTos++; - pTos->u.i = v; - pTos->flags = MEM_Int; + assert( pOp->p1>0 && pOp->p1<=p->nMem ); + pOut = &p->aMem[pOp->p1]; + Release(pOut); + pOut->flags = MEM_Int; + if( sqlite3VdbeFifoPop(&p->sFifo, &pOut->u.i)==SQLITE_DONE ){ + pc = pOp->p2 - 1; } break; } #ifndef SQLITE_OMIT_TRIGGER @@ -41645,11 +43046,11 @@ ** ** Save the current Vdbe context such that it can be restored by a ContextPop ** opcode. The context stores the last insert row id, the last statement change ** count, and the current statement change count. */ -case OP_ContextPush: { /* no-push */ +case OP_ContextPush: { int i = p->contextStackTop++; Context *pContext; assert( i>=0 ); /* FIX ME: This should be allocated as part of the vdbe at compile-time */ @@ -41671,11 +43072,11 @@ ** ** Restore the Vdbe context to the state it was in when contextPush was last ** executed. The context stores the last insert row id, the last statement ** change count, and the current statement change count. */ -case OP_ContextPop: { /* no-push */ +case OP_ContextPop: { Context *pContext = &p->contextStack[--p->contextStackTop]; assert( p->contextStackTop>=0 ); db->lastRowid = pContext->lastRowid; p->nChange = pContext->nChange; sqlite3VdbeFifoClear(&p->sFifo); @@ -41682,283 +43083,176 @@ p->sFifo = pContext->sFifo; break; } #endif /* #ifndef SQLITE_OMIT_TRIGGER */ -/* Opcode: MemStore P1 P2 * -** -** Write the top of the stack into memory location P1. -** P1 should be a small integer since space is allocated -** for all memory locations between 0 and P1 inclusive. -** -** After the data is stored in the memory location, the -** stack is popped once if P2 is 1. If P2 is zero, then -** the original data remains on the stack. -*/ -case OP_MemStore: { /* no-push */ - assert( pTos>=p->aStack ); - assert( pOp->p1>=0 && pOp->p1<p->nMem ); - rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], pTos); - pTos--; - - /* If P2 is 0 then fall thru to the next opcode, OP_MemLoad, that will - ** restore the top of the stack to its original value. - */ - if( pOp->p2 ){ - break; - } -} -/* Opcode: MemLoad P1 * * -** -** Push a copy of the value in memory location P1 onto the stack. -** -** If the value is a string, then the value pushed is a pointer to -** the string that is stored in the memory location. If the memory -** location is subsequently changed (using OP_MemStore) then the -** value pushed onto the stack will change too. -*/ -case OP_MemLoad: { - int i = pOp->p1; - assert( i>=0 && i<p->nMem ); - pTos++; - sqlite3VdbeMemShallowCopy(pTos, &p->aMem[i], MEM_Ephem); - break; -} - #ifndef SQLITE_OMIT_AUTOINCREMENT -/* Opcode: MemMax P1 * * -** -** Set the value of memory cell P1 to the maximum of its current value -** and the value on the top of the stack. The stack is unchanged. +/* Opcode: MemMax P1 P2 * * * +** +** Set the value of register P1 to the maximum of its current value +** and the value in register P2. ** ** This instruction throws an error if the memory cell is not initially ** an integer. */ -case OP_MemMax: { /* no-push */ - int i = pOp->p1; - Mem *pMem; - assert( pTos>=p->aStack ); - assert( i>=0 && i<p->nMem ); - pMem = &p->aMem[i]; - sqlite3VdbeMemIntegerify(pMem); - sqlite3VdbeMemIntegerify(pTos); - if( pMem->u.i<pTos->u.i){ - pMem->u.i = pTos->u.i; +case OP_MemMax: { /* in1, in2 */ + sqlite3VdbeMemIntegerify(pIn1); + sqlite3VdbeMemIntegerify(pIn2); + if( pIn1->u.i<pIn2->u.i){ + pIn1->u.i = pIn2->u.i; } break; } #endif /* SQLITE_OMIT_AUTOINCREMENT */ -/* Opcode: MemIncr P1 P2 * -** -** Increment the integer valued memory cell P2 by the value in P1. -** -** It is illegal to use this instruction on a memory cell that does +/* Opcode: IfPos P1 P2 * * * +** +** If the value of register P1 is 1 or greater, jump to P2. +** +** It is illegal to use this instruction on a register that does +** not contain an integer. An assertion fault will result if you try. +*/ +case OP_IfPos: { /* jump, in1 */ + assert( pIn1->flags==MEM_Int ); + if( pIn1->u.i>0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IfNeg P1 P2 * * * +** +** If the value of register P1 is less than zero, jump to P2. +** +** It is illegal to use this instruction on a register that does ** not contain an integer. An assertion fault will result if you try. */ -case OP_MemIncr: { /* no-push */ - int i = pOp->p2; - Mem *pMem; - assert( i>=0 && i<p->nMem ); - pMem = &p->aMem[i]; - assert( pMem->flags==MEM_Int ); - pMem->u.i += pOp->p1; - break; -} - -/* Opcode: IfMemPos P1 P2 * -** -** If the value of memory cell P1 is 1 or greater, jump to P2. -** -** It is illegal to use this instruction on a memory cell that does +case OP_IfNeg: { /* jump, in1 */ + assert( pIn1->flags==MEM_Int ); + if( pIn1->u.i<0 ){ + pc = pOp->p2 - 1; + } + break; +} + +/* Opcode: IfZero P1 P2 * * * +** +** If the value of register P1 is exactly 0, jump to P2. +** +** It is illegal to use this instruction on a register that does ** not contain an integer. An assertion fault will result if you try. */ -case OP_IfMemPos: { /* no-push */ - int i = pOp->p1; - Mem *pMem; - assert( i>=0 && i<p->nMem ); - pMem = &p->aMem[i]; - assert( pMem->flags==MEM_Int ); - if( pMem->u.i>0 ){ +case OP_IfZero: { /* jump, in1 */ + assert( pIn1->flags==MEM_Int ); + if( pIn1->u.i==0 ){ pc = pOp->p2 - 1; } break; } -/* Opcode: IfMemNeg P1 P2 * -** -** If the value of memory cell P1 is less than zero, jump to P2. -** -** It is illegal to use this instruction on a memory cell that does -** not contain an integer. An assertion fault will result if you try. -*/ -case OP_IfMemNeg: { /* no-push */ - int i = pOp->p1; - Mem *pMem; - assert( i>=0 && i<p->nMem ); - pMem = &p->aMem[i]; - assert( pMem->flags==MEM_Int ); - if( pMem->u.i<0 ){ - pc = pOp->p2 - 1; - } - break; -} - -/* Opcode: IfMemZero P1 P2 * -** -** If the value of memory cell P1 is exactly 0, jump to P2. -** -** It is illegal to use this instruction on a memory cell that does -** not contain an integer. An assertion fault will result if you try. -*/ -case OP_IfMemZero: { /* no-push */ - int i = pOp->p1; - Mem *pMem; - assert( i>=0 && i<p->nMem ); - pMem = &p->aMem[i]; - assert( pMem->flags==MEM_Int ); - if( pMem->u.i==0 ){ - pc = pOp->p2 - 1; - } - break; -} - -/* Opcode: MemNull P1 * * -** -** Store a NULL in memory cell P1 -*/ -case OP_MemNull: { - assert( pOp->p1>=0 && pOp->p1<p->nMem ); - sqlite3VdbeMemSetNull(&p->aMem[pOp->p1]); - break; -} - -/* Opcode: MemInt P1 P2 * -** -** Store the integer value P1 in memory cell P2. -*/ -case OP_MemInt: { - assert( pOp->p2>=0 && pOp->p2<p->nMem ); - sqlite3VdbeMemSetInt64(&p->aMem[pOp->p2], pOp->p1); - break; -} - -/* Opcode: MemMove P1 P2 * -** -** Move the content of memory cell P2 over to memory cell P1. -** Any prior content of P1 is erased. Memory cell P2 is left -** containing a NULL. -*/ -case OP_MemMove: { - assert( pOp->p1>=0 && pOp->p1<p->nMem ); - assert( pOp->p2>=0 && pOp->p2<p->nMem ); - rc = sqlite3VdbeMemMove(&p->aMem[pOp->p1], &p->aMem[pOp->p2]); - break; -} - -/* Opcode: AggStep P1 P2 P3 +/* Opcode: AggStep * P2 P3 P4 P5 ** ** Execute the step function for an aggregate. The -** function has P2 arguments. P3 is a pointer to the FuncDef -** structure that specifies the function. Use memory location -** P1 as the accumulator. -** -** The P2 arguments are popped from the stack. -*/ -case OP_AggStep: { /* no-push */ - int n = pOp->p2; +** function has P5 arguments. P4 is a pointer to the FuncDef +** structure that specifies the function. Use register +** P3 as the accumulator. +** +** The P5 arguments are taken from register P2 and its +** successors. +*/ +case OP_AggStep: { + int n = pOp->p5; int i; Mem *pMem, *pRec; sqlite3_context ctx; sqlite3_value **apVal; assert( n>=0 ); - pRec = &pTos[1-n]; - assert( pRec>=p->aStack ); + pRec = &p->aMem[pOp->p2]; apVal = p->apArg; assert( apVal || n==0 ); for(i=0; i<n; i++, pRec++){ apVal[i] = pRec; storeTypeInfo(pRec, encoding); } - ctx.pFunc = (FuncDef*)pOp->p3; - assert( pOp->p1>=0 && pOp->p1<p->nMem ); - ctx.pMem = pMem = &p->aMem[pOp->p1]; + ctx.pFunc = pOp->p4.pFunc; + assert( pOp->p3>0 && pOp->p3<=p->nMem ); + ctx.pMem = pMem = &p->aMem[pOp->p3]; pMem->n++; ctx.s.flags = MEM_Null; ctx.s.z = 0; ctx.s.xDel = 0; ctx.s.db = db; ctx.isError = 0; ctx.pColl = 0; if( ctx.pFunc->needCollSeq ){ assert( pOp>p->aOp ); - assert( pOp[-1].p3type==P3_COLLSEQ ); + assert( pOp[-1].p4type==P4_COLLSEQ ); assert( pOp[-1].opcode==OP_CollSeq ); - ctx.pColl = (CollSeq *)pOp[-1].p3; - } - (ctx.pFunc->xStep)(&ctx, n, apVal); - popStack(&pTos, n); + ctx.pColl = pOp[-1].p4.pColl; + } + (ctx.pFunc->xStep)(&ctx, n, apVal); if( ctx.isError ){ sqlite3SetString(&p->zErrMsg, sqlite3_value_text(&ctx.s), (char*)0); rc = SQLITE_ERROR; } sqlite3VdbeMemRelease(&ctx.s); break; } -/* Opcode: AggFinal P1 P2 P3 +/* Opcode: AggFinal P1 P2 * P4 * ** ** Execute the finalizer function for an aggregate. P1 is ** the memory location that is the accumulator for the aggregate. ** ** P2 is the number of arguments that the step function takes and -** P3 is a pointer to the FuncDef for this function. The P2 +** P4 is a pointer to the FuncDef for this function. The P2 ** argument is not used by this opcode. It is only there to disambiguate ** functions that can take varying numbers of arguments. The -** P3 argument is only needed for the degenerate case where +** P4 argument is only needed for the degenerate case where ** the step function was not previously called. */ -case OP_AggFinal: { /* no-push */ +case OP_AggFinal: { Mem *pMem; - assert( pOp->p1>=0 && pOp->p1<p->nMem ); + assert( pOp->p1>0 && pOp->p1<=p->nMem ); pMem = &p->aMem[pOp->p1]; assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 ); - rc = sqlite3VdbeMemFinalize(pMem, (FuncDef*)pOp->p3); + rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc); if( rc==SQLITE_ERROR ){ sqlite3SetString(&p->zErrMsg, sqlite3_value_text(pMem), (char*)0); } + UPDATE_MAX_BLOBSIZE(pMem); if( sqlite3VdbeMemTooBig(pMem) ){ goto too_big; } break; } #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) -/* Opcode: Vacuum * * * +/* Opcode: Vacuum * * * * * ** ** Vacuum the entire database. This opcode will cause other virtual ** machines to be created and run. It may not be called from within ** a transaction. */ -case OP_Vacuum: { /* no-push */ +case OP_Vacuum: { if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; rc = sqlite3RunVacuum(&p->zErrMsg, db); if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; break; } #endif #if !defined(SQLITE_OMIT_AUTOVACUUM) -/* Opcode: IncrVacuum P1 P2 * +/* Opcode: IncrVacuum P1 P2 * * * ** ** Perform a single step of the incremental vacuum procedure on ** the P1 database. If the vacuum has finished, jump to instruction ** P2. Otherwise, fall through to the next instruction. */ -case OP_IncrVacuum: { /* no-push */ +case OP_IncrVacuum: { /* jump */ Btree *pBt; assert( pOp->p1>=0 && pOp->p1<db->nDb ); assert( (p->btreeMask & (1<<pOp->p1))!=0 ); pBt = db->aDb[pOp->p1].pBt; @@ -41969,30 +43263,30 @@ } break; } #endif -/* Opcode: Expire P1 * * +/* Opcode: Expire P1 * * * * ** ** Cause precompiled statements to become expired. An expired statement ** fails with an error code of SQLITE_SCHEMA if it is ever executed ** (via sqlite3_step()). ** ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero, ** then only the currently executing statement is affected. */ -case OP_Expire: { /* no-push */ +case OP_Expire: { if( !pOp->p1 ){ sqlite3ExpirePreparedStatements(db); }else{ p->expired = 1; } break; } #ifndef SQLITE_OMIT_SHARED_CACHE -/* Opcode: TableLock P1 P2 P3 +/* Opcode: TableLock P1 P2 * P4 * ** ** Obtain a lock on a particular table. This instruction is only used when ** the shared-cache feature is enabled. ** ** If P1 is not negative, then it is the index of the database @@ -42001,80 +43295,80 @@ ** absolute value of P1 minus one (iDb = abs(P1) - 1;) and a write-lock is ** required. ** ** P2 contains the root-page of the table to lock. ** -** P3 contains a pointer to the name of the table being locked. This is only +** P4 contains a pointer to the name of the table being locked. This is only ** used to generate an error message if the lock cannot be obtained. */ -case OP_TableLock: { /* no-push */ +case OP_TableLock: { int p1 = pOp->p1; u8 isWriteLock = (p1<0); if( isWriteLock ){ p1 = (-1*p1)-1; } assert( p1>=0 && p1<db->nDb ); assert( (p->btreeMask & (1<<p1))!=0 ); rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock); if( rc==SQLITE_LOCKED ){ - const char *z = (const char *)pOp->p3; + const char *z = pOp->p4.z; sqlite3SetString(&p->zErrMsg, "database table is locked: ", z, (char*)0); } break; } #endif /* SQLITE_OMIT_SHARED_CACHE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VBegin * * P3 -** -** P3 a pointer to an sqlite3_vtab structure. Call the xBegin method +/* Opcode: VBegin * * * P4 * +** +** P4 a pointer to an sqlite3_vtab structure. Call the xBegin method ** for that table. */ -case OP_VBegin: { /* no-push */ - rc = sqlite3VtabBegin(db, (sqlite3_vtab *)pOp->p3); +case OP_VBegin: { + rc = sqlite3VtabBegin(db, pOp->p4.pVtab); break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VCreate P1 * P3 -** -** P3 is the name of a virtual table in database P1. Call the xCreate method +/* Opcode: VCreate P1 * * P4 * +** +** P4 is the name of a virtual table in database P1. Call the xCreate method ** for that table. */ -case OP_VCreate: { /* no-push */ - rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p3, &p->zErrMsg); +case OP_VCreate: { + rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg); break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VDestroy P1 * P3 -** -** P3 is the name of a virtual table in database P1. Call the xDestroy method +/* Opcode: VDestroy P1 * * P4 * +** +** P4 is the name of a virtual table in database P1. Call the xDestroy method ** of that table. */ -case OP_VDestroy: { /* no-push */ +case OP_VDestroy: { p->inVtabMethod = 2; - rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p3); + rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z); p->inVtabMethod = 0; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VOpen P1 * P3 -** -** P3 is a pointer to a virtual table object, an sqlite3_vtab structure. +/* Opcode: VOpen P1 * * P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** P1 is a cursor number. This opcode opens a cursor to the virtual ** table and stores that cursor in P1. */ -case OP_VOpen: { /* no-push */ +case OP_VOpen: { Cursor *pCur = 0; sqlite3_vtab_cursor *pVtabCursor = 0; - sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3); + sqlite3_vtab *pVtab = pOp->p4.pVtab; sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule; assert(pVtab && pModule); if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; rc = pModule->xOpen(pVtab, &pVtabCursor); @@ -42096,59 +43390,59 @@ break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VFilter P1 P2 P3 +/* Opcode: VFilter P1 P2 P3 P4 * ** ** P1 is a cursor opened using VOpen. P2 is an address to jump to if ** the filtered result set is empty. ** -** P3 is either NULL or a string that was generated by the xBestIndex -** method of the module. The interpretation of the P3 string is left +** P4 is either NULL or a string that was generated by the xBestIndex +** method of the module. The interpretation of the P4 string is left ** to the module implementation. ** ** This opcode invokes the xFilter method on the virtual table specified -** by P1. The integer query plan parameter to xFilter is the top of the -** stack. Next down on the stack is the argc parameter. Beneath the -** next of stack are argc additional parameters which are passed to -** xFilter as argv. The topmost parameter (i.e. 3rd element popped from -** the stack) becomes argv[argc-1] when passed to xFilter. -** -** The integer query plan parameter, argc, and all argv stack values -** are popped from the stack before this instruction completes. -** -** A jump is made to P2 if the result set after filtering would be -** empty. -*/ -case OP_VFilter: { /* no-push */ +** by P1. The integer query plan parameter to xFilter is stored in register +** P3. Register P3+1 stores the argc parameter to be passed to the +** xFilter method. Registers P3+2..P3+1+argc are the argc additional +** parametersneath additional parameters which are passed to +** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter. +** +** A jump is made to P2 if the result set after filtering would be empty. +*/ +case OP_VFilter: { /* jump */ int nArg; - + int iQuery; const sqlite3_module *pModule; + Mem *pQuery = &p->aMem[pOp->p3]; + Mem *pArgc = &pQuery[1]; Cursor *pCur = p->apCsr[pOp->p1]; + + REGISTER_TRACE(pOp->p3, pQuery); assert( pCur->pVtabCursor ); pModule = pCur->pVtabCursor->pVtab->pModule; - /* Grab the index number and argc parameters off the top of the stack. */ - assert( (&pTos[-1])>=p->aStack ); - assert( (pTos[0].flags&MEM_Int)!=0 && pTos[-1].flags==MEM_Int ); - nArg = pTos[-1].u.i; + /* Grab the index number and argc parameters */ + assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int ); + nArg = pArgc->u.i; + iQuery = pQuery->u.i; /* Invoke the xFilter method */ { int res = 0; int i; Mem **apArg = p->apArg; for(i = 0; i<nArg; i++){ - apArg[i] = &pTos[i+1-2-nArg]; + apArg[i] = &pArgc[i+1]; storeTypeInfo(apArg[i], 0); } if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; p->inVtabMethod = 1; - rc = pModule->xFilter(pCur->pVtabCursor, pTos->u.i, pOp->p3, nArg, apArg); + rc = pModule->xFilter(pCur->pVtabCursor, iQuery, pOp->p4.z, nArg, apArg); p->inVtabMethod = 0; if( rc==SQLITE_OK ){ res = pModule->xEof(pCur->pVtabCursor); } if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; @@ -42155,200 +43449,197 @@ if( res ){ pc = pOp->p2 - 1; } } - - /* Pop the index number, argc value and parameters off the stack */ - popStack(&pTos, 2+nArg); + pCur->nullRow = 0; + break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VRowid P1 * * -** -** Push an integer onto the stack which is the rowid of +/* Opcode: VRowid P1 P2 * * * +** +** Store into register P2 the rowid of ** the virtual-table that the P1 cursor is pointing to. */ -case OP_VRowid: { +case OP_VRowid: { /* out2-prerelease */ const sqlite3_module *pModule; - + sqlite_int64 iRow; Cursor *pCur = p->apCsr[pOp->p1]; + assert( pCur->pVtabCursor ); + if( pCur->nullRow ){ + break; + } pModule = pCur->pVtabCursor->pVtab->pModule; - if( pModule->xRowid==0 ){ - sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xRowid", 0); - rc = SQLITE_ERROR; - } else { - sqlite_int64 iRow; - - if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; - rc = pModule->xRowid(pCur->pVtabCursor, &iRow); - if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; - - pTos++; - pTos->flags = MEM_Int; - pTos->u.i = iRow; - } - + assert( pModule->xRowid ); + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; + rc = pModule->xRowid(pCur->pVtabCursor, &iRow); + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; + pOut->flags = MEM_Int; + pOut->u.i = iRow; break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VColumn P1 P2 * -** -** Push onto the stack the value of the P2-th column of -** the row of the virtual-table that the P1 cursor is pointing to. +/* Opcode: VColumn P1 P2 P3 * * +** +** Store the value of the P2-th column of +** the row of the virtual-table that the +** P1 cursor is pointing to into register P3. */ case OP_VColumn: { const sqlite3_module *pModule; + Mem *pDest; + sqlite3_context sContext; Cursor *pCur = p->apCsr[pOp->p1]; assert( pCur->pVtabCursor ); + assert( pOp->p3>0 && pOp->p3<=p->nMem ); + pDest = &p->aMem[pOp->p3]; + if( pCur->nullRow ){ + sqlite3VdbeMemSetNull(pDest); + break; + } pModule = pCur->pVtabCursor->pVtab->pModule; - if( pModule->xColumn==0 ){ - sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xColumn", 0); - rc = SQLITE_ERROR; - } else { - sqlite3_context sContext; - memset(&sContext, 0, sizeof(sContext)); - sContext.s.flags = MEM_Null; - sContext.s.db = db; - if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; - rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2); - - /* Copy the result of the function to the top of the stack. We - ** do this regardless of whether or not an error occured to ensure any - ** dynamic allocation in sContext.s (a Mem struct) is released. - */ - sqlite3VdbeChangeEncoding(&sContext.s, encoding); - pTos++; - pTos->flags = 0; - sqlite3VdbeMemMove(pTos, &sContext.s); - - if( sqlite3SafetyOn(db) ){ - goto abort_due_to_misuse; - } - if( sqlite3VdbeMemTooBig(pTos) ){ - goto too_big; - } - } - + assert( pModule->xColumn ); + memset(&sContext, 0, sizeof(sContext)); + sContext.s.flags = MEM_Null; + sContext.s.db = db; + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; + rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2); + + /* Copy the result of the function to the P3 register. We + ** do this regardless of whether or not an error occured to ensure any + ** dynamic allocation in sContext.s (a Mem struct) is released. + */ + sqlite3VdbeChangeEncoding(&sContext.s, encoding); + REGISTER_TRACE(pOp->p3, pDest); + sqlite3VdbeMemMove(pDest, &sContext.s); + UPDATE_MAX_BLOBSIZE(pDest); + + if( sqlite3SafetyOn(db) ){ + goto abort_due_to_misuse; + } + if( sqlite3VdbeMemTooBig(pDest) ){ + goto too_big; + } break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VNext P1 P2 * +/* Opcode: VNext P1 P2 * * * ** ** Advance virtual table P1 to the next row in its result set and ** jump to instruction P2. Or, if the virtual table has reached ** the end of its result set, then fall through to the next instruction. */ -case OP_VNext: { /* no-push */ +case OP_VNext: { /* jump */ const sqlite3_module *pModule; int res = 0; Cursor *pCur = p->apCsr[pOp->p1]; assert( pCur->pVtabCursor ); + if( pCur->nullRow ){ + break; + } pModule = pCur->pVtabCursor->pVtab->pModule; - if( pModule->xNext==0 ){ - sqlite3SetString(&p->zErrMsg, "Unsupported module operation: xNext", 0); - rc = SQLITE_ERROR; - } else { - /* Invoke the xNext() method of the module. There is no way for the - ** underlying implementation to return an error if one occurs during - ** xNext(). Instead, if an error occurs, true is returned (indicating that - ** data is available) and the error code returned when xColumn or - ** some other method is next invoked on the save virtual table cursor. - */ - if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; - p->inVtabMethod = 1; - rc = pModule->xNext(pCur->pVtabCursor); - p->inVtabMethod = 0; - if( rc==SQLITE_OK ){ - res = pModule->xEof(pCur->pVtabCursor); - } - if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; - - if( !res ){ - /* If there is data, jump to P2 */ - pc = pOp->p2 - 1; - } - } - + assert( pModule->xNext ); + + /* Invoke the xNext() method of the module. There is no way for the + ** underlying implementation to return an error if one occurs during + ** xNext(). Instead, if an error occurs, true is returned (indicating that + ** data is available) and the error code returned when xColumn or + ** some other method is next invoked on the save virtual table cursor. + */ + if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; + p->inVtabMethod = 1; + rc = pModule->xNext(pCur->pVtabCursor); + p->inVtabMethod = 0; + if( rc==SQLITE_OK ){ + res = pModule->xEof(pCur->pVtabCursor); + } + if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; + + if( !res ){ + /* If there is data, jump to P2 */ + pc = pOp->p2 - 1; + } break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VRename * * P3 -** -** P3 is a pointer to a virtual table object, an sqlite3_vtab structure. +/* Opcode: VRename P1 * * P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** This opcode invokes the corresponding xRename method. The value -** on the top of the stack is popped and passed as the zName argument -** to the xRename method. -*/ -case OP_VRename: { /* no-push */ - sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3); +** in register P1 is passed as the zName argument to the xRename method. +*/ +case OP_VRename: { + sqlite3_vtab *pVtab = pOp->p4.pVtab; + Mem *pName = &p->aMem[pOp->p1]; assert( pVtab->pModule->xRename ); - - Stringify(pTos, encoding); + REGISTER_TRACE(pOp->p1, pName); + + Stringify(pName, encoding); if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; sqlite3VtabLock(pVtab); - rc = pVtab->pModule->xRename(pVtab, pTos->z); + rc = pVtab->pModule->xRename(pVtab, pName->z); sqlite3VtabUnlock(db, pVtab); if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse; - popStack(&pTos, 1); break; } #endif #ifndef SQLITE_OMIT_VIRTUALTABLE -/* Opcode: VUpdate P1 P2 P3 -** -** P3 is a pointer to a virtual table object, an sqlite3_vtab structure. +/* Opcode: VUpdate P1 P2 P3 P4 * +** +** P4 is a pointer to a virtual table object, an sqlite3_vtab structure. ** This opcode invokes the corresponding xUpdate method. P2 values -** are taken from the stack to pass to the xUpdate invocation. The -** value on the top of the stack corresponds to the p2th element -** of the argv array passed to xUpdate. +** are contiguous memory cells starting at P3 to pass to the xUpdate +** invocation. The value in register (P3+P2-1) corresponds to the +** p2th element of the argv array passed to xUpdate. ** ** The xUpdate method will do a DELETE or an INSERT or both. -** The argv[0] element (which corresponds to the P2-th element down -** on the stack) is the rowid of a row to delete. If argv[0] is -** NULL then no deletion occurs. The argv[1] element is the rowid -** of the new row. This can be NULL to have the virtual table -** select the new rowid for itself. The higher elements in the -** stack are the values of columns in the new row. +** The argv[0] element (which corresponds to memory cell P3) +** is the rowid of a row to delete. If argv[0] is NULL then no +** deletion occurs. The argv[1] element is the rowid of the new +** row. This can be NULL to have the virtual table select the new +** rowid for itself. The subsequent elements in the array are +** the values of columns in the new row. ** ** If P2==1 then no insert is performed. argv[0] is the rowid of ** a row to delete. ** ** P1 is a boolean flag. If it is set to true and the xUpdate call ** is successful, then the value returned by sqlite3_last_insert_rowid() ** is set to the value of the rowid for the row just inserted. */ -case OP_VUpdate: { /* no-push */ - sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3); +case OP_VUpdate: { + sqlite3_vtab *pVtab = pOp->p4.pVtab; sqlite3_module *pModule = (sqlite3_module *)pVtab->pModule; int nArg = pOp->p2; - assert( pOp->p3type==P3_VTAB ); + assert( pOp->p4type==P4_VTAB ); if( pModule->xUpdate==0 ){ sqlite3SetString(&p->zErrMsg, "read-only table", 0); rc = SQLITE_ERROR; }else{ int i; sqlite_int64 rowid; Mem **apArg = p->apArg; - Mem *pX = &pTos[1-nArg]; - for(i = 0; i<nArg; i++, pX++){ + Mem *pX = &p->aMem[pOp->p3]; + for(i=0; i<nArg; i++){ storeTypeInfo(pX, 0); apArg[i] = pX; + pX++; } if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse; sqlite3VtabLock(pVtab); rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid); sqlite3VtabUnlock(db, pVtab); @@ -42356,19 +43647,48 @@ if( pOp->p1 && rc==SQLITE_OK ){ assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) ); db->lastRowid = rowid; } } - popStack(&pTos, nArg); break; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ -/* An other opcode is illegal... -*/ -default: { - assert( 0 ); +#ifndef SQLITE_OMIT_TRACE +/* Opcode: Trace * * * P4 * +** +** If tracing is enabled (by the sqlite3_trace()) interface, then +** the UTF-8 string contained in P4 is emitted on the trace callback. +*/ +case OP_Trace: { + if( pOp->p4.z ){ + if( db->xTrace ){ + db->xTrace(db->pTraceArg, pOp->p4.z); + } +#ifdef SQLITE_DEBUG + if( (db->flags & SQLITE_SqlTrace)!=0 ){ + sqlite3DebugPrintf("SQL-trace: %s\n", pOp->p4.z); + } +#endif /* SQLITE_DEBUG */ + } + break; +} +#endif + + +/* Opcode: Noop * * * * * +** +** Do nothing. This instruction is often useful as a jump +** destination. +*/ +/* +** The magic Explain opcode are only inserted when explain==2 (which +** is to say when the EXPLAIN QUERY PLAN syntax is used.) +** This opcode records information from the optimizer. It is the +** the same as a no-op. This opcodesnever appears in a real VM program. +*/ +default: { /* This is really OP_Noop and OP_Explain */ break; } /***************************************************************************** ** The cases of the switch statement above this line should all be indented @@ -42375,13 +43695,10 @@ ** by 6 spaces. But the left-most 6 spaces have been removed to improve the ** readability. From this point on down, the normal indentation rules are ** restored. *****************************************************************************/ } - - /* Make sure the stack limit was not exceeded */ - assert( pTos<=pStackLimit ); #ifdef VDBE_PROFILE { long long elapse = hwtime() - start; pOp->cycles += elapse; @@ -42391,77 +43708,40 @@ sqlite3VdbePrintOp(stdout, origPc, &p->aOp[origPc]); #endif } #endif -#ifdef SQLITE_TEST - /* Keep track of the size of the largest BLOB or STR that has appeared - ** on the top of the VDBE stack. - */ - if( pTos>=p->aStack && (pTos->flags & (MEM_Blob|MEM_Str))!=0 - && pTos->n>sqlite3_max_blobsize ){ - sqlite3_max_blobsize = pTos->n; - } -#endif - /* The following code adds nothing to the actual functionality ** of the program. It is only here for testing and debugging. ** On the other hand, it does burn CPU cycles every time through ** the evaluator loop. So we can leave it out when NDEBUG is defined. */ #ifndef NDEBUG - /* Sanity checking on the top element of the stack. If the previous - ** instruction was VNoChange, then the flags field of the top - ** of the stack is set to 0. This is technically invalid for a memory - ** cell, so avoid calling MemSanity() in this case. - */ - if( pTos>=p->aStack && pTos->flags ){ - assert( pTos->db==db ); - sqlite3VdbeMemSanity(pTos); - assert( !sqlite3VdbeMemTooBig(pTos) ); - } assert( pc>=-1 && pc<p->nOp ); #ifdef SQLITE_DEBUG - /* Code for tracing the vdbe stack. */ - if( p->trace && pTos>=p->aStack ){ - int i; - fprintf(p->trace, "Stack:"); - for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){ - if( pTos[i].flags & MEM_Null ){ - fprintf(p->trace, " NULL"); - }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){ - fprintf(p->trace, " si:%lld", pTos[i].u.i); - }else if( pTos[i].flags & MEM_Int ){ - fprintf(p->trace, " i:%lld", pTos[i].u.i); - }else if( pTos[i].flags & MEM_Real ){ - fprintf(p->trace, " r:%g", pTos[i].r); - }else{ - char zBuf[200]; - sqlite3VdbeMemPrettyPrint(&pTos[i], zBuf); - fprintf(p->trace, " "); - fprintf(p->trace, "%s", zBuf); - } - } - if( rc!=0 ) fprintf(p->trace," rc=%d",rc); - fprintf(p->trace,"\n"); + if( p->trace ){ + if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc); + if( opProperty & OPFLG_OUT2_PRERELEASE ){ + registerTrace(p->trace, pOp->p2, pOut); + } + if( opProperty & OPFLG_OUT3 ){ + registerTrace(p->trace, pOp->p3, pOut); + } } #endif /* SQLITE_DEBUG */ #endif /* NDEBUG */ } /* The end of the for(;;) loop the loops through opcodes */ - /* If we reach this point, it means that execution is finished. - */ -vdbe_halt: - if( rc ){ - p->rc = rc; - rc = SQLITE_ERROR; - }else{ - rc = SQLITE_DONE; - } - sqlite3VdbeHalt(p); - p->pTos = pTos; + /* If we reach this point, it means that execution is finished with + ** an error of some kind. + */ +vdbe_error_halt: + assert( rc ); + p->rc = rc; + rc = SQLITE_ERROR; + sqlite3VdbeHalt(p); /* This is the only way out of this procedure. We have to ** release the mutexes on btrees that were acquired at the ** top. */ vdbe_return: @@ -42472,19 +43752,19 @@ ** is encountered. */ too_big: sqlite3SetString(&p->zErrMsg, "string or blob too big", (char*)0); rc = SQLITE_TOOBIG; - goto vdbe_halt; + goto vdbe_error_halt; /* Jump to here if a malloc() fails. */ no_mem: db->mallocFailed = 1; sqlite3SetString(&p->zErrMsg, "out of memory", (char*)0); rc = SQLITE_NOMEM; - goto vdbe_halt; + goto vdbe_error_halt; /* Jump to here for an SQLITE_MISUSE error. */ abort_due_to_misuse: rc = SQLITE_MISUSE; @@ -42492,29 +43772,24 @@ /* Jump to here for any other kind of fatal error. The "rc" variable ** should hold the error number. */ abort_due_to_error: - if( p->zErrMsg==0 ){ - if( db->mallocFailed ) rc = SQLITE_NOMEM; - sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0); - } - goto vdbe_halt; + assert( p->zErrMsg==0 ); + if( db->mallocFailed ) rc = SQLITE_NOMEM; + sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0); + goto vdbe_error_halt; /* Jump to here if the sqlite3_interrupt() API sets the interrupt ** flag. */ abort_due_to_interrupt: assert( db->u1.isInterrupted ); - if( db->magic!=SQLITE_MAGIC_BUSY ){ - rc = SQLITE_MISUSE; - }else{ - rc = SQLITE_INTERRUPT; - } + rc = SQLITE_INTERRUPT; p->rc = rc; sqlite3SetString(&p->zErrMsg, sqlite3ErrStr(rc), (char*)0); - goto vdbe_halt; + goto vdbe_error_halt; } /************** End of vdbe.c ************************************************/ /************** Begin file vdbeblob.c ****************************************/ /* @@ -42529,11 +43804,11 @@ ** ************************************************************************* ** ** This file contains code used to implement incremental BLOB I/O. ** -** $Id: vdbeblob.c,v 1.16 2007/08/30 01:19:59 drh Exp $ +** $Id: vdbeblob.c,v 1.20 2008/01/25 15:04:50 drh Exp $ */ #ifndef SQLITE_OMIT_INCRBLOB @@ -42569,11 +43844,11 @@ ** db/table/row entry. The reason for using a vdbe program instead ** of writing code to use the b-tree layer directly is that the ** vdbe program will take advantage of the various transaction, ** locking and error handling infrastructure built into the vdbe. ** - ** After seeking the cursor, the vdbe executes an OP_Callback. + ** After seeking the cursor, the vdbe executes an OP_ResultRow. ** Code external to the Vdbe then "borrows" the b-tree cursor and ** uses it to implement the blob_read(), blob_write() and ** blob_bytes() functions. ** ** The sqlite3_blob_close() function finalizes the vdbe program, @@ -42581,25 +43856,24 @@ ** transaction. */ static const VdbeOpList openBlob[] = { {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */ {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */ - {OP_Integer, 0, 0, 0}, /* 2: Database number */ /* One of the following two instructions is replaced by an ** OP_Noop before exection. */ - {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */ - {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */ - {OP_SetNumColumns, 0, 0, 0}, /* 5: Num cols for cursor */ - - {OP_Variable, 1, 0, 0}, /* 6: Push the rowid to the stack */ - {OP_NotExists, 0, 10, 0}, /* 7: Seek the cursor */ - {OP_Column, 0, 0, 0}, /* 8 */ - {OP_Callback, 0, 0, 0}, /* 9 */ - {OP_Close, 0, 0, 0}, /* 10 */ - {OP_Halt, 0, 0, 0}, /* 11 */ + {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */ + {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */ + {OP_SetNumColumns, 0, 0, 0}, /* 4: Num cols for cursor */ + + {OP_Variable, 1, 1, 0}, /* 5: Push the rowid to the stack */ + {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */ + {OP_Column, 0, 0, 1}, /* 7 */ + {OP_ResultRow, 1, 0, 0}, /* 8 */ + {OP_Close, 0, 0, 0}, /* 9 */ + {OP_Halt, 0, 0, 0}, /* 10 */ }; Vdbe *v = 0; int rc = SQLITE_OK; char zErr[128]; @@ -42618,18 +43892,18 @@ sqlite3_mutex_leave(db->mutex); return rc; } sqlite3BtreeEnterAll(db); - pTab = sqlite3LocateTable(&sParse, zTable, zDb); + pTab = sqlite3LocateTable(&sParse, 0, zTable, zDb); if( !pTab ){ if( sParse.zErrMsg ){ sqlite3_snprintf(sizeof(zErr), zErr, "%s", sParse.zErrMsg); } sqlite3_free(sParse.zErrMsg); rc = SQLITE_ERROR; - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* Now search pTab for the exact column. */ @@ -42639,11 +43913,11 @@ } } if( iCol==pTab->nCol ){ sqlite3_snprintf(sizeof(zErr), zErr, "no such column: \"%s\"", zColumn); rc = SQLITE_ERROR; - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); sqlite3BtreeLeaveAll(db); goto blob_open_out; } /* If the value is being opened for writing, check that the @@ -42657,11 +43931,11 @@ for(j=0; j<pIdx->nColumn; j++){ if( pIdx->aiColumn[j]==iCol ){ sqlite3_snprintf(sizeof(zErr), zErr, "cannot open indexed column for writing"); rc = SQLITE_ERROR; - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); sqlite3BtreeLeaveAll(db); goto blob_open_out; } } } @@ -42681,29 +43955,27 @@ sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie); /* Make sure a mutex is held on the table to be accessed */ sqlite3VdbeUsesBtree(v, iDb); - /* Configure the db number pushed onto the stack */ - sqlite3VdbeChangeP1(v, 2, iDb); - /* Remove either the OP_OpenWrite or OpenRead. Set the P2 ** parameter of the other to pTab->tnum. */ - sqlite3VdbeChangeToNoop(v, (flags ? 3 : 4), 1); - sqlite3VdbeChangeP2(v, (flags ? 4 : 3), pTab->tnum); + sqlite3VdbeChangeToNoop(v, (flags ? 2 : 3), 1); + sqlite3VdbeChangeP2(v, (flags ? 3 : 2), pTab->tnum); + sqlite3VdbeChangeP3(v, (flags ? 3 : 2), iDb); /* Configure the OP_SetNumColumns. Configure the cursor to ** think that the table has one more column than it really ** does. An OP_Column to retrieve this imaginary column will ** always return an SQL NULL. This is useful because it means ** we can invoke OP_Column to fill in the vdbe cursors type ** and offset cache without causing any IO. */ - sqlite3VdbeChangeP2(v, 5, pTab->nCol+1); + sqlite3VdbeChangeP2(v, 4, pTab->nCol+1); if( !db->mallocFailed ){ - sqlite3VdbeMakeReady(v, 1, 0, 1, 0); + sqlite3VdbeMakeReady(v, 1, 1, 1, 0); } } sqlite3BtreeLeaveAll(db); rc = sqlite3SafetyOff(db); @@ -43110,11 +44382,11 @@ ** ************************************************************************* ** This file contains routines used for analyzing expressions and ** for generating VDBE code that evaluates expressions in SQLite. ** -** $Id: expr.c,v 1.316 2007/11/12 09:50:26 danielk1977 Exp $ +** $Id: expr.c,v 1.352 2008/01/23 14:51:49 drh Exp $ */ /* ** Return the 'affinity' of the expression pExpr if any. ** @@ -43254,19 +44526,17 @@ return sqlite3IsNumericAffinity(idx_affinity); } } /* -** Return the P1 value that should be used for a binary comparison +** Return the P5 value that should be used for a binary comparison ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2. -** If jumpIfNull is true, then set the low byte of the returned -** P1 value to tell the opcode to jump if either expression -** evaluates to NULL. -*/ -static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ - char aff = sqlite3ExprAffinity(pExpr2); - return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0); +*/ +static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){ + u8 aff = (char)sqlite3ExprAffinity(pExpr2); + aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull; + return aff; } /* ** Return a pointer to the collation sequence that should be used by ** a binary comparison operator comparing pLeft and pRight. @@ -43307,16 +44577,24 @@ static int codeCompare( Parse *pParse, /* The parsing (and code generating) context */ Expr *pLeft, /* The left operand */ Expr *pRight, /* The right operand */ int opcode, /* The comparison opcode */ + int in1, int in2, /* Register holding operands */ int dest, /* Jump here if true. */ int jumpIfNull /* If true, jump if either operand is NULL */ ){ - int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull); - CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); - return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ); + int p5; + int addr; + CollSeq *p4; + + p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight); + p5 = binaryCompareP5(pLeft, pRight, jumpIfNull); + addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1, + (void*)p4, P4_COLLSEQ); + sqlite3VdbeChangeP5(pParse->pVdbe, p5); + return addr; } /* ** Construct a new expression node and return a pointer to it. Memory ** for this node is obtained from sqlite3_malloc(). The calling function @@ -43379,36 +44657,31 @@ return sqlite3Expr(pParse->db, op, pLeft, pRight, pToken); } /* ** When doing a nested parse, you can include terms in an expression -** that look like this: #0 #1 #2 ... These terms refer to elements -** on the stack. "#0" means the top of the stack. -** "#1" means the next down on the stack. And so forth. +** that look like this: #1 #2 ... These terms refer to registers +** in the virtual machine. #N is the N-th register. ** ** This routine is called by the parser to deal with on of those terms. ** It immediately generates code to store the value in a memory location. ** The returns an expression that will code to extract the value from ** that memory location as needed. */ SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){ Vdbe *v = pParse->pVdbe; Expr *p; - int depth; if( pParse->nested==0 ){ sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken); return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0); } if( v==0 ) return 0; p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken); if( p==0 ){ return 0; /* Malloc failed */ } - depth = atoi((char*)&pToken->z[1]); - p->iTable = pParse->nMem++; - sqlite3VdbeAddOp(v, OP_Dup, depth, 0); - sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1); + p->iTable = atoi((char*)&pToken->z[1]); return p; } /* ** Join two expressions using an AND operator. If either expression is @@ -44203,18 +45476,21 @@ ** it is a new.* or old.* trigger argument reference */ if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){ TriggerStack *pTriggerStack = pParse->trigStack; Table *pTab = 0; + u32 *piColMask; if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){ pExpr->iTable = pTriggerStack->newIdx; assert( pTriggerStack->pTab ); pTab = pTriggerStack->pTab; + piColMask = &(pTriggerStack->newColMask); }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){ pExpr->iTable = pTriggerStack->oldIdx; assert( pTriggerStack->pTab ); pTab = pTriggerStack->pTab; + piColMask = &(pTriggerStack->oldColMask); } if( pTab ){ int iCol; Column *pCol = pTab->aCol; @@ -44229,10 +45505,13 @@ pExpr->affinity = pTab->aCol[iCol].affinity; if( (pExpr->flags & EP_ExpCollate)==0 ){ pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0); } pExpr->pTab = pTab; + if( iCol>=0 ){ + *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0); + } break; } } } } @@ -44316,27 +45595,20 @@ /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if( cnt!=1 ){ - char *z = 0; - char *zErr; - zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s"; + const char *zErr; + zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ - sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0); + sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ - sqlite3SetString(&z, zTab, ".", zCol, (char*)0); - }else{ - z = sqlite3StrDup(zCol); - } - if( z ){ - sqlite3ErrorMsg(pParse, zErr, z); - sqlite3_free(z); - pTopNC->nErr++; - }else{ - db->mallocFailed = 1; - } + sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); + }else{ + sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); + } + pTopNC->nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the @@ -44618,10 +45890,147 @@ struct QueryCoder { Parse *pParse; /* The parsing context */ NameContext *pNC; /* Namespace of first enclosing query */ }; +#ifdef SQLITE_TEST + int sqlite3_enable_in_opt = 1; +#else + #define sqlite3_enable_in_opt 1 +#endif + +/* +** 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 +** either to test for membership of the (...) set or to iterate through +** its members, skipping duplicates. +** +** The cursor opened on the structure (database table, database index +** or ephermal table) is stored in pX->iTable before this function returns. +** 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_EPH - The cursor was opened on a specially created and +** populated epheremal table. +** +** An existing structure may only be used if the SELECT is of the simple +** form: +** +** SELECT <column> FROM <table> +** +** 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 <column> is an INTEGER PRIMARY KEY or an index can +** be found with <column> as its left-most column. +** +** 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 <column> 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 mustBeUnique){ + Select *p; + int eType = 0; + int iTab = pParse->nTab++; + + /* The follwing if(...) expression is true if the SELECT is of the + ** simple form: + ** + ** SELECT <column> FROM <table> + ** + ** If this is the case, it may be possible to use an existing table + ** or index instead of generating an epheremal table. + */ + 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; + int iCol = pExpr->iColumn; + Vdbe *v = sqlite3GetVdbe(pParse); + + /* This function is only called from two places. In both cases the vdbe + ** has already been allocated. So assume sqlite3GetVdbe() is always + ** successful here. + */ + assert(v); + if( iCol<0 ){ + 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); + + sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); + eType = IN_INDEX_ROWID; + + sqlite3VdbeJumpHere(v, iAddr); + }else{ + /* The collation sequence used by the comparison. If an index is to + ** be used in place of a temp-table, it must be ordered according + ** to this collation sequence. + */ + CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr); + + /* Check that the affinity that will be used to perform the + ** comparison is the same as the affinity of the column. If + ** it is not, it is not possible to use any index. + */ + Table *pTab = p->pSrc->a[0].pTab; + char aff = comparisonAffinity(pX); + int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE); + + for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){ + if( (pIdx->aiColumn[0]==iCol) + && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0)) + && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None)) + ){ + int iDb; + int iMem = ++pParse->nMem; + int iAddr; + char *pKey; + + pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx); + iDb = sqlite3SchemaToIndex(db, pIdx->pSchema); + sqlite3VdbeUsesBtree(v, iDb); + + iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem); + + sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb, + pKey,P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + eType = IN_INDEX_INDEX; + sqlite3VdbeAddOp2(v, OP_SetNumColumns, iTab, pIdx->nColumn); + + sqlite3VdbeJumpHere(v, iAddr); + } + } + } + } + + if( eType==0 ){ + sqlite3CodeSubselect(pParse, pX); + eType = IN_INDEX_EPH; + }else{ + pX->iTable = iTab; + } + return eType; +} +#endif /* ** Generate code for scalar subqueries used as an expression ** and IN operators. Examples: ** @@ -44649,15 +46058,14 @@ ** ** If all of the above are false, then we can run this code just once ** save the results, and reuse the same result on subsequent invocations. */ if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){ - 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); + int mem = ++pParse->nMem; + sqlite3VdbeAddOp1(v, OP_If, mem); + testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem); + assert( testAddr>0 || pParse->db->mallocFailed ); } switch( pExpr->op ){ case TK_IN: { char affinity; @@ -44678,25 +46086,28 @@ ** if either column has NUMERIC or INTEGER affinity. If neither ** 'x' nor the SELECT... statement are columns, then numeric affinity ** is used. */ pExpr->iTable = pParse->nTab++; - addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0); + addr = sqlite3VdbeAddOp1(v, OP_OpenEphemeral, pExpr->iTable); memset(&keyInfo, 0, sizeof(keyInfo)); keyInfo.nField = 1; - sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, pExpr->iTable, 1); if( pExpr->pSelect ){ /* Case 1: expr IN (SELECT ...) ** ** Generate code to write the results of the select into the temporary ** table allocated and opened above. */ - int iParm = pExpr->iTable + (((int)affinity)<<16); + SelectDest dest; ExprList *pEList; + + sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable); + dest.affinity = (int)affinity; assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable ); - if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){ + if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0, 0) ){ return; } pEList = pExpr->pSelect->pEList; if( pEList && pEList->nExpr>0 ){ keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, @@ -44711,37 +46122,42 @@ ** a column, use numeric affinity. */ int i; ExprList *pList = pExpr->pList; struct ExprList_item *pItem; + int r1, r2; if( !affinity ){ affinity = SQLITE_AFF_NONE; } keyInfo.aColl[0] = pExpr->pLeft->pColl; /* Loop through each expression in <exprlist>. */ + r1 = sqlite3GetTempReg(pParse); + r2 = sqlite3GetTempReg(pParse); for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){ Expr *pE2 = pItem->pExpr; /* If the expression is not constant then we will need to ** disable the test that was generated above that makes sure ** this code only executes once. Because for a non-constant ** expression we need to rerun this code each time. */ - if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){ - sqlite3VdbeChangeToNoop(v, testAddr-1, 3); + if( testAddr && !sqlite3ExprIsConstant(pE2) ){ + sqlite3VdbeChangeToNoop(v, testAddr-1, 2); testAddr = 0; } /* Evaluate the expression and insert it into the temp table */ - sqlite3ExprCode(pParse, pE2); - sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); - sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0); - } - } - sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO); + sqlite3ExprCode(pParse, pE2, r1); + sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2); + } + sqlite3ReleaseTempReg(pParse, r1); + sqlite3ReleaseTempReg(pParse, r2); + } + sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO); break; } case TK_EXISTS: case TK_SELECT: { @@ -44749,35 +46165,35 @@ ** value of this select in a memory cell and record the number ** of the memory cell in iColumn. */ static const Token one = { (u8*)"1", 0, 1 }; Select *pSel; - int iMem; - int sop; - - pExpr->iColumn = iMem = pParse->nMem++; + SelectDest dest; + pSel = pExpr->pSelect; + sqlite3SelectDestInit(&dest, 0, ++pParse->nMem); if( pExpr->op==TK_SELECT ){ - sop = SRT_Mem; - sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0); - VdbeComment((v, "# Init subquery result")); - }else{ - sop = SRT_Exists; - sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem); - VdbeComment((v, "# Init EXISTS result")); + dest.eDest = SRT_Mem; + sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm); + VdbeComment((v, "Init subquery result")); + }else{ + dest.eDest = SRT_Exists; + sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm); + VdbeComment((v, "Init EXISTS result")); } sqlite3ExprDelete(pSel->pLimit); pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one); - if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){ + if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0, 0) ){ return; } + pExpr->iColumn = dest.iParm; break; } } if( testAddr ){ - sqlite3VdbeJumpHere(v, testAddr); + sqlite3VdbeJumpHere(v, testAddr-1); } return; } #endif /* SQLITE_OMIT_SUBQUERY */ @@ -44793,186 +46209,202 @@ return out; } /* ** Generate an instruction that will put the floating point -** value described by z[0..n-1] on the stack. +** value described by z[0..n-1] into register iMem. ** ** 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){ +static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){ assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed ); if( z ){ double value; char *zV; assert( !isdigit(z[n]) ); sqlite3AtoF(z, &value); if( negateFlag ) value = -value; zV = dup8bytes(v, (char*)&value); - sqlite3VdbeOp3(v, OP_Real, 0, 0, zV, P3_REAL); + sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL); } } /* ** Generate an instruction that will put the integer describe by -** text z[0..n-1] on the stack. +** text z[0..n-1] into register iMem. ** ** 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, const char *z, int n, int negateFlag){ +static void codeInteger(Vdbe *v, const char *z, int n, int negFlag, int iMem){ assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed ); if( z ){ int i; assert( !isdigit(z[n]) ); if( sqlite3GetInt32(z, &i) ){ - if( negateFlag ) i = -i; - sqlite3VdbeAddOp(v, OP_Integer, i, 0); - }else if( sqlite3FitsIn64Bits(z, negateFlag) ){ + if( negFlag ) i = -i; + sqlite3VdbeAddOp2(v, OP_Integer, i, iMem); + }else if( sqlite3FitsIn64Bits(z, negFlag) ){ i64 value; char *zV; sqlite3Atoi64(z, &value); - if( negateFlag ) value = -value; + if( negFlag ) value = -value; zV = dup8bytes(v, (char*)&value); - sqlite3VdbeOp3(v, OP_Int64, 0, 0, zV, P3_INT64); - }else{ - codeReal(v, z, n, negateFlag); + sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64); + }else{ + codeReal(v, z, n, negFlag, iMem); } } } /* ** Generate code that will extract the iColumn-th column from -** 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 void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){ +** table pTab and store the column value in register iReg. +** There is an open cursor to pTab in +** iTable. If iColumn<0 then code is generated that extracts the rowid. +*/ +SQLITE_PRIVATE void sqlite3ExprCodeGetColumn( + Vdbe *v, /* The VM being created */ + 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 */ +){ if( iColumn<0 ){ int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid; - sqlite3VdbeAddOp(v, op, iTable, 0); + sqlite3VdbeAddOp2(v, op, iTable, iReg); }else if( pTab==0 ){ - sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn); + sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg); }else{ int op = IsVirtual(pTab) ? OP_VColumn : OP_Column; - sqlite3VdbeAddOp(v, op, iTable, iColumn); + sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg); sqlite3ColumnDefault(v, pTab, iColumn); #ifndef SQLITE_OMIT_FLOATING_POINT if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){ - sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0); + sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg); } #endif } } /* ** Generate code into the current Vdbe to evaluate the given -** expression and leave the result on the top of stack. -** -** 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 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; +** expression. Attempt to store the results in register "target". +** Return the register where results are stored. +** +** 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. +*/ +static 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; /* Various register numbers */ + + assert( v!=0 || pParse->db->mallocFailed ); + assert( target>0 && target<=pParse->nMem ); + if( v==0 ) return 0; + if( pExpr==0 ){ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); - return; - } - op = pExpr->op; + op = TK_NULL; + }else{ + op = pExpr->op; + } switch( op ){ case TK_AGG_COLUMN: { AggInfo *pAggInfo = pExpr->pAggInfo; struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg]; if( !pAggInfo->directMode ){ - sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0); + assert( pCol->iMem>0 ); + inReg = pCol->iMem; break; }else if( pAggInfo->useSortingIdx ){ - sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx, - pCol->iSorterColumn); + sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx, + pCol->iSorterColumn, target); break; } /* Otherwise, fall thru into the TK_COLUMN case */ } case TK_COLUMN: { if( pExpr->iTable<0 ){ /* This only happens when coding check constraints */ - assert( pParse->ckOffset>0 ); - sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1); - }else{ - sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable); + assert( pParse->ckBase>0 ); + inReg = pExpr->iColumn + pParse->ckBase; + }else{ + sqlite3ExprCodeGetColumn(v, pExpr->pTab, + pExpr->iColumn, pExpr->iTable, target); } break; } case TK_INTEGER: { - codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0); + codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0, target); break; } case TK_FLOAT: { - codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0); + codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target); break; } case TK_STRING: { sqlite3DequoteExpr(pParse->db, pExpr); - sqlite3VdbeOp3(v,OP_String8, 0, 0, (char*)pExpr->token.z, pExpr->token.n); + sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0, + (char*)pExpr->token.z, pExpr->token.n); break; } case TK_NULL: { - sqlite3VdbeAddOp(v, OP_Null, 0, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, target); break; } #ifndef SQLITE_OMIT_BLOB_LITERAL case TK_BLOB: { int n; const char *z; - assert( TK_BLOB==OP_HexBlob ); + 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]=='\'' ); n = pExpr->token.n - 3; z = (char*)pExpr->token.z + 2; - assert( n>=0 ); - if( n==0 ){ - z = ""; - } - sqlite3VdbeOp3(v, op, 0, 0, z, n); + zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n); + sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC); break; } #endif case TK_VARIABLE: { - sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0); + sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target); if( pExpr->token.n>1 ){ - sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n); + sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n); } break; } case TK_REGISTER: { - sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0); + inReg = pExpr->iTable; break; } #ifndef SQLITE_OMIT_CAST case TK_CAST: { /* Expressions of the form: CAST(pLeft AS token) */ int aff, to_op; - sqlite3ExprCode(pParse, pExpr->pLeft); + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); aff = sqlite3AffinityType(&pExpr->token); to_op = aff - SQLITE_AFF_TEXT + OP_ToText; assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT ); assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE ); 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 ); - sqlite3VdbeAddOp(v, to_op, 0, 0); - stackChng = 0; + sqlite3VdbeAddOp1(v, to_op, inReg); break; } #endif /* SQLITE_OMIT_CAST */ case TK_LT: case TK_LE: @@ -44984,14 +46416,14 @@ assert( TK_LE==OP_Le ); assert( TK_GT==OP_Gt ); assert( TK_GE==OP_Ge ); assert( TK_EQ==OP_Eq ); assert( TK_NE==OP_Ne ); - sqlite3ExprCode(pParse, pExpr->pLeft); - sqlite3ExprCode(pParse, pExpr->pRight); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0); - stackChng = -1; + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, inReg, SQLITE_STOREP2); break; } case TK_AND: case TK_OR: case TK_PLUS: @@ -45013,59 +46445,61 @@ assert( TK_BITOR==OP_BitOr ); assert( TK_SLASH==OP_Divide ); assert( TK_LSHIFT==OP_ShiftLeft ); assert( TK_RSHIFT==OP_ShiftRight ); assert( TK_CONCAT==OP_Concat ); - sqlite3ExprCode(pParse, pExpr->pLeft); - sqlite3ExprCode(pParse, pExpr->pRight); - sqlite3VdbeAddOp(v, op, 0, 0); - stackChng = -1; + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + sqlite3VdbeAddOp3(v, op, r2, r1, target); 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*)p->z, p->n, 1); - }else{ - codeInteger(v, (char*)p->z, p->n, 1); - } - break; - } - /* Fall through into TK_NOT */ + codeReal(v, (char*)p->z, p->n, 1, target); + }else{ + codeInteger(v, (char*)p->z, p->n, 1, target); + } + }else{ + regFree1 = r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_Integer, 0, r1); + r2 = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target); + } + inReg = target; + break; } case TK_BITNOT: case TK_NOT: { assert( TK_BITNOT==OP_BitNot ); assert( TK_NOT==OP_Not ); - sqlite3ExprCode(pParse, pExpr->pLeft); - sqlite3VdbeAddOp(v, op, 0, 0); - stackChng = 0; + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + sqlite3VdbeAddOp1(v, op, inReg); break; } case TK_ISNULL: case TK_NOTNULL: { - int dest; + int addr; assert( TK_ISNULL==OP_IsNull ); assert( TK_NOTNULL==OP_NotNull ); - 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; + sqlite3VdbeAddOp2(v, OP_Integer, 1, target); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + addr = sqlite3VdbeAddOp1(v, op, r1); + sqlite3VdbeAddOp2(v, OP_AddImm, target, -1); + sqlite3VdbeJumpHere(v, addr); break; } case TK_AGG_FUNCTION: { AggInfo *pInfo = pExpr->pAggInfo; if( pInfo==0 ){ sqlite3ErrorMsg(pParse, "misuse of aggregate: %T", &pExpr->span); }else{ - sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0); + inReg = pInfo->aFunc[pExpr->iAgg].iMem; } break; } case TK_CONST_FUNC: case TK_FUNCTION: { @@ -45082,11 +46516,17 @@ zId = (char*)pExpr->token.z; nId = pExpr->token.n; pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0); assert( pDef!=0 ); - nExpr = sqlite3ExprCodeExprList(pParse, pList); + if( pList ){ + nExpr = pList->nExpr; + r1 = sqlite3GetTempRange(pParse, nExpr); + sqlite3ExprCodeExprList(pParse, pList, r1); + }else{ + nExpr = r1 = 0; + } #ifndef SQLITE_OMIT_VIRTUALTABLE /* Possibly overload the function if the first argument is ** a virtual table column. ** ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the @@ -45112,196 +46552,289 @@ pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr); } } if( pDef->needCollSeq ){ if( !pColl ) pColl = pParse->db->pDfltColl; - sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); - } - sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF); - stackChng = 1-nExpr; + sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); + } + sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target, + (char*)pDef, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, nExpr); + if( nExpr ){ + sqlite3ReleaseTempRange(pParse, r1, nExpr); + } break; } #ifndef SQLITE_OMIT_SUBQUERY case TK_EXISTS: case TK_SELECT: { if( pExpr->iColumn==0 ){ sqlite3CodeSubselect(pParse, pExpr); } - sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0); - VdbeComment((v, "# load subquery result")); + inReg = pExpr->iColumn; break; } case TK_IN: { - int addr; + int j1, j2, j3, j4, j5; char affinity; - int ckOffset = pParse->ckOffset; - sqlite3CodeSubselect(pParse, pExpr); + int eType; + + 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 - ** P3 of OP_MakeRecord. + ** P4 of OP_MakeRecord. */ affinity = comparisonAffinity(pExpr); - sqlite3VdbeAddOp(v, OP_Integer, 1, 0); - pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0); + sqlite3VdbeAddOp2(v, OP_Integer, 1, target); /* Code the <expr> from "<expr> IN (...)". The temporary table ** pExpr->iTable contains the values that make up the (...) set. */ - 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, addr+7); - sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); /* addr + 4 */ - sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7); - sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); /* addr + 6 */ - - break; - } -#endif + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + j2 = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, j1); + if( eType==IN_INDEX_ROWID ){ + j3 = sqlite3VdbeAddOp3(v, OP_MustBeInt, r1, 0, 1); + j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, r1); + j5 = sqlite3VdbeAddOp0(v, OP_Goto); + sqlite3VdbeJumpHere(v, j3); + sqlite3VdbeJumpHere(v, j4); + }else{ + r2 = regFree2 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1); + j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2); + } + sqlite3VdbeAddOp2(v, OP_AddImm, target, -1); + sqlite3VdbeJumpHere(v, j2); + sqlite3VdbeJumpHere(v, j5); + 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; - 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); + + r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); + r3 = sqlite3GetTempReg(pParse); + codeCompare(pParse, pLeft, pRight, OP_Ge, + r1, r2, r3, SQLITE_STOREP2); pLItem++; pRight = pLItem->pExpr; - sqlite3ExprCode(pParse, pRight); - codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0); - sqlite3VdbeAddOp(v, OP_And, 0, 0); + sqlite3ReleaseTempReg(pParse, regFree2); + r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2); + codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r2, SQLITE_STOREP2); + sqlite3VdbeAddOp3(v, OP_And, r3, r2, target); + sqlite3ReleaseTempReg(pParse, r3); break; } case TK_UPLUS: { - sqlite3ExprCode(pParse, pExpr->pLeft); - stackChng = 0; - break; - } + inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target); + 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 expr_end_label; - int jumpInst; - int nExpr; - int i; - ExprList *pEList; - struct ExprList_item *aListelem; + 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) */ assert(pExpr->pList); assert((pExpr->pList->nExpr % 2) == 0); assert(pExpr->pList->nExpr > 0); pEList = pExpr->pList; aListelem = pEList->a; nExpr = pEList->nExpr; - expr_end_label = sqlite3VdbeMakeLabel(v); - if( pExpr->pLeft ){ - sqlite3ExprCode(pParse, pExpr->pLeft); + endLabel = sqlite3VdbeMakeLabel(v); + if( (pX = pExpr->pLeft)!=0 ){ + cacheX = *pX; + cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, ®Free1); + cacheX.op = TK_REGISTER; + opCompare.op = TK_EQ; + opCompare.pLeft = &cacheX; + pTest = &opCompare; } for(i=0; i<nExpr; i=i+2){ - sqlite3ExprCode(pParse, aListelem[i].pExpr); - if( pExpr->pLeft ){ - 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{ - jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0); - } - 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( pX ){ + opCompare.pRight = aListelem[i].pExpr; + }else{ + pTest = aListelem[i].pExpr; + } + nextCase = sqlite3VdbeMakeLabel(v); + sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL); + sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target); + sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel); + sqlite3VdbeResolveLabel(v, nextCase); } if( pExpr->pRight ){ - sqlite3ExprCode(pParse, pExpr->pRight); - }else{ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); - } - sqlite3VdbeResolveLabel(v, expr_end_label); + sqlite3ExprCode(pParse, pExpr->pRight, target); + }else{ + sqlite3VdbeAddOp2(v, OP_Null, 0, target); + } + sqlite3VdbeResolveLabel(v, endLabel); break; } #ifndef SQLITE_OMIT_TRIGGER case TK_RAISE: { if( !pParse->trigStack ){ sqlite3ErrorMsg(pParse, "RAISE() may only be used within a trigger-program"); - return; + return 0; } if( pExpr->iColumn!=OE_Ignore ){ assert( pExpr->iColumn==OE_Rollback || pExpr->iColumn == OE_Abort || pExpr->iColumn == OE_Fail ); sqlite3DequoteExpr(pParse->db, pExpr); - sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, + sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0, (char*)pExpr->token.z, pExpr->token.n); } else { assert( pExpr->iColumn == OE_Ignore ); - sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0); - sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump); - VdbeComment((v, "# raise(IGNORE)")); - } - stackChng = 0; - break; - } -#endif - } - - if( pParse->ckOffset ){ - pParse->ckOffset += stackChng; - assert( pParse->ckOffset ); - } -} - -#ifndef SQLITE_OMIT_TRIGGER -/* -** Generate code that evalutes the given expression and leaves the result -** on the stack. See also sqlite3ExprCode(). -** -** 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 void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){ - Vdbe *v = pParse->pVdbe; - int iMem; - int addr1, addr2; - if( v==0 ) return; - addr1 = sqlite3VdbeCurrentAddr(v); - sqlite3ExprCode(pParse, pExpr); - addr2 = sqlite3VdbeCurrentAddr(v); - if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){ - iMem = pExpr->iTable = pParse->nMem++; - sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0); + sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0); + sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump); + VdbeComment((v, "raise(IGNORE)")); + } + 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 no +** 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; + } + return r2; +} + +/* +** 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. +** +** 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. +*/ +SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){ + 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->op = TK_REGISTER; } -} -#endif + return inReg; +} + /* ** Generate code that pushes the value of every element of the given -** expression list onto the stack. -** -** Return the number of elements pushed onto the stack. +** expression list into a sequence of registers beginning at target. +** +** Return the number of elements evaluated. */ SQLITE_PRIVATE int sqlite3ExprCodeExprList( Parse *pParse, /* Parsing context */ - ExprList *pList /* The expression list to be coded */ + ExprList *pList, /* The expression list to be coded */ + int target /* Where to write results */ ){ struct ExprList_item *pItem; int i, n; - if( pList==0 ) return 0; + assert( pList!=0 || pParse->db->mallocFailed ); + if( pList==0 ){ + return 0; + } + assert( target>0 ); n = pList->nExpr; for(pItem=pList->a, i=n; i>0; i--, pItem++){ - sqlite3ExprCode(pParse, pItem->pExpr); + sqlite3ExprCode(pParse, pItem->pExpr, target); + target++; } return n; } /* @@ -45308,11 +46841,11 @@ ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is true but execution ** 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 true. +** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL. ** ** 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 @@ -45319,17 +46852,21 @@ ** below verify that the numbers are aligned correctly. */ SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; - int ckOffset = pParse->ckOffset; + int regFree1 = 0; + int regFree2 = 0; + int r1, r2; + + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); if( v==0 || pExpr==0 ) return; op = pExpr->op; switch( op ){ case TK_AND: { int d2 = sqlite3VdbeMakeLabel(v); - sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull); + sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL); sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3VdbeResolveLabel(v, d2); break; } case TK_OR: { @@ -45351,68 +46888,81 @@ assert( TK_LE==OP_Le ); assert( TK_GT==OP_Gt ); assert( TK_GE==OP_Ge ); assert( TK_EQ==OP_Eq ); assert( TK_NE==OP_Ne ); - sqlite3ExprCode(pParse, pExpr->pLeft); - sqlite3ExprCode(pParse, pExpr->pRight); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, jumpIfNull); break; } case TK_ISNULL: case TK_NOTNULL: { assert( TK_ISNULL==OP_IsNull ); assert( TK_NOTNULL==OP_NotNull ); - sqlite3ExprCode(pParse, pExpr->pLeft); - sqlite3VdbeAddOp(v, op, 1, dest); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + sqlite3VdbeAddOp2(v, op, r1, dest); break; } case TK_BETWEEN: { - /* The expression "x BETWEEN y AND z" is implemented as: - ** - ** 1 IF (x < y) GOTO 3 - ** 2 IF (x <= z) GOTO <dest> - ** 3 ... - */ - 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); - - 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); + /* x BETWEEN y AND z + ** + ** Is equivalent to + ** + ** x>=y AND x<=z + ** + ** Code it as such, taking care to do the common subexpression + ** elementation of x. + */ + Expr exprAnd; + Expr compLeft; + Expr compRight; + Expr exprX; + + 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); + exprX.op = TK_REGISTER; + sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull); break; } default: { - sqlite3ExprCode(pParse, pExpr); - sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest); - break; - } - } - pParse->ckOffset = ckOffset; + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0); + break; + } + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); } /* ** Generate code for a boolean expression such that a jump is made ** to the label "dest" if the expression is false but execution ** continues straight thru if the expression is true. ** ** If the expression evaluates to NULL (neither true nor false) then -** jump if jumpIfNull is true or fall through if jumpIfNull is false. +** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull +** is 0. */ SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){ Vdbe *v = pParse->pVdbe; int op = 0; - int ckOffset = pParse->ckOffset; + int regFree1 = 0; + int regFree2 = 0; + int r1, r2; + + assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 ); if( v==0 || pExpr==0 ) return; /* The value of pExpr->op and op are related as follows: ** ** pExpr->op op @@ -45450,11 +47000,11 @@ sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); break; } case TK_OR: { int d2 = sqlite3VdbeMakeLabel(v); - sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull); + sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL); sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull); sqlite3VdbeResolveLabel(v, d2); break; } case TK_NOT: { @@ -45465,51 +47015,60 @@ case TK_LE: case TK_GT: case TK_GE: case TK_NE: case TK_EQ: { - sqlite3ExprCode(pParse, pExpr->pLeft); - sqlite3ExprCode(pParse, pExpr->pRight); - codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2); + codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, + r1, r2, dest, jumpIfNull); break; } case TK_ISNULL: case TK_NOTNULL: { - sqlite3ExprCode(pParse, pExpr->pLeft); - sqlite3VdbeAddOp(v, op, 1, dest); + r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1); + sqlite3VdbeAddOp2(v, op, r1, dest); break; } case TK_BETWEEN: { - /* The expression is "x BETWEEN y AND z". It is implemented as: - ** - ** 1 IF (x >= y) GOTO 3 - ** 2 GOTO <dest> - ** 3 IF (x > z) GOTO <dest> - */ - 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); - - 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); + /* x BETWEEN y AND z + ** + ** Is equivalent to + ** + ** x>=y AND x<=z + ** + ** Code it as such, taking care to do the common subexpression + ** elementation of x. + */ + Expr exprAnd; + Expr compLeft; + Expr compRight; + Expr exprX; + + 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); + exprX.op = TK_REGISTER; + sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull); break; } default: { - sqlite3ExprCode(pParse, pExpr); - sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest); - break; - } - } - pParse->ckOffset = ckOffset; + r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1); + sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0); + break; + } + } + sqlite3ReleaseTempReg(pParse, regFree1); + sqlite3ReleaseTempReg(pParse, regFree2); } /* ** Do a deep comparison of two expression trees. Return TRUE (non-zero) ** if they are identical and return FALSE if they differ in any way. @@ -45636,11 +47195,11 @@ ){ pCol = &pAggInfo->aCol[k]; 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 ){ int j, n; ExprList *pGB = pAggInfo->pGroupBy; @@ -45692,11 +47251,11 @@ u8 enc = ENC(pParse->db); i = addAggInfoFunc(pParse->db, pAggInfo); 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); if( pExpr->flags & EP_Distinct ){ pItem->iDistinct = pParse->nTab++; @@ -45731,36 +47290,68 @@ ** for variables that need to be added to the pParse->aAgg[] array. ** Make additional entries to the pParse->aAgg[] array as necessary. ** ** 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 int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ - int nErr = pNC->pParse->nErr; - walkExprTree(pExpr, analyzeAggregate, pNC); - return pNC->pParse->nErr - nErr; +*/ +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){ + walkExprTree(pExpr, analyzeAggregate, pNC); } /* ** Call sqlite3ExprAnalyzeAggregates() for every expression in an ** expression list. Return the number of errors. ** ** If an error is found, the analysis is cut short. */ -SQLITE_PRIVATE int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ +SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){ struct ExprList_item *pItem; int i; - int nErr = 0; if( pList ){ - for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){ - nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); - } - } - return nErr; + for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){ + sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr); + } + } +} + +/* +** Allocate or deallocate temporary use registers during code generation. +*/ +SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){ + if( pParse->nTempReg ){ + return pParse->aTempReg[--pParse->nTempReg]; + }else{ + return ++pParse->nMem; + } +} +SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){ + if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){ + assert( iReg>0 ); + pParse->aTempReg[pParse->nTempReg++] = iReg; + } +} + +/* +** Allocate or deallocate a block of nReg consecutive registers +*/ +SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){ + int i; + if( nReg<=pParse->nRangeReg ){ + i = pParse->iRangeReg; + 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; + } } /************** End of expr.c ************************************************/ /************** Begin file alter.c *******************************************/ /* @@ -45775,11 +47366,11 @@ ** ************************************************************************* ** This file contains C code routines that used to generate VDBE code ** that implements the ALTER TABLE command. ** -** $Id: alter.c,v 1.33 2007/10/20 20:58:57 drh Exp $ +** $Id: alter.c,v 1.41 2008/01/25 15:04:48 drh Exp $ */ /* ** The code in this file only exists if we are not omitting the ** ALTER TABLE logic from the build. @@ -45830,11 +47421,11 @@ /* Store the token that zCsr points to in tname. */ tname.z = zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', - ** and it's length in 'len' (to be used next iteration of this loop). + ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = sqlite3GetToken(zCsr, &token); } while( token==TK_SPACE ); @@ -45888,11 +47479,11 @@ /* Store the token that zCsr points to in tname. */ tname.z = zCsr; tname.n = len; /* Advance zCsr to the next token. Store that token type in 'token', - ** and it's length in 'len' (to be used next iteration of this loop). + ** and its length in 'len' (to be used next iteration of this loop). */ do { zCsr += len; len = sqlite3GetToken(zCsr, &token); }while( token==TK_SPACE ); @@ -46004,28 +47595,28 @@ #ifndef SQLITE_OMIT_TRIGGER /* Drop any table triggers from the internal schema. */ for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){ int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema); assert( iTrigDb==iDb || iTrigDb==1 ); - sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0); + sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0); } #endif /* Drop the table and index from the internal schema */ - sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0); + sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); /* Reload the table, index and permanent trigger schemas. */ zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName); if( !zWhere ) return; - sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC); + sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_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 ){ - sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC); + sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC); } #endif } /* @@ -46052,11 +47643,11 @@ if( db->mallocFailed ) goto exit_rename_table; assert( pSrc->nSrc==1 ); assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); - pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase); + pTab = sqlite3LocateTable(pParse, 0, 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; /* Get a NULL terminated version of the new table name. */ @@ -46081,10 +47672,17 @@ } if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto exit_rename_table; } +#ifndef SQLITE_OMIT_VIEW + if( pTab->pSelect ){ + sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); + goto exit_rename_table; + } +#endif + #ifndef SQLITE_OMIT_AUTHORIZATION /* Invoke the authorization callback. */ if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ goto exit_rename_table; } @@ -46107,21 +47705,22 @@ v = sqlite3GetVdbe(pParse); if( v==0 ){ goto exit_rename_table; } sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb); - sqlite3ChangeCookie(db, v, iDb); + sqlite3ChangeCookie(pParse, iDb); /* If this is a virtual table, invoke the xRename() function if ** one is defined. The xRename() callback will modify the names ** of any resources used by the v-table implementation (including other ** SQLite tables) that are identified by the name of the virtual table. */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( isVirtualRename ){ - sqlite3VdbeOp3(v, OP_String8, 0, 0, zName, 0); - sqlite3VdbeOp3(v, OP_VRename, 0, 0, (const char*)pTab->pVtab, P3_VTAB); + 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); } #endif /* figure out how many UTF-8 characters are in zName */ zTabName = pTab->zName; @@ -46322,11 +47921,11 @@ /* Look up the table being altered. */ assert( pParse->pNewTable==0 ); assert( sqlite3BtreeHoldsAllMutexes(db) ); if( db->mallocFailed ) goto exit_begin_add_column; - pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase); + pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase); if( !pTab ) goto exit_begin_add_column; #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); @@ -46374,11 +47973,11 @@ /* Begin a transaction and increment the schema cookie. */ sqlite3BeginWriteOperation(pParse, 0, iDb); v = sqlite3GetVdbe(pParse); if( !v ) goto exit_begin_add_column; - sqlite3ChangeCookie(db, v, iDb); + sqlite3ChangeCookie(pParse, iDb); exit_begin_add_column: sqlite3SrcListDelete(pSrc); return; } @@ -46397,11 +47996,11 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code associated with the ANALYZE command. ** -** @(#) $Id: analyze.c,v 1.24 2007/11/15 13:10:23 danielk1977 Exp $ +** @(#) $Id: analyze.c,v 1.41 2008/01/25 15:04:49 drh Exp $ */ #ifndef SQLITE_OMIT_ANALYZE /* ** This routine generates code that opens the sqlite_stat1 table on cursor @@ -46418,10 +48017,11 @@ const char *zWhere /* Delete entries associated with this table */ ){ sqlite3 *db = pParse->db; Db *pDb; int iRootPage; + int createStat1 = 0; Table *pStat; Vdbe *v = sqlite3GetVdbe(pParse); if( v==0 ) return; assert( sqlite3BtreeHoldsAllMutexes(db) ); @@ -46428,17 +48028,18 @@ assert( sqlite3VdbeDb(v)==db ); pDb = &db->aDb[iDb]; 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 on the top of the stack. This is + ** the rootpage of the new table in register pParse->regRoot. 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 = 0; /* Cause rootpage to be taken from top of stack */ + iRootPage = pParse->regRoot; + createStat1 = 1; /* 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. */ sqlite3NestedParse(pParse, "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", @@ -46446,24 +48047,24 @@ ); iRootPage = pStat->tnum; }else{ /* The sqlite_stat1 table already exists. Delete all rows. */ iRootPage = pStat->tnum; - sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb); + sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb); } /* Open the sqlite_stat1 table for writing. Unless it was created ** by this vdbe program, lock it for writing at the shared-cache level. ** If this vdbe did create the sqlite_stat1 table, then it must have ** already obtained a schema-lock, making the write-lock redundant. */ - if( iRootPage>0 ){ + if( !createStat1 ){ sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1"); } - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); - sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage); - sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3); + sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb); + sqlite3VdbeChangeP5(v, createStat1); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, iStatCur, 3); } /* ** Generate code to do an analysis of all indices associated with ** a single table. @@ -46503,23 +48104,31 @@ sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName); 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); + sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb, + (char *)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); nCol = pIdx->nColumn; - if( iMem+nCol*2>=pParse->nMem ){ - pParse->nMem = iMem+nCol*2+1; - } - sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, nCol+1); + regFields = iMem+nCol*2; + regTemp = regRowid = regCol = regFields+3; + regRec = regCol+1; + if( regRec>pParse->nMem ){ + pParse->nMem = regRec; + } + sqlite3VdbeAddOp2(v, OP_SetNumColumns, iIdxCur, nCol+1); /* Memory cells are used as follows: ** ** mem[iMem]: The total number of rows in the table. ** mem[iMem+1]: Number of distinct values in column 1 @@ -46531,37 +48140,37 @@ ** ** Cells iMem through iMem+nCol are initialized to 0. The others ** are initialized to NULL. */ for(i=0; i<=nCol; i++){ - sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem+i); + sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i); } for(i=0; i<nCol; i++){ - sqlite3VdbeAddOp(v, OP_MemNull, iMem+nCol+i+1, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1); } /* Do the analysis. */ endOfLoop = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, endOfLoop); + sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop); topOfLoop = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem); + sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1); for(i=0; i<nCol; i++){ - sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i); - sqlite3VdbeAddOp(v, OP_MemLoad, iMem+nCol+i+1, 0); - sqlite3VdbeAddOp(v, OP_Ne, 0x100, 0); - } - sqlite3VdbeAddOp(v, OP_Goto, 0, endOfLoop); + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol); + sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1); + /**** TODO: add collating sequence *****/ + sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL); + } + sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop); for(i=0; i<nCol; i++){ - addr = sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem+i+1); - sqlite3VdbeChangeP2(v, topOfLoop + 3*i + 3, addr); - sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i); - sqlite3VdbeAddOp(v, OP_MemStore, iMem+nCol+i+1, 1); + sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1)); + sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1); + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1); } sqlite3VdbeResolveLabel(v, endOfLoop); - sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop); - sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0); + sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop); + sqlite3VdbeAddOp1(v, OP_Close, iIdxCur); /* Store the results. ** ** The result is a single row of the sqlite_stat1 table. The first ** two columns are the names of the table and index. The third column @@ -46577,33 +48186,28 @@ ** ** If K==0 then no entry is made into the sqlite_stat1 table. ** If K>0 then it is always the case the D>0 so division by zero ** is never possible. */ - 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); + 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); for(i=0; i<nCol; i++){ - sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0); - sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0); - sqlite3VdbeAddOp(v, OP_Add, 0, 0); - sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); - sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0); - sqlite3VdbeAddOp(v, OP_Divide, 0, 0); - sqlite3VdbeAddOp(v, OP_ToInt, 0, 0); - if( i==nCol-1 ){ - sqlite3VdbeAddOp(v, OP_Concat, nCol*2-1, 0); - }else{ - sqlite3VdbeAddOp(v, OP_Dup, 1, 0); - } - } - sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "aaa", 0); - sqlite3VdbeAddOp(v, OP_Insert, iStatCur, OPFLAG_APPEND); + sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0); + sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2); + sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp); + sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1); + sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp); + sqlite3VdbeAddOp1(v, OP_ToInt, regTemp); + sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2); + } + sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0); + sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); sqlite3VdbeJumpHere(v, addr); } } /* @@ -46611,11 +48215,11 @@ ** be laoded into internal hash tables where is can be used. */ static void loadAnalysis(Parse *pParse, int iDb){ Vdbe *v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp(v, OP_LoadAnalysis, iDb, 0); + sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb); } } /* ** Generate code that will do an analysis of an entire database @@ -46628,11 +48232,11 @@ int iMem; sqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab++; openStatTable(pParse, iDb, iStatCur, 0); - iMem = pParse->nMem; + iMem = pParse->nMem+1; for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ Table *pTab = (Table*)sqliteHashData(k); analyzeOneTable(pParse, pTab, iStatCur, iMem); } loadAnalysis(pParse, iDb); @@ -46650,11 +48254,11 @@ assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); sqlite3BeginWriteOperation(pParse, 0, iDb); iStatCur = pParse->nTab++; openStatTable(pParse, iDb, iStatCur, pTab->zName); - analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem); + analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1); loadAnalysis(pParse, iDb); } /* ** Generate code for the ANALYZE command. The parser calls this routine @@ -46695,11 +48299,11 @@ if( iDb>=0 ){ analyzeDatabase(pParse, iDb); }else{ z = sqlite3NameFromToken(db, pName1); if( z ){ - pTab = sqlite3LocateTable(pParse, z, 0); + pTab = sqlite3LocateTable(pParse, 0, z, 0); sqlite3_free(z); if( pTab ){ analyzeTable(pParse, pTab); } } @@ -46709,11 +48313,11 @@ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName); if( iDb>=0 ){ zDb = db->aDb[iDb].zName; z = sqlite3NameFromToken(db, pTableName); if( z ){ - pTab = sqlite3LocateTable(pParse, z, zDb); + pTab = sqlite3LocateTable(pParse, 0, z, zDb); sqlite3_free(z); if( pTab ){ analyzeTable(pParse, pTab); } } @@ -46794,13 +48398,13 @@ /* Load new statistics out of the sqlite_stat1 table */ zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase); - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0); - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); sqlite3_free(zSql); return rc; } @@ -46819,11 +48423,11 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the ATTACH and DETACH commands. ** -** $Id: attach.c,v 1.63 2007/10/03 08:46:44 danielk1977 Exp $ +** $Id: attach.c,v 1.70 2008/01/23 03:03:05 drh Exp $ */ #ifndef SQLITE_OMIT_ATTACH /* ** Resolve an expression that was part of an ATTACH or DETACH statement. This @@ -46993,13 +48597,15 @@ ** If this fails, or if opening the file failed, then close the file and ** remove the entry from the db->aDb[] array. i.e. put everything back the way ** we found it. */ if( rc==SQLITE_OK ){ - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); + sqlite3BtreeEnterAll(db); rc = sqlite3Init(db, &zErrDyn); - sqlite3SafetyOff(db); + sqlite3BtreeLeaveAll(db); + (void)sqlite3SafetyOff(db); } if( rc ){ int iDb = db->nDb - 1; assert( iDb>=2 ); if( db->aDb[iDb].pBt ){ @@ -47102,10 +48708,11 @@ int rc; NameContext sName; Vdbe *v; FuncDef *pFunc; sqlite3* db = pParse->db; + int regArgs; #ifndef SQLITE_OMIT_AUTHORIZATION assert( db->mallocFailed || pAuthArg ); if( pAuthArg ){ char *zAuthArg = sqlite3NameFromToken(db, &pAuthArg->span); @@ -47131,25 +48738,27 @@ pParse->nErr++; goto attach_end; } v = sqlite3GetVdbe(pParse); - sqlite3ExprCode(pParse, pFilename); - sqlite3ExprCode(pParse, pDbname); - sqlite3ExprCode(pParse, pKey); + regArgs = sqlite3GetTempRange(pParse, 3); + sqlite3ExprCode(pParse, pFilename, regArgs); + sqlite3ExprCode(pParse, pDbname, regArgs+1); + sqlite3ExprCode(pParse, pKey, regArgs+2); assert( v || db->mallocFailed ); if( v ){ - sqlite3VdbeAddOp(v, OP_Function, 0, nFunc); + sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-nFunc, regArgs); + sqlite3VdbeChangeP5(v, nFunc); pFunc = sqlite3FindFunction(db, zFunc, strlen(zFunc), nFunc, SQLITE_UTF8,0); - sqlite3VdbeChangeP3(v, -1, (char *)pFunc, P3_FUNCDEF); + sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_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). */ - sqlite3VdbeAddOp(v, OP_Expire, (type==SQLITE_ATTACH), 0); + sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH)); } attach_end: sqlite3ExprDelete(pFilename); sqlite3ExprDelete(pDbname); @@ -47589,11 +49198,11 @@ ** creating ID lists ** BEGIN TRANSACTION ** COMMIT ** ROLLBACK ** -** $Id: build.c,v 1.448 2007/11/12 09:50:26 danielk1977 Exp $ +** $Id: build.c,v 1.472 2008/01/31 13:35:49 drh Exp $ */ /* ** This routine is called when a new SQL statement is beginning to ** be parsed. Initialize the pParse structure as needed. @@ -47679,11 +49288,11 @@ TableLock *p = &pParse->aTableLock[i]; int p1 = p->iDb; if( p->isWriteLock ){ p1 = -1*(p1+1); } - sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC); + sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, 0, p->zName, P4_STATIC); } } #else #define codeTableLocks(x) #endif @@ -47703,10 +49312,11 @@ Vdbe *v; 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; return; } @@ -47715,11 +49325,11 @@ /* Begin by generating some termination code at the end of the ** vdbe program */ v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp(v, OP_Halt, 0, 0); + sqlite3VdbeAddOp0(v, OP_Halt); /* 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 ** set for each database that is used. Generate code to start a ** transaction on each used database and to verify the schema cookie @@ -47730,36 +49340,38 @@ int iDb; sqlite3VdbeJumpHere(v, pParse->cookieGoto-1); for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){ if( (mask & pParse->cookieMask)==0 ) continue; sqlite3VdbeUsesBtree(v, iDb); - sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0); - sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); + sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0); + sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]); } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pParse->pVirtualLock ){ char *vtab = (char *)pParse->pVirtualLock->pVtab; - sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB); + sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB); } #endif /* Once all the cookies have been verified and transactions opened, ** obtain the required table-locks. This is a no-op unless the ** shared-cache feature is enabled. */ codeTableLocks(pParse); - sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto); + sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto); } #ifndef SQLITE_OMIT_TRACE - /* 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); + 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); + } + } #endif /* SQLITE_OMIT_TRACE */ } /* Get the VDBE program ready for execution @@ -47853,11 +49465,16 @@ ** ** The difference between this routine and sqlite3FindTable() is that this ** routine leaves an error message in pParse->zErrMsg where ** sqlite3FindTable() does not. */ -SQLITE_PRIVATE Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){ +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 */ +){ Table *p; /* Read the database schema. If an error occurs, leave an error message ** and code in pParse and return NULL. */ if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ @@ -47864,14 +49481,15 @@ return 0; } p = sqlite3FindTable(pParse->db, zName, zDbase); if( p==0 ){ + const char *zMsg = isView ? "no such view" : "no such table"; if( zDbase ){ - sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName); - }else{ - sqlite3ErrorMsg(pParse, "no such table: %s", zName); + sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName); + }else{ + sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName); } pParse->checkSchema = 1; } return p; } @@ -47968,21 +49586,26 @@ ** files. If iDb>=2 then reset the internal schema for only the ** single file indicated. */ SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){ int i, j; - assert( iDb>=0 && iDb<db->nDb ); + + if( iDb==0 ){ + sqlite3BtreeEnterAll(db); + } for(i=iDb; i<db->nDb; i++){ Db *pDb = &db->aDb[i]; if( pDb->pSchema ){ + assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt))); sqlite3SchemaFree(pDb->pSchema); } if( iDb>0 ) return; } assert( iDb==0 ); db->flags &= ~SQLITE_InternChanges; + sqlite3BtreeLeaveAll(db); /* If one or more of the auxiliary database files has been closed, ** then remove them from the auxiliary database list. We take the ** opportunity to do this here since we have just deleted all of the ** schema hash tables and therefore do not have to make any changes @@ -48159,13 +49782,12 @@ ** writing. The table is opened using cursor 0. */ SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){ Vdbe *v = sqlite3GetVdbe(p); sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(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 */ + sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */ } /* ** The token *pName contains the name of a database (either "main" or ** "temp" or the name of an attached db). This routine returns the @@ -48398,34 +50020,37 @@ ** indices to be created and the table record must come before the ** indices. Hence, the record number for the table must be allocated ** now. */ if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ - int lbl; + int j1; int fileFormat; + int reg1, reg2, reg3; sqlite3BeginWriteOperation(pParse, 0, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( isVirtual ){ - sqlite3VdbeAddOp(v, OP_VBegin, 0, 0); + sqlite3VdbeAddOp0(v, OP_VBegin); } #endif /* If the file format and encoding in the database have not been set, ** set them now. */ - sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */ + reg1 = pParse->regRowid = ++pParse->nMem; + reg2 = pParse->regRoot = ++pParse->nMem; + reg3 = ++pParse->nMem; + sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */ sqlite3VdbeUsesBtree(v, iDb); - lbl = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp(v, OP_If, 0, lbl); + j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? 1 : SQLITE_MAX_FILE_FORMAT; - 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); + 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); /* This just creates a place-holder record in the sqlite_master table. ** The record created does not contain anything yet. It will be replaced ** by the real entry in code generated at sqlite3EndTable(). ** @@ -48433,23 +50058,22 @@ ** The rowid value is needed by the code that sqlite3EndTable will ** generate. */ #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) if( isView || isVirtual ){ - sqlite3VdbeAddOp(v, OP_Integer, 0, 0); + sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2); }else #endif { - sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0); + sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2); } sqlite3OpenMasterTable(pParse, iDb); - 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); + 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); } /* Normal (non-error) return. */ return; @@ -48834,13 +50458,17 @@ ** the schema to change multiple times and for the cookie to be ** set back to prior value. But schema changes are infrequent ** 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(sqlite3 *db, Vdbe *v, int iDb){ - sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0); - sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0); +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); } /* ** Measure the number of characters needed to output the given ** identifier. The number returned includes any quotes used @@ -48883,11 +50511,11 @@ /* ** Generate a CREATE TABLE statement appropriate for the given ** table. Memory to hold the text of the statement is obtained ** from sqliteMalloc() and must be freed by the calling function. */ -static char *createTableStmt(Table *p, int isTemp){ +static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){ int i, k, n; char *zStmt; char *zSep, *zSep2, *zEnd, *z; Column *pCol; n = 0; @@ -48908,11 +50536,14 @@ zSep2 = ",\n "; zEnd = "\n)"; } n += 35 + 6*p->nCol; zStmt = sqlite3_malloc( n ); - if( zStmt==0 ) return 0; + if( zStmt==0 ){ + db->mallocFailed = 1; + return 0; + } sqlite3_snprintf(n, zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE "); k = strlen(zStmt); identPut(zStmt, &k, p->zName); zStmt[k++] = '('; @@ -49019,11 +50650,11 @@ char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */ v = sqlite3GetVdbe(pParse); if( v==0 ) return; - sqlite3VdbeAddOp(v, OP_Close, 0, 0); + sqlite3VdbeAddOp1(v, OP_Close, 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 ** views. Initialize zType at the same time. */ @@ -49051,17 +50682,19 @@ ** as a schema-lock must have already been obtained to create it. Since ** a schema-lock excludes all other database users, the write-lock would ** be redundant. */ if( pSelect ){ + SelectDest dest; Table *pSelTab; - sqlite3VdbeAddOp(v, OP_Dup, 0, 0); - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); - sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0); + + sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb); + sqlite3VdbeChangeP5(v, 1); pParse->nTab = 2; - sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0); - sqlite3VdbeAddOp(v, OP_Close, 1, 0); + sqlite3SelectDestInit(&dest, SRT_Table, 1); + sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0); + sqlite3VdbeAddOp1(v, OP_Close, 1); if( pParse->nErr==0 ){ pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect); if( pSelTab==0 ) return; assert( p->aCol==0 ); p->nCol = pSelTab->nCol; @@ -49072,11 +50705,11 @@ } } /* Compute the complete text of the CREATE statement */ if( pSelect ){ - zStmt = createTableStmt(p, p->pSchema==db->aDb[1].pSchema); + zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema); }else{ n = pEnd->z - pParse->sNameToken.z + 1; zStmt = sqlite3MPrintf(db, "CREATE %s %.*s", zType2, n, pParse->sNameToken.z ); @@ -49088,20 +50721,22 @@ ** slot is the 2nd item on the stack. The top of the stack is the ** root page for the new table (or a 0 if this is a view). */ sqlite3NestedParse(pParse, "UPDATE %Q.%s " - "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q " - "WHERE rowid=#1", + "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " + "WHERE rowid=#%d", db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zType, p->zName, p->zName, - zStmt + pParse->regRoot, + zStmt, + pParse->regRowid ); sqlite3_free(zStmt); - sqlite3ChangeCookie(db, v, iDb); + sqlite3ChangeCookie(pParse, iDb); #ifndef SQLITE_OMIT_AUTOINCREMENT /* Check to see if we need to create an sqlite_sequence table for ** keeping track of autoincrement keys. */ @@ -49115,12 +50750,12 @@ } } #endif /* Reparse everything to update our internal data structures */ - sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, - sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P3_DYNAMIC); + sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, + sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC); } /* Add the table to the in-memory representation of the database. */ @@ -49392,24 +51027,26 @@ ** if a root-page of another table is moved by the btree-layer whilst ** erasing iTable (this can happen with an auto-vacuum database). */ static void destroyRootPage(Parse *pParse, int iTable, int iDb){ Vdbe *v = sqlite3GetVdbe(pParse); - sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb); + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb); #ifndef SQLITE_OMIT_AUTOVACUUM - /* OP_Destroy pushes an integer onto the stack. If this integer + /* OP_Destroy stores an in integer r1. 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 "#0" in the SQL is a special constant that means whatever value + ** The "#%d" 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 #0 AND rootpage=#0", - pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable); -#endif + "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d", + pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1); +#endif + sqlite3ReleaseTempReg(pParse, r1); } /* ** Write VDBE code to erase table pTab and all associated indices on disk. ** Code to update the sqlite_master tables and internal schema definitions @@ -49481,11 +51118,12 @@ if( pParse->nErr || db->mallocFailed ){ goto exit_drop_table; } assert( pName->nSrc==1 ); - pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase); + pTab = sqlite3LocateTable(pParse, isView, + pName->a[0].zName, pName->a[0].zDatabase); if( pTab==0 ){ if( noErr ){ sqlite3ErrorClear(pParse); } @@ -49559,17 +51197,17 @@ */ v = sqlite3GetVdbe(pParse); if( v ){ Trigger *pTrigger; Db *pDb = &db->aDb[iDb]; - sqlite3BeginWriteOperation(pParse, 0, iDb); + sqlite3BeginWriteOperation(pParse, 1, iDb); #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ Vdbe *v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp(v, OP_VBegin, 0, 0); + sqlite3VdbeAddOp0(v, OP_VBegin); } } #endif /* Drop all triggers associated with the table being dropped. Code @@ -49614,14 +51252,14 @@ /* Remove the table entry from SQLite's internal schema and modify ** the schema cookie. */ if( IsVirtual(pTab) ){ - sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0); - } - sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0); - sqlite3ChangeCookie(db, v, iDb); + sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0); + } + sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0); + sqlite3ChangeCookie(pParse, iDb); } sqliteViewResetAll(db, iDb); exit_drop_table: sqlite3SrcListDelete(pName); @@ -49766,11 +51404,11 @@ ** Generate code that will erase and refill index *pIdx. This is ** used to initialize a newly created index or to recompute the ** content of an index in response to a REINDEX command. ** ** if memRootPage is not negative, it means that the index is newly -** created. The memory cell specified by memRootPage contains the +** created. The register 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. */ static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){ @@ -49779,10 +51417,12 @@ int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */ int addr1; /* Address of top of loop */ 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); #ifndef SQLITE_OMIT_AUTHORIZATION if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0, @@ -49795,38 +51435,44 @@ sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName); v = sqlite3GetVdbe(pParse); if( v==0 ) return; if( memRootPage>=0 ){ - sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0); - tnum = 0; + tnum = memRootPage; }else{ tnum = pIndex->tnum; - sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb); - } - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); + sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb); + } pKey = sqlite3IndexKeyinfo(pParse, pIndex); - sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, + (char *)pKey, P4_KEYINFO_HANDOFF); + if( memRootPage>=0 ){ + sqlite3VdbeChangeP5(v, 1); + } sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead); - addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0); - sqlite3GenerateIndexKey(v, pIndex, iTab); + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); + regRecord = sqlite3GetTempReg(pParse); + regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord); if( pIndex->onError!=OE_None ){ - 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) ); - } - sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0); - sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1); + 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, (char*)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); + } + sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord); + sqlite3ReleaseTempReg(pParse, regRecord); + sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp(v, OP_Close, iTab, 0); - sqlite3VdbeAddOp(v, OP_Close, iIdx, 0); + sqlite3VdbeAddOp1(v, OP_Close, iTab); + sqlite3VdbeAddOp1(v, OP_Close, iIdx); } /* ** Create a new index for an SQL table. pName1.pName2 is the name of the index ** and pTblList is the name of the table that is to be indexed. Both will @@ -49885,15 +51531,18 @@ iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); if( iDb<0 ) goto exit_create_index; #ifndef SQLITE_OMIT_TEMPDB /* If the index name was unqualified, check if the the table - ** is a temp table. If so, set the database to 1. - */ - pTab = sqlite3SrcListLookup(pParse, pTblName); - if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ - iDb = 1; + ** is a temp table. If so, set the database to 1. Do not do this + ** if initialising a database schema. + */ + if( !db->init.busy ){ + pTab = sqlite3SrcListLookup(pParse, pTblName); + if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){ + iDb = 1; + } } #endif if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) && sqlite3FixSrcList(&sFix, pTblName) @@ -49900,11 +51549,11 @@ ){ /* Because the parser constructs pTblName from a single identifier, ** sqlite3FixSrcList can never fail. */ assert(0); } - pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName, + pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, pTblName->a[0].zDatabase); if( !pTab ) goto exit_create_index; assert( db->aDb[iDb].pSchema==pTab->pSchema ); }else{ assert( pName==0 ); @@ -50185,21 +51834,20 @@ ** step can be skipped. */ 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; /* Create the rootpage for the index */ sqlite3BeginWriteOperation(pParse, 1, iDb); - sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0); - sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0); + sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem); /* Gather the complete text of the CREATE INDEX statement into ** the zStmt variable */ if( pStart && pEnd ){ @@ -50215,28 +51863,28 @@ } /* Add an entry in sqlite_master for this index */ sqlite3NestedParse(pParse, - "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);", + "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%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 ** to invalidate all pre-compiled statements. */ if( pTblName ){ sqlite3RefillIndex(pParse, pIndex, iMem); - sqlite3ChangeCookie(db, v, iDb); - sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, - sqlite3MPrintf(db, "name='%q'", pIndex->zName), P3_DYNAMIC); - sqlite3VdbeAddOp(v, OP_Expire, 0, 0); + sqlite3ChangeCookie(pParse, iDb); + sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, + sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC); + sqlite3VdbeAddOp1(v, OP_Expire, 0); } } /* When adding an index to the list of indices for a table, make ** sure all indices labeled OE_Replace come after all those labeled @@ -50276,16 +51924,21 @@ */ SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){ Vdbe *v; v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); + int r1 = sqlite3GetTempReg(pParse); + int r2 = sqlite3GetTempReg(pParse); + int j1; + sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1); sqlite3VdbeUsesBtree(v, iDb); - 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); + 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); } } /* ** Fill the Index.aiRowEst[] array with default information - information @@ -50370,18 +52023,19 @@ #endif /* Generate code to remove the index and from the master table */ v = sqlite3GetVdbe(pParse); if( v ){ + sqlite3BeginWriteOperation(pParse, 1, iDb); sqlite3NestedParse(pParse, "DELETE FROM %Q.%s WHERE name=%Q", db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName ); - sqlite3ChangeCookie(db, v, iDb); + sqlite3ChangeCookie(pParse, iDb); destroyRootPage(pParse, pIndex->tnum, iDb); - sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0); + sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0); } exit_drop_index: sqlite3SrcListDelete(pName); } @@ -50673,15 +52327,15 @@ v = sqlite3GetVdbe(pParse); if( !v ) return; if( type!=TK_DEFERRED ){ for(i=0; i<db->nDb; i++){ - sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); + sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1); sqlite3VdbeUsesBtree(v, i); } } - sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0); + sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0); } /* ** Commit a transaction */ @@ -50693,11 +52347,11 @@ if( pParse->nErr || db->mallocFailed ) return; if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return; v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0); + sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0); } } /* ** Rollback a transaction @@ -50710,11 +52364,11 @@ if( pParse->nErr || db->mallocFailed ) return; if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return; v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1); + sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1); } } /* ** Make sure the TEMP database is open and available for use. Return @@ -50737,19 +52391,11 @@ sqlite3ErrorMsg(pParse, "unable to open a temporary database " "file for storing temporary tables"); pParse->rc = rc; return 1; } - 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->flags & SQLITE_InTrans)==0 || db->autoCommit ); assert( db->aDb[1].pSchema ); } return 0; } @@ -50782,11 +52428,11 @@ v = sqlite3GetVdbe(pParse); if( v==0 ) return; /* This only happens if there was a prior error */ db = pParse->db; if( pParse->cookieGoto==0 ){ - pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1; + pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1; } if( iDb>=0 ){ assert( iDb<db->nDb ); assert( db->aDb[iDb].pBt!=0 || iDb==1 ); assert( iDb<SQLITE_MAX_ATTACHED+2 ); @@ -50823,11 +52469,11 @@ Vdbe *v = sqlite3GetVdbe(pParse); if( v==0 ) return; sqlite3CodeVerifySchema(pParse, iDb); pParse->writeMask |= 1<<iDb; if( setStatement && pParse->nested==0 ){ - sqlite3VdbeAddOp(v, OP_Statement, iDb, 0); + sqlite3VdbeAddOp1(v, OP_Statement, iDb); } if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){ sqlite3BeginWriteOperation(pParse, setStatement, 1); } } @@ -51390,11 +53036,11 @@ ** ************************************************************************* ** 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.131 2007/11/11 18:36:34 drh Exp $ +** $Id: delete.c,v 1.160 2008/01/25 15:04:50 drh Exp $ */ /* ** Look up every table that is named in pSrc. If any table is not found, ** add an error message to pParse->zErrMsg and return NULL. If all tables @@ -51403,11 +53049,11 @@ SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){ Table *pTab = 0; int i; struct SrcList_item *pItem; for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){ - pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase); + pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); sqlite3DeleteTable(pItem->pTab); pItem->pTab = pTab; if( pTab ){ pTab->nRef++; } @@ -51452,14 +53098,13 @@ Vdbe *v; if( IsVirtual(pTab) ) return; v = sqlite3GetVdbe(p); assert( opcode==OP_OpenWrite || opcode==OP_OpenRead ); sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite), 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); + sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb); + VdbeComment((v, "%s", pTab->zName)); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, iCur, pTab->nCol); } /* ** Generate code for a DELETE FROM statement. @@ -51490,10 +53135,15 @@ #ifndef SQLITE_OMIT_TRIGGER 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; if( pParse->nErr || db->mallocFailed ){ goto delete_from_cleanup; @@ -51547,10 +53197,13 @@ /* 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; @@ -51569,25 +53222,48 @@ goto delete_from_cleanup; } 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 ){ - Select *pView = sqlite3SelectDup(db, pTab->pSelect); - sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0); + SelectDest dest; + Select *pView; + + pView = sqlite3SelectDup(db, pTab->pSelect); + sqlite3SelectMask(pParse, pView, old_col_mask); + sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); + sqlite3Select(pParse, pView, &dest, 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++; - sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt); + memCnt = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt); } /* Special case: A DELETE without a WHERE clause deletes everything. ** It is easier just to erase the whole table. Note, however, that ** this means that the row change count will be incorrect. @@ -51594,157 +53270,147 @@ */ if( pWhere==0 && !triggers_exist && !IsVirtual(pTab) ){ if( db->flags & SQLITE_CountRows ){ /* If counting rows deleted, just count the total number of ** entries in the table. */ - int endOfLoop = sqlite3VdbeMakeLabel(v); int addr2; if( !isView ){ sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); } - sqlite3VdbeAddOp(v, OP_Rewind, iCur, sqlite3VdbeCurrentAddr(v)+2); - addr2 = sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt); - sqlite3VdbeAddOp(v, OP_Next, iCur, addr2); - sqlite3VdbeResolveLabel(v, endOfLoop); - sqlite3VdbeAddOp(v, OP_Close, iCur, 0); + 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); } if( !isView ){ - sqlite3VdbeAddOp(v, OP_Clear, pTab->tnum, iDb); + sqlite3VdbeAddOp2(v, OP_Clear, pTab->tnum, iDb); if( !pParse->nested ){ - sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC); + sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); } for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ assert( pIdx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp(v, OP_Clear, pIdx->tnum, iDb); + sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb); } } } /* The usual case: There is a WHERE clause so we have to scan through ** 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); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0); if( pWInfo==0 ) goto delete_from_cleanup; /* Remember the rowid of every item to be deleted. */ - sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0); - sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0); + sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, iRowid); + sqlite3VdbeAddOp1(v, OP_FifoWrite, iRowid); if( db->flags & SQLITE_CountRows ){ - sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt); + sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1); } /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); /* Open the pseudo-table used to store OLD if there are triggers. */ if( triggers_exist ){ - sqlite3VdbeAddOp(v, OP_OpenPseudo, oldIdx, 0); - sqlite3VdbeAddOp(v, OP_SetNumColumns, oldIdx, pTab->nCol); + sqlite3VdbeAddOp1(v, OP_OpenPseudo, oldIdx); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, oldIdx, pTab->nCol); } /* Delete every item whose key was written to the list during the ** database scan. We have to delete items after the scan is complete ** because deleting an item can change the scan order. */ end = sqlite3VdbeMakeLabel(v); - /* This is the beginning of the delete loop when there are - ** row triggers. - */ + 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. + */ + if( triggers_exist ){ + sqlite3VdbeResolveLabel(v, addr); + } + addr = sqlite3VdbeAddOp2(v, OP_FifoRead, iRowid, end); + if( triggers_exist ){ - int mem1 = pParse->nMem++; - addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, end); - sqlite3VdbeAddOp(v, OP_MemStore, mem1, 0); - if( !isView ){ - sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead); - } - sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0); - 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); - } - - (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); - } + 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); + } + sqlite3VdbeAddOp3(v, OP_Insert, oldIdx, iData, iRowid); + + /* Jump back and run the BEFORE triggers */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginBeforeTrigger); + sqlite3VdbeJumpHere(v, iEndBeforeTrigger); } 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); - } - /* Delete the row */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ + const char *pVtab = (const char *)pTab->pVtab; pParse->pVirtualLock = pTab; - sqlite3VdbeOp3(v, OP_VUpdate, 0, 1, (const char*)pTab->pVtab, P3_VTAB); + sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVtab, P4_VTAB); }else #endif { - sqlite3GenerateRowDelete(db, v, pTab, iCur, pParse->nested==0); + sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, pParse->nested==0); } } /* If there are row triggers, close all cursors then invoke ** the AFTER triggers */ if( triggers_exist ){ - 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); + /* Jump back and run the AFTER triggers */ + sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger); + sqlite3VdbeJumpHere(v, iEndAfterTrigger); } /* End of the delete loop */ - sqlite3VdbeAddOp(v, OP_Goto, 0, addr); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); sqlite3VdbeResolveLabel(v, end); /* Close the cursors after the loop if there are no row triggers */ - if( !triggers_exist && !IsVirtual(pTab) ){ + if( !isView && !IsVirtual(pTab) ){ 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); + sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum); + } + sqlite3VdbeAddOp1(v, OP_Close, iCur); } } /* ** Return the number of rows that were deleted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ - sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0); - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P3_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", P4_STATIC); } delete_from_cleanup: sqlite3AuthContextPop(&sContext); sqlite3SrcListDelete(pTabList); @@ -51763,30 +53429,33 @@ ** to be deleted, must be opened as cursor number "base". ** ** 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 on the top -** of the stack. +** 3. The record number of the row to be deleted must be stored in +** memory cell iRowid. ** ** 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( - sqlite3 *db, /* The database containing the index */ - Vdbe *v, /* Generate code into this VDBE */ + Parse *pParse, /* Parsing context */ 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; - addr = sqlite3VdbeAddOp(v, OP_NotExists, iCur, 0); - sqlite3GenerateRowIndexDelete(v, pTab, iCur, 0); - sqlite3VdbeAddOp(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0)); + 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)); if( count ){ - sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC); + sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); } sqlite3VdbeJumpHere(v, addr); } /* @@ -51804,51 +53473,67 @@ ** ** 3. The "iCur" cursor must be pointing to the row that is to be ** deleted. */ SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete( - Vdbe *v, /* Generate code into this VDBE */ + Parse *pParse, /* Parsing and code generating context */ Table *pTab, /* Table containing the row to be deleted */ int iCur, /* Cursor number for the table */ - char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */ + int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */ ){ int i; Index *pIdx; - + int r1; + + r1 = sqlite3GetTempReg(pParse); for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){ - if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue; - sqlite3GenerateIndexKey(v, pIdx, iCur); - sqlite3VdbeAddOp(v, OP_IdxDelete, iCur+i, 0); - } + if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue; + sqlite3GenerateIndexKey(pParse, pIdx, iCur, r1); + sqlite3VdbeAddOp2(pParse->pVdbe, OP_IdxDelete, iCur+i, r1); + } + sqlite3ReleaseTempReg(pParse, r1); } /* ** 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. -*/ -SQLITE_PRIVATE void sqlite3GenerateIndexKey( - Vdbe *v, /* Generate code into this VDBE */ +** +** 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 */ Index *pIdx, /* The index for which to generate a key */ - int iCur /* Cursor number for the pIdx->pTable table */ -){ + int iCur, /* Cursor number for the pIdx->pTable table */ + int regOut /* Write the new index key to this register */ +){ + Vdbe *v = pParse->pVdbe; int j; Table *pTab = pIdx->pTable; - - sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); - for(j=0; j<pIdx->nColumn; j++){ + int regBase; + int nCol; + + nCol = pIdx->nColumn; + regBase = sqlite3GetTempRange(pParse, nCol+1); + sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol); + for(j=0; j<nCol; j++){ int idx = pIdx->aiColumn[j]; if( idx==pTab->iPKey ){ - sqlite3VdbeAddOp(v, OP_Dup, j, 0); - }else{ - sqlite3VdbeAddOp(v, OP_Column, iCur, idx); + sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j); + }else{ + sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j); sqlite3ColumnDefault(v, pTab, idx); } } - sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut); sqlite3IndexAffinityStr(v, pIdx); + sqlite3ReleaseTempRange(pParse, regBase, nCol+1); + return regBase; } /************** End of delete.c **********************************************/ /************** Begin file func.c ********************************************/ /* @@ -51867,11 +53552,11 @@ ** ** There is only one exported symbol in this file - the function ** sqliteRegisterBuildinFunctions() found at the bottom of the file. ** All other code has file scope. ** -** $Id: func.c,v 1.176 2007/11/01 17:38:31 drh Exp $ +** $Id: func.c,v 1.183 2008/01/21 16:22:46 drh Exp $ */ /* ** Return the collating function associated with a function. @@ -52251,10 +53936,23 @@ u8 matchOne; u8 matchSet; u8 noCase; }; +/* +** For LIKE and GLOB matching on EBCDIC machines, assume that every +** character is exactly one byte in size. Also, all characters are +** able to participate in upper-case-to-lower-case mappings in EBCDIC +** whereas only characters less than 0x80 do in ASCII. +*/ +#if defined(SQLITE_EBCDIC) +# define sqlite3Utf8Read(A,B,C) (*(A++)) +# define GlogUpperToLower(A) A = sqlite3UpperToLower[A] +#else +# define GlogUpperToLower(A) if( A<0x80 ){ A = sqlite3UpperToLower[A]; } +#endif + static const struct compareInfo globInfo = { '*', '?', '[', 0 }; /* The correct SQL-92 behavior is for the LIKE operator to ignore ** case. Thus 'a' LIKE 'A' would be true. */ static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 }; /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator @@ -52327,15 +54025,15 @@ } return *zString!=0; } while( (c2 = sqlite3Utf8Read(zString,0,&zString))!=0 ){ if( noCase ){ - c2 = c2<0x80 ? sqlite3UpperToLower[c2] : c2; - c = c<0x80 ? sqlite3UpperToLower[c] : c; + GlogUpperToLower(c2); + GlogUpperToLower(c); while( c2 != 0 && c2 != c ){ c2 = sqlite3Utf8Read(zString, 0, &zString); - if( c2<0x80 ) c2 = sqlite3UpperToLower[c2]; + GlogUpperToLower(c2); } }else{ while( c2 != 0 && c2 != c ){ c2 = sqlite3Utf8Read(zString, 0, &zString); } @@ -52383,12 +54081,12 @@ }else if( esc==c && !prevEscape ){ prevEscape = 1; }else{ c2 = sqlite3Utf8Read(zString, 0, &zString); if( noCase ){ - c = c<0x80 ? sqlite3UpperToLower[c] : c; - c2 = c2<0x80 ? sqlite3UpperToLower[c2] : c2; + GlogUpperToLower(c); + GlogUpperToLower(c2); } if( c!=c2 ){ return 0; } prevEscape = 0; @@ -52711,11 +54409,11 @@ const unsigned char *zCharSet; /* Set of characters to trim */ int nIn; /* Number of bytes in input */ int flags; /* 1: trimleft 2: trimright 3: trim */ int i; /* Loop counter */ unsigned char *aLen; /* Length of each character in zCharSet */ - const unsigned char **azChar; /* Individual characters in zCharSet */ + unsigned char **azChar; /* Individual characters in zCharSet */ int nChar; /* Number of characters in zCharSet */ if( sqlite3_value_type(argv[0])==SQLITE_NULL ){ return; } @@ -52726,11 +54424,11 @@ if( argc==1 ){ static const unsigned char lenOne[] = { 1 }; static const unsigned char *azOne[] = { (u8*)" " }; nChar = 1; aLen = (u8*)lenOne; - azChar = azOne; + azChar = (unsigned char **)azOne; zCharSet = 0; }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){ return; }else{ const unsigned char *z; @@ -52742,11 +54440,11 @@ if( azChar==0 ){ return; } aLen = (unsigned char*)&azChar[nChar]; for(z=zCharSet, nChar=0; *z; nChar++){ - azChar[nChar] = z; + azChar[nChar] = (unsigned char *)z; SQLITE_SKIP_UTF8(z); aLen[nChar] = z - azChar[nChar]; } } } @@ -52982,14 +54680,11 @@ char const *z = (char*)sqlite3_value_text(argv[i]); if( z ){ char *zAux = sqlite3_get_auxdata(pCtx, i); if( zAux ){ zRet[i*2] = '1'; - if( strcmp(zAux, z) ){ - sqlite3_result_error(pCtx, "Auxilary data corruption", -1); - return; - } + assert( strcmp(zAux,z)==0 ); }else { zRet[i*2] = '0'; } zAux = contextMalloc(pCtx, strlen(z)+1); @@ -53005,11 +54700,11 @@ #endif /* SQLITE_TEST */ #ifdef SQLITE_TEST /* ** A function to test error reporting from user functions. This function -** returns a copy of it's first argument as an error. +** returns a copy of its first argument as an error. */ static void test_error( sqlite3_context *pCtx, int nArg, sqlite3_value **argv @@ -53158,46 +54853,56 @@ } sqlite3VdbeMemRelease(pRes); } } -#ifdef SQLITE_GROUP_CONCAT /* ** group_concat(EXPR, ?SEPARATOR?) */ static void groupConcatStep( sqlite3_context *context, int argc, sqlite3_value **argv ){ const char *zVal; - char **pzAccumulator; + StrAccum *pAccum; const char *zSep; + int nVal, nSep; if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return; - zVal = sqlite3_value_text(argv[0]); - pzAccumulator = (char**)sqlite3_aggregate_context(context, sizeof(char*)); - if( pzAccumulator ){ - if( *pzAccumulator==0 ){ - *pzAccumulator = sqlite3_mprintf("%s", zVal); - }else{ + pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum)); + + if( pAccum ){ + pAccum->useMalloc = 1; + if( pAccum->nChar ){ if( argc==2 ){ - zSep = sqlite3_value_text(argv[1]); + zSep = (char*)sqlite3_value_text(argv[1]); + nSep = sqlite3_value_bytes(argv[1]); }else{ zSep = ","; - } - *pzAccumulator = sqlite3_mprintf("%z%s%s", *pzAccumulator, zSep, zVal); - } + nSep = 1; + } + sqlite3StrAccumAppend(pAccum, zSep, nSep); + } + zVal = (char*)sqlite3_value_text(argv[0]); + nVal = sqlite3_value_bytes(argv[0]); + sqlite3StrAccumAppend(pAccum, zVal, nVal); } } static void groupConcatFinalize(sqlite3_context *context){ - char **pzAccum; - pzAccum = sqlite3_aggregate_context(context, 0); - if( pzAccum ){ - sqlite3_result_text(context, *pzAccum, -1, sqlite3_free); - } -} -#endif /*SQLITE_GROUP_CONCAT*/ + StrAccum *pAccum; + pAccum = sqlite3_aggregate_context(context, 0); + if( pAccum ){ + if( pAccum->tooBig ){ + sqlite3_result_error_toobig(context); + }else if( pAccum->mallocFailed ){ + sqlite3_result_error_nomem(context); + }else{ + sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, + sqlite3_free); + } + } +} /* ** This function registered all of the above C functions as SQL ** functions. This should be the only routine in this file with ** external linkage. @@ -53273,14 +54978,12 @@ { "sum", 1, 0, 0, sumStep, sumFinalize }, { "total", 1, 0, 0, sumStep, totalFinalize }, { "avg", 1, 0, 0, sumStep, avgFinalize }, { "count", 0, 0, 0, countStep, countFinalize }, { "count", 1, 0, 0, countStep, countFinalize }, -#ifdef SQLITE_GROUP_CONCAT { "group_concat", 1, 0, 0, groupConcatStep, groupConcatFinalize }, { "group_concat", 2, 0, 0, groupConcatStep, groupConcatFinalize }, -#endif }; int i; for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){ void *pArg; @@ -53415,15 +55118,15 @@ ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle INSERT statements in SQLite. ** -** $Id: insert.c,v 1.193 2007/11/23 15:02:19 drh Exp $ -*/ - -/* -** Set P3 of the most recently inserted opcode to a column affinity +** $Id: insert.c,v 1.228 2008/01/25 15:04:50 drh Exp $ +*/ + +/* +** Set P4 of the most recently inserted opcode to a column affinity ** string for index pIdx. A column affinity string has one character ** for each column in the table, according to the affinity of the column: ** ** Character Column affinity ** ------------------------------ @@ -53430,10 +55133,13 @@ ** 'a' TEXT ** 'b' NONE ** 'c' NUMERIC ** 'd' INTEGER ** 'e' REAL +** +** An extra 'b' is appended to the end of the string to cover the +** rowid that appears as the last column in every index. */ SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){ if( !pIdx->zColAff ){ /* The first time a column affinity string for a particular index is ** required, it is allocated and populated here. It is then stored as @@ -53444,25 +55150,26 @@ ** up. */ int n; Table *pTab = pIdx->pTable; sqlite3 *db = sqlite3VdbeDb(v); - pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+1); + pIdx->zColAff = (char *)sqlite3DbMallocZero(db, pIdx->nColumn+2); if( !pIdx->zColAff ){ return; } for(n=0; n<pIdx->nColumn; n++){ pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity; } - pIdx->zColAff[pIdx->nColumn] = '\0'; - } - - sqlite3VdbeChangeP3(v, -1, pIdx->zColAff, 0); -} - -/* -** Set P3 of the most recently inserted opcode to a column affinity + pIdx->zColAff[n++] = SQLITE_AFF_NONE; + pIdx->zColAff[n] = 0; + } + + sqlite3VdbeChangeP4(v, -1, pIdx->zColAff, 0); +} + +/* +** Set P4 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: ** ** Character Column affinity @@ -53497,11 +55204,11 @@ zColAff[pTab->nCol] = '\0'; pTab->zColAff = zColAff; } - sqlite3VdbeChangeP3(v, -1, pTab->zColAff, 0); + sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0); } /* ** Return non-zero if the table pTab in database iDb or any of its indices ** have been opened at any point in the VDBE program beginning at location @@ -53512,79 +55219,80 @@ static int readsTable(Vdbe *v, int iStartAddr, int iDb, Table *pTab){ int i; int iEnd = sqlite3VdbeCurrentAddr(v); for(i=iStartAddr; i<iEnd; i++){ VdbeOp *pOp = sqlite3VdbeGetOp(v, i); - if( pOp->opcode==OP_OpenRead ){ - VdbeOp *pPrior = &pOp[-1]; + assert( pOp!=0 ); + if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){ + Index *pIndex; int tnum = pOp->p2; - assert( i>iStartAddr ); - assert( pPrior->opcode==OP_Integer ); - if( pPrior->p1==iDb ){ - Index *pIndex; - if( tnum==pTab->tnum ){ + if( tnum==pTab->tnum ){ + return 1; + } + for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ + if( tnum==pIndex->tnum ){ return 1; } - for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){ - if( tnum==pIndex->tnum ){ - return 1; - } - } - } - } - if( pOp->opcode==OP_VOpen && pOp->p3==(const char*)pTab->pVtab ){ - assert( pOp->p3!=0 ); - assert( pOp->p3type==P3_VTAB ); - 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 ); + return 1; + } +#endif } return 0; } #ifndef SQLITE_OMIT_AUTOINCREMENT /* ** 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 memory cell. Code generated by -** autoIncStep() will keep that memory cell holding the largest +** table and stores that value in a register. Code generated by +** autoIncStep() will keep that register 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. ** -** 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. +** 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. */ 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; + int memId = 0; /* Register holding maximum rowid */ if( pTab->autoInc ){ Vdbe *v = pParse->pVdbe; Db *pDb = &pParse->db->aDb[iDb]; int iCur = pParse->nTab; - int addr; + int addr; /* Address of the top of the loop */ assert( v ); - addr = sqlite3VdbeCurrentAddr(v); - memId = pParse->nMem+1; - pParse->nMem += 2; + pParse->nMem++; /* Holds name of table */ + memId = ++pParse->nMem; + pParse->nMem++; 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); + addr = sqlite3VdbeCurrentAddr(v); + sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, pTab->zName, 0); + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, addr+8); + 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+8); + sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+2); + sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); } return memId; } /* @@ -53593,19 +55301,19 @@ ** This routine should be called when the top of the stack holds a ** new rowid that is about to be inserted. If that new rowid is ** 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){ +static void autoIncStep(Parse *pParse, int memId, int regRowid){ if( memId>0 ){ - sqlite3VdbeAddOp(pParse->pVdbe, OP_MemMax, memId, 0); + sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid); } } /* ** After doing one or more inserts, the maximum rowid is stored -** in mem[memId]. Generate code to write this value back into the +** in reg[memId]. Generate code to write this value back into the ** the sqlite_sequence table. */ static void autoIncEnd( Parse *pParse, /* The parsing context */ int iDb, /* Index of the database holding pTab */ @@ -53614,32 +55322,30 @@ ){ if( pTab->autoInc ){ int iCur = pParse->nTab; Vdbe *v = pParse->pVdbe; Db *pDb = &pParse->db->aDb[iDb]; - int addr; - assert( v ); - addr = sqlite3VdbeCurrentAddr(v); + int j1; + + assert( v ); sqlite3OpenTable(pParse, iCur, iDb, pDb->pSchema->pSeqTab, OP_OpenWrite); - 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); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); + sqlite3VdbeAddOp2(v, OP_NewRowid, iCur, memId+1); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, memId-1); + sqlite3VdbeAddOp3(v, OP_Insert, iCur, memId-1, memId+1); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); + sqlite3VdbeAddOp1(v, OP_Close, iCur); } } #else /* ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines ** above are all no-ops */ # define autoIncBegin(A,B,C) (0) -# define autoIncStep(A,B) +# define autoIncStep(A,B,C) # define autoIncEnd(A,B,C,D) #endif /* SQLITE_OMIT_AUTOINCREMENT */ /* Forward declaration */ @@ -53745,35 +55451,43 @@ ExprList *pList, /* List of values to be inserted */ Select *pSelect, /* A SELECT statement to use as the data source */ IdList *pColumn, /* Column names corresponding to IDLIST. */ int onError /* How to handle constraint errors */ ){ - Table *pTab; /* The table to insert into */ + sqlite3 *db; /* The main database structure */ + Table *pTab; /* The table to insert into. aka TABLE */ 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 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 nHidden = 0; /* Number of hidden columns if TABLE is virtual */ + int baseCur = 0; /* VDBE Cursor number for pTab */ 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 iCont=0,iBreak=0; /* Beginning and end of the loop over srcTab */ 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 newIdx = -1; /* Cursor for the NEW pseudo-table */ + int iDb; /* Index of database holding TABLE */ + Db *pDb; /* The database containing table being inserted into */ int appendFlag = 0; /* True if the insert is likely to be an append */ - int iDb; - - int nHidden = 0; + + /* 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 *aRegIdx = 0; /* One register allocated to each index */ + #ifndef SQLITE_OMIT_TRIGGER int isView; /* True if attempting to insert into a view */ int triggers_exist = 0; /* True if there are FOR EACH ROW triggers */ #endif @@ -53858,15 +55572,13 @@ goto insert_cleanup; } #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 counterMem. Also - ** remember the rowid of the sqlite_sequence table entry in memory cell - ** counterRowid. - */ - counterMem = autoIncBegin(pParse, iDb, pTab); + ** sqlite_sequence table and store it in memory cell regAutoinc. + */ + regAutoinc = autoIncBegin(pParse, iDb, pTab); /* Figure out how many columns of data are supplied. If the data ** 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 @@ -53875,23 +55587,27 @@ ** results in a temporary table. (Template 3.) */ if( pSelect ){ /* Data is coming from a SELECT. Generate code to implement that SELECT */ + SelectDest dest; int rc, iInitCode; - iInitCode = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); + + iInitCode = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); iSelectLoop = sqlite3VdbeCurrentAddr(v); iInsertBlock = sqlite3VdbeMakeLabel(v); + sqlite3SelectDestInit(&dest, SRT_Subroutine, iInsertBlock); /* Resolve the expressions in the SELECT statement and execute it. */ - rc = sqlite3Select(pParse, pSelect, SRT_Subroutine, iInsertBlock,0,0,0,0); + rc = sqlite3Select(pParse, pSelect, &dest, 0, 0, 0, 0); if( rc || pParse->nErr || db->mallocFailed ){ goto insert_cleanup; } + regFromSelect = dest.iMem; iCleanup = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp(v, OP_Goto, 0, iCleanup); + sqlite3VdbeAddOp2(v, OP_Goto, 0, iCleanup); assert( pSelect->pEList ); nColumn = pSelect->pEList->nExpr; /* Set useTempTable to TRUE if the result of the SELECT statement ** should be written into a temporary table. Set to FALSE if each @@ -53907,26 +55623,31 @@ if( useTempTable ){ /* Generate the subroutine that SELECT calls to process each row of ** the result. Store the result in a temporary table */ + int regRec, regRowid; + srcTab = pParse->nTab++; + regRec = sqlite3GetTempReg(pParse); + regRowid = sqlite3GetTempReg(pParse); sqlite3VdbeResolveLabel(v, iInsertBlock); - 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); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec); + sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regRowid); + sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regRowid); + sqlite3VdbeAddOp2(v, OP_Return, 0, 0); + sqlite3ReleaseTempReg(pParse, regRec); + sqlite3ReleaseTempReg(pParse, regRowid); /* 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); + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, 0); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, srcTab, nColumn); + sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop); sqlite3VdbeResolveLabel(v, iCleanup); }else{ sqlite3VdbeJumpHere(v, iInitCode); } }else{ @@ -54012,170 +55733,197 @@ } /* Open the temp table for FOR EACH ROW triggers */ if( triggers_exist ){ - sqlite3VdbeAddOp(v, OP_OpenPseudo, newIdx, 0); - sqlite3VdbeAddOp(v, OP_SetNumColumns, newIdx, pTab->nCol); + sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol); } /* Initialize the count of rows to be inserted */ if( db->flags & SQLITE_CountRows ){ - iCntMem = pParse->nMem++; - sqlite3VdbeAddOp(v, OP_MemInt, 0, iCntMem); - } - - /* Open tables and indices if there are no row triggers */ - if( !triggers_exist ){ - base = pParse->nTab; - sqlite3OpenTableAndIndices(pParse, pTab, base, OP_OpenWrite); + regRowCount = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); + } + + /* 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 = sqlite3DbMallocZero(db, sizeof(int)*(nIdx+1)); + if( aRegIdx==0 ){ + goto insert_cleanup; + } + for(i=0; i<nIdx; i++){ + aRegIdx[i] = ++pParse->nMem; + } } /* 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. */ if( useTempTable ){ iBreak = sqlite3VdbeMakeLabel(v); - sqlite3VdbeAddOp(v, OP_Rewind, srcTab, iBreak); + sqlite3VdbeAddOp2(v, OP_Rewind, srcTab, iBreak); iCont = sqlite3VdbeCurrentAddr(v); }else if( pSelect ){ - sqlite3VdbeAddOp(v, OP_Goto, 0, iSelectLoop); + sqlite3VdbeAddOp2(v, OP_Goto, 0, iSelectLoop); sqlite3VdbeResolveLabel(v, iInsertBlock); } + + /* Allocate registers for holding the rowid of the new row, + ** the content of the new row, and the assemblied row record. + */ + regRecord = ++pParse->nMem; + regRowid = regIns = pParse->nMem+1; + pParse->nMem += pTab->nCol + 1; + if( IsVirtual(pTab) ){ + regRowid++; + pParse->nMem++; + } + 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 ** translated into a unique ID for the row. But on a BEFORE trigger, ** 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 ){ - sqlite3VdbeAddOp(v, OP_Integer, -1, 0); + sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid); }else if( useTempTable ){ - sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); - }else{ + sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); + }else{ + int j1; assert( pSelect==0 ); /* Otherwise useTempTable is true */ - 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); + 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); } /* Cannot have triggers on a virtual table. If it were possible, ** this block would have to account for hidden column. */ assert(!IsVirtual(pTab)); /* Create the new column data */ + regCols = sqlite3GetTempRange(pParse, pTab->nCol); for(i=0; i<pTab->nCol; i++){ if( pColumn==0 ){ j = i; }else{ for(j=0; j<pColumn->nId; j++){ if( pColumn->a[j].idx==i ) break; } } if( pColumn && j>=pColumn->nId ){ - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i); }else if( useTempTable ){ - sqlite3VdbeAddOp(v, OP_Column, srcTab, j); + sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i); }else{ assert( pSelect==0 ); /* Otherwise useTempTable is true */ - sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr); - } - } - sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); + sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i); + } + } + regRec = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regCols, pTab->nCol, regRec); /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger, ** do not attempt any conversions before assembling the record. ** If this is a real table, attempt conversions as required by the ** table column affinities. */ if( !isView ){ sqlite3TableAffinityStr(v, pTab); } - sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); + sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); + sqlite3ReleaseTempReg(pParse, regRec); + sqlite3ReleaseTempReg(pParse, regRowid); + sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol); /* Fire BEFORE or INSTEAD OF triggers */ if( sqlite3CodeRowTrigger(pParse, TK_INSERT, 0, TRIGGER_BEFORE, pTab, - newIdx, -1, onError, endOfLoop) ){ + newIdx, -1, onError, endOfLoop, 0, 0) ){ 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 ** case the record number is the same as that column. */ if( !isView ){ if( IsVirtual(pTab) ){ - /* The row that the VUpdate opcode will delete: none */ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); + /* The row that the VUpdate opcode will delete: none */ + sqlite3VdbeAddOp2(v, OP_Null, 0, regIns); } if( keyColumn>=0 ){ if( useTempTable ){ - sqlite3VdbeAddOp(v, OP_Column, srcTab, keyColumn); + sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid); }else if( pSelect ){ - sqlite3VdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1); + sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid); }else{ VdbeOp *pOp; - sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr); + sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid); pOp = sqlite3VdbeGetOp(v, sqlite3VdbeCurrentAddr(v) - 1); if( pOp && pOp->opcode==OP_Null ){ appendFlag = 1; pOp->opcode = OP_NewRowid; - pOp->p1 = base; - pOp->p2 = counterMem; + pOp->p1 = baseCur; + pOp->p2 = regRowid; + pOp->p3 = regAutoinc; } } /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid ** to generate a unique primary key value. */ if( !appendFlag ){ - 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); + int j1; + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); + sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); + sqlite3VdbeJumpHere(v, j1); + sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); } }else if( IsVirtual(pTab) ){ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); - }else{ - sqlite3VdbeAddOp(v, OP_NewRowid, base, counterMem); + sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid); + }else{ + sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc); appendFlag = 1; } - autoIncStep(pParse, counterMem); + autoIncStep(pParse, regAutoinc, regRowid); /* Push onto the stack, data for all columns of the new entry, beginning ** with the first column. */ nHidden = 0; for(i=0; i<pTab->nCol; 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. */ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore); continue; } if( pColumn==0 ){ if( IsHiddenColumn(&pTab->aCol[i]) ){ assert( IsVirtual(pTab) ); @@ -54188,134 +55936,146 @@ for(j=0; j<pColumn->nId; j++){ if( pColumn->a[j].idx==i ) break; } } if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){ - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore); }else if( useTempTable ){ - sqlite3VdbeAddOp(v, OP_Column, srcTab, j); + sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); }else if( pSelect ){ - sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1); - }else{ - sqlite3ExprCode(pParse, pList->a[j].pExpr); + sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore); + }else{ + sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore); } } /* Generate code to check constraints and generate index keys and ** do the insertion. */ #ifndef SQLITE_OMIT_VIRTUALTABLE if( IsVirtual(pTab) ){ pParse->pVirtualLock = pTab; - sqlite3VdbeOp3(v, OP_VUpdate, 1, pTab->nCol+2, - (const char*)pTab->pVtab, P3_VTAB); + sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, + (const char*)pTab->pVtab, P4_VTAB); }else #endif { - 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); + 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 + ); } } /* Update the count of rows that are inserted */ if( (db->flags & SQLITE_CountRows)!=0 ){ - sqlite3VdbeAddOp(v, OP_MemIncr, 1, iCntMem); + sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } 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) ){ + newIdx, -1, onError, endOfLoop, 0, 0) ){ goto insert_cleanup; } } /* The bottom of the loop, if the data source is a SELECT statement */ sqlite3VdbeResolveLabel(v, endOfLoop); if( useTempTable ){ - sqlite3VdbeAddOp(v, OP_Next, srcTab, iCont); + sqlite3VdbeAddOp2(v, OP_Next, srcTab, iCont); sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp(v, OP_Close, srcTab, 0); + sqlite3VdbeAddOp2(v, OP_Close, srcTab, 0); }else if( pSelect ){ - sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); - sqlite3VdbeAddOp(v, OP_Return, 0, 0); + sqlite3VdbeAddOp2(v, OP_Return, 0, 0); sqlite3VdbeResolveLabel(v, iCleanup); } - if( !triggers_exist && !IsVirtual(pTab) ){ + if( !IsVirtual(pTab) && !isView ){ /* Close all tables opened */ - sqlite3VdbeAddOp(v, OP_Close, base, 0); + sqlite3VdbeAddOp2(v, OP_Close, baseCur, 0); for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){ - sqlite3VdbeAddOp(v, OP_Close, idx+base, 0); + sqlite3VdbeAddOp2(v, OP_Close, idx+baseCur, 0); } } /* Update the sqlite_sequence table by storing the content of the - ** counter value in memory counterMem back into the sqlite_sequence + ** counter value in memory regAutoinc back into the sqlite_sequence ** table. */ - autoIncEnd(pParse, iDb, pTab, counterMem); + autoIncEnd(pParse, iDb, pTab, regAutoinc); /* ** Return the number of rows inserted. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( db->flags & SQLITE_CountRows && pParse->nested==0 && !pParse->trigStack ){ - sqlite3VdbeAddOp(v, OP_MemLoad, iCntMem, 0); - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P3_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", P4_STATIC); } insert_cleanup: sqlite3SrcListDelete(pTabList); sqlite3ExprListDelete(pList); sqlite3SelectDelete(pSelect); sqlite3IdListDelete(pColumn); -} - -/* -** Generate code to do a constraint check prior to an INSERT or an UPDATE. -** -** When this routine is called, the stack contains (from bottom to top) -** the following values: + sqlite3_free(aRegIdx); +} + +/* +** Generate code to do constraint checks prior to an INSERT or an UPDATE. +** +** The input is a range of consecutive registers as follows: ** ** 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. +** change to the record number or writing to a virtual table. ** ** 2. The rowid of the row after the update. ** ** 3. The data in the first column of the entry after the update. ** ** i. Data from middle columns... ** ** 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 and rowidChng is true if the record number is being changed. -** -** 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. +** 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. +** +** 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. ** ** This routine also generates code to check constraints. NOT NULL, ** CHECK, and UNIQUE constraints are all checked. If a constraint fails, ** then the appropriate action is performed. There are five possible ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE. @@ -54353,47 +56113,43 @@ ** Or if overrideError==OE_Default, then the pParse->onError parameter ** is used. Or if pParse->onError==OE_Default then the onError value ** for the constraint is used. ** ** The calling routine must open a read/write cursor for pTab with -** cursor number "base". All indices of pTab must also have open -** read/write cursors with cursor number base+i for the i-th cursor. +** cursor number "baseCur". All indices of pTab must also have open +** read/write cursors with cursor number baseCur+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 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. +** cursors do not need to be open for indices where aRegIdx[i]==0. */ SQLITE_PRIVATE void sqlite3GenerateConstraintChecks( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ - 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 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 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 */ ){ int i; Vdbe *v; int nCol; int onError; - int addr; - int extra; + int j1, j2, j3; /* Addresses of jump instructions */ + int regData; /* Register containing first data column */ 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. */ for(i=0; i<nCol; i++){ if( i==pTab->iPKey ){ @@ -54407,55 +56163,48 @@ onError = OE_Abort; } if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){ onError = OE_Abort; } - sqlite3VdbeAddOp(v, OP_Dup, nCol-1-i, 1); - addr = sqlite3VdbeAddOp(v, OP_NotNull, 1, 0); + j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i); 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 = 0; - sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError); + sqlite3VdbeAddOp2(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); + sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC); break; } case OE_Ignore: { - sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); - sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); break; } case OE_Replace: { - sqlite3ExprCode(pParse, pTab->aCol[i].pDflt); - sqlite3VdbeAddOp(v, OP_Push, nCol-i, 0); - break; - } - } - sqlite3VdbeJumpHere(v, addr); + sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i); + break; + } + } + sqlite3VdbeJumpHere(v, j1); } /* Test all CHECK constraints */ #ifndef SQLITE_OMIT_CHECK if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){ int allOk = sqlite3VdbeMakeLabel(v); - assert( pParse->ckOffset==0 ); - pParse->ckOffset = nCol; - sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, 1); - assert( pParse->ckOffset==nCol ); - pParse->ckOffset = 0; + pParse->ckBase = regData; + sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL); onError = overrideError!=OE_Default ? overrideError : OE_Abort; if( onError==OE_Ignore ){ - sqlite3VdbeAddOp(v, OP_Pop, nCol+1+hasTwoRowids, 0); - sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); - }else{ - sqlite3VdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); + }else{ + sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_CONSTRAINT, onError); } sqlite3VdbeResolveLabel(v, allOk); } #endif /* !defined(SQLITE_OMIT_CHECK) */ @@ -54469,74 +56218,69 @@ onError = overrideError; }else if( onError==OE_Default ){ onError = OE_Abort; } - 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 */ - } - case OE_Rollback: - case OE_Abort: - case OE_Fail: { - sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, - "PRIMARY KEY must be unique", P3_STATIC); - break; - } - 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); + if( onError!=OE_Replace || pTab->pIndex ){ + if( isUpdate ){ + j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, regRowid-1); + } + 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; + } + } + sqlite3VdbeJumpHere(v, j3); + if( isUpdate ){ + sqlite3VdbeJumpHere(v, j2); + } } } /* Test all UNIQUE constraints by creating entries for each UNIQUE ** 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++){ - if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */ - extra++; + int regIdx; + int regR; + + if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */ /* Create a key for accessing the index entry */ - sqlite3VdbeAddOp(v, OP_Dup, nCol+extra, 1); + regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1); for(i=0; i<pIdx->nColumn; i++){ int idx = pIdx->aiColumn[i]; if( idx==pTab->iPKey ){ - sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1); - }else{ - sqlite3VdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1); - } - } - jumpInst1 = sqlite3VdbeAddOp(v, OP_MakeIdxRec, pIdx->nColumn, 0); + sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + }else{ + sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i); + } + } + sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]); sqlite3IndexAffinityStr(v, pIdx); + sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1); /* Find out what action to take in case there is an indexing conflict */ onError = pIdx->onError; if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */ if( overrideError!=OE_Default ){ @@ -54549,12 +56293,15 @@ else if( onError==OE_Fail ) onError = OE_Abort; } /* Check to see if the new index entry will be unique */ - sqlite3VdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRowids, 1); - jumpInst2 = sqlite3VdbeAddOp(v, OP_IsUnique, base+iCur+1, 0); + 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, (char*)aRegIdx[iCur], P4_INT32); /* Generate code that executes if the new index entry is not unique */ assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail || onError==OE_Ignore || onError==OE_Replace ); switch( onError ){ @@ -54582,51 +56329,45 @@ n1 += n2; } } sqlite3_snprintf(sizeof(zErrMsg)-n1, &zErrMsg[n1], pIdx->nColumn>1 ? " are not unique" : " is not unique"); - sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0); + sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, zErrMsg,0); break; } case OE_Ignore: { assert( seenReplace==0 ); - sqlite3VdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRowids, 0); - sqlite3VdbeAddOp(v, OP_Goto, 0, ignoreDest); + sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest); break; } case OE_Replace: { - sqlite3GenerateRowDelete(pParse->db, v, pTab, base, 0); - if( isUpdate ){ - sqlite3VdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRowids, 1); - sqlite3VdbeAddOp(v, OP_MoveGe, base, 0); - } + sqlite3GenerateRowDelete(pParse, pTab, baseCur, regR, 0); seenReplace = 1; break; } } -#if NULL_DISTINCT_FOR_UNIQUE - sqlite3VdbeJumpHere(v, jumpInst1); -#endif - sqlite3VdbeJumpHere(v, jumpInst2); + sqlite3VdbeJumpHere(v, j2); + sqlite3VdbeJumpHere(v, j3); + sqlite3ReleaseTempReg(pParse, regR); } } /* ** This routine generates code to finish the INSERT or UPDATE operation ** that was started by a prior call to sqlite3GenerateConstraintChecks. -** 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. +** A consecutive range of registers starting at regRowid contains the +** rowid and the content to be inserted. ** ** The arguments to this routine should be the same as the first six ** arguments to sqlite3GenerateConstraintChecks. */ SQLITE_PRIVATE void sqlite3CompleteInsertion( Parse *pParse, /* The parser context */ Table *pTab, /* the table into which we are inserting */ - int base, /* Index of a read/write cursor pointing at pTab */ - char *aIdxUsed, /* Which indices are used. NULL means all are used */ + 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 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 */ int appendBias /* True if this is likely to be an append */ ){ @@ -54633,26 +56374,28 @@ int i; Vdbe *v; 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( aIdxUsed && aIdxUsed[i]==0 ) continue; - sqlite3VdbeAddOp(v, OP_IdxInsert, base+i+1, 0); - } - sqlite3VdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0); + if( aRegIdx[i]==0 ) continue; + sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]); + } + regData = regRowid + 1; + regRec = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec); sqlite3TableAffinityStr(v, pTab); #ifndef SQLITE_OMIT_TRIGGER if( newIdx>=0 ){ - sqlite3VdbeAddOp(v, OP_Dup, 1, 0); - sqlite3VdbeAddOp(v, OP_Dup, 1, 0); - sqlite3VdbeAddOp(v, OP_Insert, newIdx, 0); + sqlite3VdbeAddOp3(v, OP_Insert, newIdx, regRec, regRowid); } #endif if( pParse->nested ){ pik_flags = 0; }else{ @@ -54660,51 +56403,51 @@ pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID); } if( appendBias ){ pik_flags |= OPFLAG_APPEND; } - sqlite3VdbeAddOp(v, OP_Insert, base, pik_flags); + sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid); if( !pParse->nested ){ - sqlite3VdbeChangeP3(v, -1, pTab->zName, P3_STATIC); - } - - if( isUpdate && rowidChng ){ - sqlite3VdbeAddOp(v, OP_Pop, 1, 0); - } + sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC); + } + sqlite3VdbeChangeP5(v, pik_flags); } /* ** Generate code that will open cursors for a table and for all -** indices of that table. The "base" parameter is the cursor number used +** indices of that table. The "baseCur" parameter is the cursor number used ** for the table. Indices are opened on subsequent cursors. -*/ -SQLITE_PRIVATE void sqlite3OpenTableAndIndices( +** +** Return the number of indices on the table. +*/ +SQLITE_PRIVATE int sqlite3OpenTableAndIndices( Parse *pParse, /* Parsing context */ Table *pTab, /* Table to be opened */ - int base, /* Cursor number assigned to the table */ + int baseCur, /* Cursor number assigned to the table */ int op /* OP_OpenRead or OP_OpenWrite */ ){ int i; int iDb; Index *pIdx; Vdbe *v; - if( IsVirtual(pTab) ) return; + if( IsVirtual(pTab) ) return 0; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); v = sqlite3GetVdbe(pParse); assert( v!=0 ); - sqlite3OpenTable(pParse, base, iDb, pTab, op); + sqlite3OpenTable(pParse, baseCur, iDb, pTab, op); for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); assert( pIdx->pSchema==pTab->pSchema ); - 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<=base+i ){ - pParse->nTab = base+i; - } + sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIdx->zName)); + } + if( pParse->nTab<=baseCur+i ){ + pParse->nTab = baseCur+i; + } + return i-1; } #ifdef SQLITE_TEST /* @@ -54758,11 +56501,11 @@ } if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){ return 0; /* Different sort orders */ } if( pSrc->azColl[i]!=pDest->azColl[i] ){ - return 0; /* Different sort orders */ + return 0; /* Different collating sequences */ } } /* If no test above fails then the indices must be compatible */ return 1; @@ -54816,12 +56559,13 @@ int addr1, addr2; /* Loop addresses */ int emptyDestTest; /* Address of test for empty pDest */ int emptySrcTest; /* Address of test for empty pSrc */ Vdbe *v; /* The VDBE we are building */ KeyInfo *pKey; /* Key information for an index */ - int counterMem; /* Memory register used by AUTOINC */ + int regAutoinc; /* 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 ... */ } if( pDest->pTrigger ){ @@ -54879,11 +56623,11 @@ /* At this point we have established that the statement is of the ** correct syntactic form to participate in this optimization. Now ** we have to check the semantics. */ pItem = pSelect->pSrc->a; - pSrc = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase); + pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase); if( pSrc==0 ){ return 0; /* FROM clause does not contain a real table */ } if( pSrc==pDest ){ return 0; /* tab1 and tab2 may not be the same table */ @@ -54944,11 +56688,11 @@ iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema); v = sqlite3GetVdbe(pParse); sqlite3CodeVerifySchema(pParse, iDbSrc); iSrc = pParse->nTab++; iDest = pParse->nTab++; - counterMem = autoIncBegin(pParse, iDbDest, pDest); + regAutoinc = 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 ** are indices to be copied and the destination is not empty, ** we have to disallow the transfer optimization because the @@ -54957,68 +56701,69 @@ ** Or if the destination has a UNIQUE index and is not empty, ** we also disallow the transfer optimization because we cannot ** insure that all entries in the union of DEST and SRC will be ** unique. */ - addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iDest, 0); - emptyDestTest = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); + addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); + emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0); sqlite3VdbeJumpHere(v, addr1); }else{ emptyDestTest = 0; } sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead); - emptySrcTest = sqlite3VdbeAddOp(v, OP_Rewind, iSrc, 0); + emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); + regData = sqlite3GetTempReg(pParse); + regRowid = sqlite3GetTempReg(pParse); if( pDest->iPKey>=0 ){ - 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); + 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); sqlite3VdbeJumpHere(v, addr2); - autoIncStep(pParse, counterMem); + autoIncStep(pParse, regAutoinc, regRowid); }else if( pDest->pIndex==0 ){ - addr1 = sqlite3VdbeAddOp(v, OP_NewRowid, iDest, 0); - }else{ - addr1 = sqlite3VdbeAddOp(v, OP_Rowid, iSrc, 0); + addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid); + }else{ + addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid); assert( pDest->autoInc==0 ); } - 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); + 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); for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){ for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){ if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break; } assert( pSrcIdx ); - sqlite3VdbeAddOp(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp(v, OP_Close, iDest, 0); - sqlite3VdbeAddOp(v, OP_Integer, iDbSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx); - VdbeComment((v, "# %s", pSrcIdx->zName)); - sqlite3VdbeOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, - (char*)pKey, P3_KEYINFO_HANDOFF); - sqlite3VdbeAddOp(v, OP_Integer, iDbDest, 0); + sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pSrcIdx->zName)); pKey = sqlite3IndexKeyinfo(pParse, pDestIdx); - 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); + 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); sqlite3VdbeJumpHere(v, addr1); } sqlite3VdbeJumpHere(v, emptySrcTest); - sqlite3VdbeAddOp(v, OP_Close, iSrc, 0); - sqlite3VdbeAddOp(v, OP_Close, iDest, 0); + sqlite3ReleaseTempReg(pParse, regRowid); + sqlite3ReleaseTempReg(pParse, regData); + sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); if( emptyDestTest ){ - sqlite3VdbeAddOp(v, OP_Halt, SQLITE_OK, 0); + sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0); sqlite3VdbeJumpHere(v, emptyDestTest); - sqlite3VdbeAddOp(v, OP_Close, iDest, 0); + sqlite3VdbeAddOp2(v, OP_Close, iDest, 0); return 0; }else{ return 1; } } @@ -55175,11 +56920,13 @@ ** This file contains code used to dynamically load extensions into ** the SQLite library. */ #ifndef SQLITE_OMIT_LOAD_EXTENSION -#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ +#ifndef SQLITE_CORE + #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ +#endif /************** Include sqlite3ext.h in the middle of loadext.c **************/ /************** Begin file sqlite3ext.h **************************************/ /* ** 2006 June 7 ** @@ -56041,11 +57788,11 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to implement the PRAGMA command. ** -** $Id: pragma.c,v 1.150 2007/11/13 10:30:25 danielk1977 Exp $ +** $Id: pragma.c,v 1.169 2008/01/22 01:48:09 drh Exp $ */ /* Ignore this whole file if pragmas are disabled */ #if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER) @@ -56175,16 +57922,17 @@ /* ** Generate code to return a single integer value. */ static void returnSingleInt(Parse *pParse, const char *zLabel, int value){ Vdbe *v = sqlite3GetVdbe(pParse); - sqlite3VdbeAddOp(v, OP_Integer, value, 0); + int mem = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, value, mem); if( pParse->explain==0 ){ sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P3_STATIC); - } - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, P4_STATIC); + } + sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1); } #ifndef SQLITE_OMIT_FLAG_PRAGMAS /* ** Check to see if zRight and zLeft refer to a pragma that queries @@ -56237,11 +57985,11 @@ /* Many of the flag-pragmas modify the code generated by the SQL ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. */ - sqlite3VdbeAddOp(v, OP_Expire, 0, 0); + sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); } } return 1; } @@ -56277,12 +58025,13 @@ const char *zDb = 0; /* The database name */ Token *pId; /* Pointer to <id> token */ int iDb; /* Database index for <database> */ sqlite3 *db = pParse->db; Db *pDb; - Vdbe *v = sqlite3GetVdbe(pParse); + Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db); 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[]. */ iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); if( iDb<0 ) return; @@ -56325,37 +58074,38 @@ ** synchronous setting. A negative value means synchronous is off ** and a positive value means synchronous is on. */ if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){ static const VdbeOpList getCacheSize[] = { - { 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}, + { 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}, }; int addr; if( sqlite3ReadSchema(pParse) ) goto pragma_out; sqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P3_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", P4_STATIC); + pParse->nMem += 2; addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize); sqlite3VdbeChangeP1(v, addr, iDb); sqlite3VdbeChangeP1(v, addr+5, SQLITE_DEFAULT_CACHE_SIZE); }else{ int size = atoi(zRight); if( size<0 ) size = -size; sqlite3BeginWriteOperation(pParse, 0, iDb); - 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); + 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); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } }else @@ -56444,13 +58194,13 @@ assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE); if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ zRet = "exclusive"; } sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P3_STATIC); - sqlite3VdbeOp3(v, OP_String8, 0, 0, zRet, 0); - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", P4_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); }else #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ /* ** PRAGMA [database.]auto_vacuum @@ -56468,10 +58218,11 @@ int auto_vacuum = pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM; returnSingleInt(pParse, "auto_vacuum", auto_vacuum); }else{ int eAuto = getAutoVacuum(zRight); + db->nextAutovac = eAuto; if( eAuto>=0 ){ /* Call SetAutoVacuum() to set initialize the internal auto and ** incr-vacuum flags. This is required in case this connection ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. @@ -56483,15 +58234,15 @@ ** file. Before writing to meta[6], check that meta[3] indicates ** that this really is an auto-vacuum capable database. */ static const VdbeOpList setMeta6[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ - { OP_ReadCookie, 0, 3, 0}, /* 1 */ - { OP_If, 0, 0, 0}, /* 2 */ + { OP_ReadCookie, 0, 1, 3}, /* 1 */ + { OP_If, 1, 0, 0}, /* 2 */ { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ - { OP_Integer, 0, 0, 0}, /* 4 */ - { OP_SetCookie, 0, 6, 0}, /* 5 */ + { OP_Integer, 0, 1, 0}, /* 4 */ + { OP_SetCookie, 0, 6, 1}, /* 5 */ }; int iAddr; iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6); sqlite3VdbeChangeP1(v, iAddr, iDb); sqlite3VdbeChangeP1(v, iAddr+1, iDb); @@ -56518,15 +58269,15 @@ } if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ iLimit = 0x7fffffff; } sqlite3BeginWriteOperation(pParse, 0, iDb); - 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); + 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); sqlite3VdbeJumpHere(v, addr); }else #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS @@ -56588,13 +58339,13 @@ if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){ if( !zRight ){ if( sqlite3_temp_directory ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, - "temp_store_directory", P3_STATIC); - sqlite3VdbeOp3(v, OP_String8, 0, 0, sqlite3_temp_directory, 0); - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + "temp_store_directory", P4_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } }else{ if( zRight[0] && !sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE) ){ @@ -56668,35 +58419,36 @@ if( pTab ){ int i; int nHidden = 0; Column *pCol; sqlite3VdbeSetNumCols(v, 6); - 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); + 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); sqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ const Token *pDflt; if( IsHiddenColumn(pCol) ){ nHidden++; continue; } - sqlite3VdbeAddOp(v, OP_Integer, i-nHidden, 0); - sqlite3VdbeOp3(v, OP_String8, 0, 0, pCol->zName, 0); - sqlite3VdbeOp3(v, OP_String8, 0, 0, + sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pCol->zType ? pCol->zType : "", 0); - sqlite3VdbeAddOp(v, OP_Integer, pCol->notNull, 0); + sqlite3VdbeAddOp2(v, OP_Integer, pCol->notNull, 4); if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){ - sqlite3VdbeOp3(v, OP_String8, 0, 0, (char*)pDflt->z, pDflt->n); - }else{ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); - } - sqlite3VdbeAddOp(v, OP_Integer, pCol->isPrimKey, 0); - sqlite3VdbeAddOp(v, OP_Callback, 6, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pDflt->z, pDflt->n); + }else{ + sqlite3VdbeAddOp2(v, OP_Null, 0, 5); + } + sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6); } } }else if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){ @@ -56706,20 +58458,21 @@ pIdx = sqlite3FindIndex(db, zRight, zDb); if( pIdx ){ int i; pTab = pIdx->pTable; sqlite3VdbeSetNumCols(v, 3); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", P3_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", P3_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", P3_STATIC); + 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); for(i=0; i<pIdx->nColumn; i++){ int cnum = pIdx->aiColumn[i]; - sqlite3VdbeAddOp(v, OP_Integer, i, 0); - sqlite3VdbeAddOp(v, OP_Integer, cnum, 0); + sqlite3VdbeAddOp2(v, OP_Integer, i, 1); + sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2); assert( pTab->nCol>cnum ); - sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->aCol[cnum].zName, 0); - sqlite3VdbeAddOp(v, OP_Callback, 3, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } } }else if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){ @@ -56731,18 +58484,19 @@ v = sqlite3GetVdbe(pParse); pIdx = pTab->pIndex; if( pIdx ){ int i = 0; sqlite3VdbeSetNumCols(v, 3); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", P3_STATIC); + 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); while(pIdx){ - 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); + 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); ++i; pIdx = pIdx->pNext; } } } @@ -56750,35 +58504,37 @@ if( sqlite3StrICmp(zLeft, "database_list")==0 ){ int i; if( sqlite3ReadSchema(pParse) ) goto pragma_out; sqlite3VdbeSetNumCols(v, 3); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC); - sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", P3_STATIC); + 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); for(i=0; i<db->nDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zName!=0 ); - sqlite3VdbeAddOp(v, OP_Integer, i, 0); - sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, 0); - sqlite3VdbeOp3(v, OP_String8, 0, 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, sqlite3BtreeGetFilename(db->aDb[i].pBt), 0); - sqlite3VdbeAddOp(v, OP_Callback, 3, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } }else if( sqlite3StrICmp(zLeft, "collation_list")==0 ){ int i = 0; HashElem *p; sqlite3VdbeSetNumCols(v, 2); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P3_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC); + pParse->nMem = 2; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", P4_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P4_STATIC); for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); - sqlite3VdbeAddOp(v, OP_Integer, i++, 0); - sqlite3VdbeOp3(v, OP_String8, 0, 0, pColl->zName, 0); - sqlite3VdbeAddOp(v, OP_Callback, 2, 0); + sqlite3VdbeAddOp2(v, OP_Integer, i++, 1); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); } }else #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ #ifndef SQLITE_OMIT_FOREIGN_KEY @@ -56791,26 +58547,27 @@ v = sqlite3GetVdbe(pParse); pFK = pTab->pFKey; if( pFK ){ int i = 0; sqlite3VdbeSetNumCols(v, 5); - 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); + 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); while(pFK){ int j; for(j=0; j<pFK->nCol; j++){ char *zCol = pFK->aCol[j].zCol; - 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); + 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); } ++i; pFK = pFK->pNextFrom; } } @@ -56842,39 +58599,47 @@ #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 #endif #ifndef SQLITE_OMIT_INTEGRITY_CHECK - if( sqlite3StrICmp(zLeft, "integrity_check")==0 ){ + /* Pragma "quick_check" is an experimental reduced version of + ** integrity_check designed to detect most database corruption + ** without most of the overhead of a full integrity-check. + */ + if( sqlite3StrICmp(zLeft, "integrity_check")==0 + || sqlite3StrICmp(zLeft, "quick_check")==0 + ){ int i, j, addr, mxErr; /* Code that appears at the end of the integrity check. If no error ** messages have been generated, output OK. Otherwise output the ** error message */ static const VdbeOpList endCode[] = { - { 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}, + { OP_AddImm, 1, 0, 0}, /* 0 */ + { OP_IfNeg, 1, 0, 0}, /* 1 */ + { OP_String8, 0, 3, 0}, /* 2 */ + { OP_ResultRow, 3, 1, 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", P3_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", P4_STATIC); /* Set the maximum error count */ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if( zRight ){ mxErr = atoi(zRight); if( mxErr<=0 ){ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } - sqlite3VdbeAddOp(v, OP_MemInt, mxErr, 0); + sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */ /* Do an integrity check on each database file */ for(i=0; i<db->nDb; i++){ HashElem *x; Hash *pTbls; @@ -56881,113 +58646,128 @@ int cnt = 0; if( OMIT_TEMPDB && i==1 ) continue; sqlite3CodeVerifySchema(pParse, i); - addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0); - sqlite3VdbeAddOp(v, OP_Halt, 0, 0); + addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */ + sqlite3VdbeAddOp2(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; - sqlite3VdbeAddOp(v, OP_Integer, pTab->tnum, 0); + sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt); cnt++; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ - sqlite3VdbeAddOp(v, OP_Integer, pIdx->tnum, 0); + sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt); cnt++; } } if( cnt==0 ) continue; - sqlite3VdbeAddOp(v, OP_IntegrityCk, 0, i); - addr = sqlite3VdbeAddOp(v, OP_IsNull, -1, 0); - sqlite3VdbeOp3(v, OP_String8, 0, 0, + + /* Make sure sufficient number of registers have been allocated */ + if( pParse->nMem < cnt+3 ){ + pParse->nMem = cnt+3; + } + + /* 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, sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName), - P3_DYNAMIC); - sqlite3VdbeAddOp(v, OP_Pull, 1, 0); - sqlite3VdbeAddOp(v, OP_Concat, 0, 0); - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + P4_DYNAMIC); + sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 2); + sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1); sqlite3VdbeJumpHere(v, addr); /* Make sure all the indices are constructed correctly. */ - for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ + for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; int loopTop; if( pTab->pIndex==0 ) continue; - addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0); - sqlite3VdbeAddOp(v, OP_Halt, 0, 0); + addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */ + sqlite3VdbeAddOp2(v, OP_Halt, 0, 0); sqlite3VdbeJumpHere(v, addr); sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead); - sqlite3VdbeAddOp(v, OP_MemInt, 0, 1); - loopTop = sqlite3VdbeAddOp(v, OP_Rewind, 1, 0); - sqlite3VdbeAddOp(v, OP_MemIncr, 1, 1); + 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 */ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int jmp2; static const VdbeOpList idxErr[] = { - { 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}, + { 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}, }; - sqlite3GenerateIndexKey(v, pIdx, 1); - jmp2 = sqlite3VdbeAddOp(v, OP_Found, j+2, 0); + sqlite3GenerateIndexKey(pParse, pIdx, 1, 3); + jmp2 = sqlite3VdbeAddOp3(v, OP_Found, j+2, 0, 3); addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr); - sqlite3VdbeChangeP3(v, addr+4, pIdx->zName, P3_STATIC); + 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, jmp2); } - sqlite3VdbeAddOp(v, OP_Next, 1, loopTop+1); + sqlite3VdbeAddOp2(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_MemInt, 0, 2, 0}, + { OP_Integer, 0, 3, 0}, { OP_Rewind, 0, 0, 0}, /* 1 */ - { OP_MemIncr, 1, 2, 0}, + { OP_AddImm, 3, 1, 0}, { OP_Next, 0, 0, 0}, /* 3 */ - { 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}, + { 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}, }; if( pIdx->tnum==0 ) continue; - addr = sqlite3VdbeAddOp(v, OP_IfMemPos, 0, 0); - sqlite3VdbeAddOp(v, OP_Halt, 0, 0); + addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); + sqlite3VdbeAddOp2(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+6); - sqlite3VdbeChangeP3(v, addr+9, pIdx->zName, P3_STATIC); + sqlite3VdbeJumpHere(v, addr+4); + sqlite3VdbeChangeP4(v, addr+6, + "wrong # of entries in index ", P4_STATIC); + sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC); } } } addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode); - sqlite3VdbeChangeP1(v, addr+1, mxErr); - sqlite3VdbeJumpHere(v, addr+2); + sqlite3VdbeChangeP2(v, addr, -mxErr); + sqlite3VdbeJumpHere(v, addr+1); + sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC); }else #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_UTF16 /* ** PRAGMA encoding ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" ** - ** In it's first form, this pragma returns the encoding of the main + ** In its first form, this pragma returns the encoding of the main ** database. If the database is not initialized, it is initialized now. ** ** The second form of this pragma is a no-op if the main database file ** has not already been initialized. In this case it sets the default ** encoding that will be used for the main database file if a new file @@ -57020,19 +58800,19 @@ }; const struct EncName *pEnc; if( !zRight ){ /* "PRAGMA encoding" */ if( sqlite3ReadSchema(pParse) ) goto pragma_out; sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P3_STATIC); - sqlite3VdbeAddOp(v, OP_String8, 0, 0); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", P4_STATIC); + sqlite3VdbeAddOp2(v, OP_String8, 0, 1); for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ if( pEnc->enc==ENC(pParse->db) ){ - sqlite3VdbeChangeP3(v, -1, pEnc->zName, P3_STATIC); + sqlite3VdbeChangeP4(v, -1, pEnc->zName, P4_STATIC); break; } } - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); }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 ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. @@ -57104,29 +58884,29 @@ if( zRight && iDb>=0 ){ /* Write the specified cookie value */ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ - { OP_Integer, 0, 0, 0}, /* 1 */ - { OP_SetCookie, 0, 0, 0}, /* 2 */ + { OP_Integer, 0, 1, 0}, /* 1 */ + { OP_SetCookie, 0, 0, 1}, /* 2 */ }; int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie); sqlite3VdbeChangeP1(v, addr, iDb); sqlite3VdbeChangeP1(v, addr+1, atoi(zRight)); sqlite3VdbeChangeP1(v, addr+2, iDb); sqlite3VdbeChangeP2(v, addr+2, iCookie); }else{ /* Read the specified cookie value */ static const VdbeOpList readCookie[] = { - { OP_ReadCookie, 0, 0, 0}, /* 0 */ - { OP_Callback, 1, 0, 0} + { OP_ReadCookie, 0, 1, 0}, /* 0 */ + { OP_ResultRow, 1, 1, 0} }; int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie); sqlite3VdbeChangeP1(v, addr, iDb); - sqlite3VdbeChangeP2(v, addr, iCookie); + sqlite3VdbeChangeP3(v, addr, iCookie); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P3_TRANSIENT); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, P4_TRANSIENT); } }else #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) @@ -57138,28 +58918,29 @@ "unlocked", "shared", "reserved", "pending", "exclusive" }; int i; Vdbe *v = sqlite3GetVdbe(pParse); sqlite3VdbeSetNumCols(v, 2); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P3_STATIC); - sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P3_STATIC); + pParse->nMem = 2; + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", P4_STATIC); + sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", P4_STATIC); for(i=0; i<db->nDb; i++){ Btree *pBt; Pager *pPager; const char *zState = "unknown"; int j; if( db->aDb[i].zName==0 ) continue; - sqlite3VdbeOp3(v, OP_String8, 0, 0, db->aDb[i].zName, P3_STATIC); + sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC); pBt = db->aDb[i].pBt; if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){ zState = "closed"; - }else if( sqlite3_file_control(db, db->aDb[i].zName, + }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } - sqlite3VdbeOp3(v, OP_String8, 0, 0, zState, P3_STATIC); - sqlite3VdbeAddOp(v, OP_Callback, 2, 0); + sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC); + sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2); } }else #endif #ifdef SQLITE_SSE @@ -57200,11 +58981,11 @@ if( v ){ /* Code an OP_Expire at the end of each PRAGMA program to cause ** the VDBE implementing the pragma to expire. Most (all?) pragmas ** are only valid for a single execution. */ - sqlite3VdbeAddOp(v, OP_Expire, 1, 0); + sqlite3VdbeAddOp2(v, OP_Expire, 1, 0); /* ** Reset the safety level, in case the fullfsync flag or synchronous ** setting changed. */ @@ -57237,11 +59018,11 @@ ************************************************************************* ** This file contains the implementation of the sqlite3_prepare() ** interface, and routines that contribute to loading the database schema ** from disk. ** -** $Id: prepare.c,v 1.64 2007/11/14 06:48:48 danielk1977 Exp $ +** $Id: prepare.c,v 1.75 2008/01/23 03:03:05 drh Exp $ */ /* ** Fill the InitData structure with an error message that indicates ** that the database is corrupt. @@ -57308,10 +59089,12 @@ corruptSchema(pData, zErr); } sqlite3_free(zErr); return 1; } + }else if( argv[0]==0 ){ + corruptSchema(pData, 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 ** constraint for a CREATE TABLE. The index should have already ** been created when we processed the CREATE TABLE. All we have @@ -57380,10 +59163,11 @@ #endif assert( iDb>=0 && iDb<db->nDb ); assert( db->aDb[iDb].pSchema ); assert( sqlite3_mutex_held(db->mutex) ); + assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) ); /* zMasterSchema and zInitScript are set to point at the master schema ** and initialisation script appropriate for the database being ** initialised. zMasterName is the name of the master table. */ @@ -57393,29 +59177,28 @@ zMasterSchema = master_schema; } zMasterName = SCHEMA_TABLE(iDb); /* Construct the schema tables. */ - sqlite3SafetyOff(db); azArg[0] = zMasterName; azArg[1] = "1"; azArg[2] = zMasterSchema; azArg[3] = 0; initData.db = db; initData.iDb = iDb; initData.pzErrMsg = pzErrMsg; + (void)sqlite3SafetyOff(db); rc = sqlite3InitCallback(&initData, 3, (char **)azArg, 0); - if( rc ){ - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); + if( rc ){ rc = initData.rc; goto error_out; } pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName); if( pTab ){ pTab->readOnly = 1; } - sqlite3SafetyOn(db); /* Create a cursor to hold the database open */ pDb = &db->aDb[iDb]; if( pDb->pBt==0 ){ @@ -57490,10 +59273,11 @@ } pDb->pSchema->enc = ENC(db); 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); /* ** file_format==1 Version 3.0.0. @@ -57510,10 +59294,18 @@ 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, + ** clear the legacy_file_format pragma flag so that a VACUUM will + ** not downgrade the database and thus invalidate any descending + ** indices that the user might have created. + */ + if( iDb==0 && meta[1]>=4 ){ + db->flags &= ~SQLITE_LegacyFileFmt; + } /* Read the schema information out of the schema tables */ assert( db->init.busy ); if( rc==SQLITE_EMPTY ){ @@ -57522,11 +59314,11 @@ }else{ char *zSql; zSql = sqlite3MPrintf(db, "SELECT name, rootpage, sql FROM '%q'.%s", db->aDb[iDb].zName, zMasterName); - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); #ifndef SQLITE_OMIT_AUTHORIZATION { int (*xAuth)(void*,int,const char*,const char*,const char*,const char*); xAuth = db->xAuth; db->xAuth = 0; @@ -57535,11 +59327,11 @@ #ifndef SQLITE_OMIT_AUTHORIZATION db->xAuth = xAuth; } #endif if( rc==SQLITE_ABORT ) rc = initData.rc; - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); sqlite3_free(zSql); #ifndef SQLITE_OMIT_ANALYZE if( rc==SQLITE_OK ){ sqlite3AnalysisLoad(db, iDb); } @@ -57556,11 +59348,11 @@ ** the schema loaded, even if errors occured. In this situation the ** current sqlite3_prepare() operation will fail, but the following one ** will attempt to compile the supplied statement against whatever subset ** of the schema was loaded before the error occured. The primary ** purpose of this is to allow access to the sqlite_master table - ** even when it's contents have been corrupted. + ** even when its contents have been corrupted. */ DbSetProperty(db, iDb, DB_SchemaLoaded); rc = SQLITE_OK; } sqlite3BtreeLeave(pDb->pBt); @@ -57734,21 +59526,23 @@ int rc; rc = sqlite3BtreeSchemaLocked(pBt); if( rc ){ const char *zDb = db->aDb[i].zName; sqlite3Error(db, SQLITE_LOCKED, "database schema is locked: %s", zDb); - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); return SQLITE_LOCKED; } } } memset(&sParse, 0, sizeof(sParse)); sParse.db = db; if( nBytes>=0 && zSql[nBytes]!=0 ){ char *zSqlCopy; - if( nBytes>SQLITE_MAX_SQL_LENGTH ){ + if( SQLITE_MAX_SQL_LENGTH>0 && nBytes>SQLITE_MAX_SQL_LENGTH ){ + sqlite3Error(db, SQLITE_TOOBIG, "statement too long"); + (void)sqlite3SafetyOff(db); return SQLITE_TOOBIG; } zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes); if( zSqlCopy ){ sqlite3RunParser(&sParse, zSqlCopy, &zErrMsg); @@ -57779,20 +59573,23 @@ #ifndef SQLITE_OMIT_EXPLAIN if( rc==SQLITE_OK && sParse.pVdbe && sParse.explain ){ if( sParse.explain==2 ){ sqlite3VdbeSetNumCols(sParse.pVdbe, 3); - 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, 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); + 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); + }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); } } #endif if( sqlite3SafetyOff(db) ){ @@ -57815,11 +59612,10 @@ }else{ sqlite3Error(db, rc, 0); } rc = sqlite3ApiExit(db, rc); - /* sqlite3ReleaseThreadData(); */ assert( (rc&db->errMask)==rc ); return rc; } static int sqlite3LockAndPrepare( sqlite3 *db, /* Database handle. */ @@ -57828,11 +59624,11 @@ int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */ sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */ const char **pzTail /* OUT: End of parsed string */ ){ int rc; - if( sqlite3SafetyCheck(db) ){ + if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE; } sqlite3_mutex_enter(db->mutex); sqlite3BtreeEnterAll(db); rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, ppStmt, pzTail); @@ -57852,13 +59648,11 @@ const char *zSql; sqlite3 *db; assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) ); zSql = sqlite3_sql((sqlite3_stmt *)p); - if( zSql==0 ){ - return 0; - } + assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */ db = sqlite3VdbeDb(p); assert( sqlite3_mutex_held(db->mutex) ); rc = sqlite3LockAndPrepare(db, zSql, -1, 0, &pNew, 0); if( rc ){ if( rc==SQLITE_NOMEM ){ @@ -57923,11 +59717,11 @@ */ char *zSql8; const char *zTail8 = 0; int rc = SQLITE_OK; - if( sqlite3SafetyCheck(db) ){ + if( !sqlite3SafetyCheckOk(db) ){ return SQLITE_MISUSE; } sqlite3_mutex_enter(db->mutex); zSql8 = sqlite3Utf16to8(db, zSql, nBytes); if( zSql8 ){ @@ -57992,11 +59786,11 @@ ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle SELECT statements in SQLite. ** -** $Id: select.c,v 1.363 2007/11/23 13:42:52 drh Exp $ +** $Id: select.c,v 1.411 2008/01/25 15:04:50 drh Exp $ */ /* ** Delete all the content of a Select structure but do not deallocate @@ -58010,10 +59804,20 @@ sqlite3ExprDelete(p->pHaving); sqlite3ExprListDelete(p->pOrderBy); sqlite3SelectDelete(p->pPrior); sqlite3ExprDelete(p->pLimit); 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; } /* ** Allocate a new Select structure and return a pointer to that @@ -58363,26 +60167,38 @@ ** stack into the sorter. */ static void pushOntoSorter( Parse *pParse, /* Parser context */ ExprList *pOrderBy, /* The ORDER BY clause */ - Select *pSelect /* The whole SELECT statement */ + Select *pSelect, /* The whole SELECT statement */ + int regData /* Register holding data to be sorted */ ){ Vdbe *v = pParse->pVdbe; - 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); + int nExpr = pOrderBy->nExpr; + int regBase = sqlite3GetTempRange(pParse, nExpr+2); + int regRecord = sqlite3GetTempReg(pParse); + sqlite3ExprCodeExprList(pParse, pOrderBy, regBase); + sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr); + sqlite3VdbeAddOp2(v, OP_Move, regData, regBase+nExpr+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>=0 ){ int addr1, addr2; - addr1 = sqlite3VdbeAddOp(v, OP_IfMemZero, pSelect->iLimit+1, 0); - sqlite3VdbeAddOp(v, OP_MemIncr, -1, pSelect->iLimit+1); - addr2 = sqlite3VdbeAddOp(v, OP_Goto, 0, 0); + int iLimit; + if( pSelect->pOffset ){ + 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); sqlite3VdbeJumpHere(v, addr1); - sqlite3VdbeAddOp(v, OP_Last, pOrderBy->iECursor, 0); - sqlite3VdbeAddOp(v, OP_Delete, pOrderBy->iECursor, 0); + sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor); + sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor); sqlite3VdbeJumpHere(v, addr2); pSelect->iLimit = -1; } } @@ -58390,56 +60206,61 @@ ** Add code to implement the OFFSET */ 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 nPop /* Number of times to pop stack when jumping */ + int iContinue /* Jump here to skip the current record */ ){ if( p->iOffset>=0 && iContinue!=0 ){ int addr; - 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")); + 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")); sqlite3VdbeJumpHere(v, addr); } } /* -** 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 +** 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 ** seen combinations of the N values. A new entry is made in iTab ** if the current N values are new. ** ** A jump to addrRepeat is made and the N+1 values are popped from the ** stack if the top N elements are not distinct. */ static void codeDistinct( - Vdbe *v, /* Generate code into this VM */ + Parse *pParse, /* Parsing and code generating context */ int iTab, /* A sorting index used to test for distinctness */ int addrRepeat, /* Jump to here if not distinct */ - int N /* The top N elements of the stack must be distinct */ -){ - 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); + int N, /* Number of elements */ + int iMem /* First element */ +){ + 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); } /* ** Generate an error message when a SELECT is used within a subexpression ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result ** column. We do this in a subroutine because the error occurs in multiple ** places. */ -static int checkForMultiColumnSelectError(Parse *pParse, int eDest, int nExpr){ +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; 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"); return 1; }else{ @@ -58454,143 +60275,170 @@ ** If srcTab and nColumn are both zero, then the pEList expressions ** are evaluated in order to get the data for this row. If nColumn>0 ** then data is pulled from srcTab and pEList is used only to get the ** datatypes for each column. */ -static int selectInnerLoop( +static void selectInnerLoop( Parse *pParse, /* The parser context */ Select *p, /* The complete select statement being coded */ ExprList *pEList, /* List of values being extracted */ int srcTab, /* Pull data from this table */ 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 */ - int eDest, /* How to dispose of the results */ - int iParm, /* An argument to the disposal method */ + SelectDest *pDest, /* How to dispose of the results */ int iContinue, /* Jump here to continue with next row */ 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 */ - - if( v==0 ) return 0; + 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 */ + int nToFree; /* Number of result columns to release */ + + if( v==0 ) return; assert( pEList!=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, 0); + codeOffset(v, p, iContinue); } /* Pull the requested columns. */ if( nColumn>0 ){ + nResultCol = nColumn; + }else{ + nResultCol = pEList->nExpr; + } + if( pDest->iMem>0 ){ + regResult = pDest->iMem; + nToFree = 0; + }else{ + pDest->iMem = regResult = sqlite3GetTempRange(pParse, nResultCol); + nToFree = nResultCol; + } + if( nColumn>0 ){ for(i=0; i<nColumn; i++){ - sqlite3VdbeAddOp(v, OP_Column, srcTab, i); - } - }else{ - nColumn = pEList->nExpr; - sqlite3ExprCodeExprList(pParse, pEList); - } + sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i); + } + }else if( eDest!=SRT_Exists ){ + /* If the destination is an EXISTS(...) expression, the actual + ** values returned by the SELECT are not required. + */ + for(i=0; i<nResultCol; i++){ + sqlite3ExprCode(pParse, pEList->a[i].pExpr, regResult+i); + } + } + 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 ** part of the result. */ if( hasDistinct ){ assert( pEList!=0 ); assert( pEList->nExpr==nColumn ); - codeDistinct(v, distinct, iContinue, nColumn); + codeDistinct(pParse, distinct, iContinue, nColumn, regResult); if( pOrderBy==0 ){ - codeOffset(v, p, iContinue, nColumn); - } - } - - if( checkForMultiColumnSelectError(pParse, eDest, pEList->nExpr) ){ - return 0; + codeOffset(v, p, iContinue); + } + } + + if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ + return; } switch( eDest ){ /* In this mode, write each query result to the key of the temporary ** table iParm. */ #ifndef SQLITE_OMIT_COMPOUND_SELECT case SRT_Union: { - sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); + int r1; + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); if( aff ){ - sqlite3VdbeChangeP3(v, -1, aff, P3_STATIC); - } - sqlite3VdbeAddOp(v, OP_IdxInsert, iParm, 0); + sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC); + } + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); + sqlite3ReleaseTempReg(pParse, r1); break; } /* Construct a record from the query result, but instead of ** saving that record, use it as a key to delete elements from ** the temporary table iParm. */ case SRT_Except: { - 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); + int r1; + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + sqlite3VdbeChangeP4(v, -1, aff, P4_STATIC); + sqlite3VdbeAddOp2(v, OP_IdxDelete, iParm, r1); + sqlite3ReleaseTempReg(pParse, r1); break; } #endif /* Store the result as data using a unique key. */ case SRT_Table: case SRT_EphemTab: { - sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); if( pOrderBy ){ - pushOntoSorter(pParse, pOrderBy, p); - }else{ - sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); - sqlite3VdbeAddOp(v, OP_Pull, 1, 0); - sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); - } + pushOntoSorter(pParse, pOrderBy, p, r1); + }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); + } + 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 addr1 = sqlite3VdbeCurrentAddr(v); int addr2; assert( nColumn==1 ); - 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); + addr2 = sqlite3VdbeAddOp1(v, OP_IsNull, regResult); + p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity); 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); - }else{ - sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &p->affinity, 1); - sqlite3VdbeAddOp(v, OP_IdxInsert, (iParm&0x0000FFFF), 0); + pushOntoSorter(pParse, pOrderBy, p, regResult); + }else{ + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1); + sqlite3ReleaseTempReg(pParse, r1); } sqlite3VdbeJumpHere(v, addr2); break; } /* If any row exist in the result set, record that fact and abort. */ case SRT_Exists: { - sqlite3VdbeAddOp(v, OP_MemInt, 1, iParm); - sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm); /* The LIMIT clause will terminate the loop for us */ break; } /* If this is a scalar select that is part of an expression, then @@ -58598,13 +60446,13 @@ ** of the scan loop. */ case SRT_Mem: { assert( nColumn==1 ); if( pOrderBy ){ - pushOntoSorter(pParse, pOrderBy, p); - }else{ - sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); + pushOntoSorter(pParse, pOrderBy, p, regResult); + }else{ + sqlite3VdbeAddOp2(v, OP_Move, regResult, iParm); /* The LIMIT clause will jump out of the loop for us */ } break; } #endif /* #ifndef SQLITE_OMIT_SUBQUERY */ @@ -58614,16 +60462,19 @@ ** popping the data from the stack. */ case SRT_Subroutine: case SRT_Callback: { if( pOrderBy ){ - sqlite3VdbeAddOp(v, OP_MakeRecord, nColumn, 0); - pushOntoSorter(pParse, pOrderBy, p); + int r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1); + pushOntoSorter(pParse, pOrderBy, p, r1); + sqlite3ReleaseTempReg(pParse, r1); }else if( eDest==SRT_Subroutine ){ - sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); - }else{ - sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); + nToFree = 0; /* Preserve registers. Subroutine will need them. */ + sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); + }else{ + sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn); } break; } #if !defined(SQLITE_OMIT_TRIGGER) @@ -58632,23 +60483,22 @@ ** user-defined functions that have side effects. We do not care ** about the actual results of the select. */ default: { assert( eDest==SRT_Discard ); - sqlite3VdbeAddOp(v, OP_Pop, nColumn, 0); break; } #endif } /* Jump to the end of the loop if the LIMIT is reached. */ if( p->iLimit>=0 && pOrderBy==0 ){ - sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); - sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, iBreak); - } - return 0; + sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); + sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, iBreak); + } + sqlite3ReleaseTempRange(pParse, regResult, nToFree); } /* ** Given an expression list, generate a KeyInfo structure that records ** the collating sequence for each expression in that expression list. @@ -58659,12 +60509,12 @@ ** then the KeyInfo structure is appropriate for initializing a virtual ** index to implement a DISTINCT test. ** ** 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 P3 field of an opcode using -** P3_KEYINFO_HANDOFF is the usual way of dealing with this. +** freed. Add the KeyInfo structure to the P4 field of an opcode using +** P4_KEYINFO_HANDOFF is the usual way of dealing with this. */ static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){ sqlite3 *db = pParse->db; int nExpr; KeyInfo *pInfo; @@ -58696,95 +60546,102 @@ ** then the results were placed in a sorter. After the loop is terminated ** we need to run the sorter and output the results. The following ** 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 */ - int eDest, /* Write the sorted results here */ - int iParm /* Optional parameter associated with eDest */ + 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 */ ){ int brk = sqlite3VdbeMakeLabel(v); int cont = sqlite3VdbeMakeLabel(v); int addr; int iTab; 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_Subroutine ){ pseudoTab = pParse->nTab++; - sqlite3VdbeAddOp(v, OP_OpenPseudo, pseudoTab, 0); - sqlite3VdbeAddOp(v, OP_SetNumColumns, pseudoTab, nColumn); - } - 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); + sqlite3VdbeAddOp2(v, OP_OpenPseudo, pseudoTab, 0); + sqlite3VdbeAddOp2(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); switch( eDest ){ case SRT_Table: case SRT_EphemTab: { - sqlite3VdbeAddOp(v, OP_NewRowid, iParm, 0); - sqlite3VdbeAddOp(v, OP_Pull, 1, 0); - sqlite3VdbeAddOp(v, OP_Insert, iParm, OPFLAG_APPEND); + sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid); + sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid); + sqlite3VdbeChangeP5(v, OPFLAG_APPEND); break; } #ifndef SQLITE_OMIT_SUBQUERY case SRT_Set: { + int j1; assert( nColumn==1 ); - 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); + j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regRow); + sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRow, &p->affinity, 1); + sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRow); + sqlite3VdbeJumpHere(v, j1); break; } case SRT_Mem: { assert( nColumn==1 ); - sqlite3VdbeAddOp(v, OP_MemStore, iParm, 1); + sqlite3VdbeAddOp2(v, OP_Move, regRow, iParm); /* The LIMIT clause will terminate the loop for us */ break; } #endif case SRT_Callback: case SRT_Subroutine: { int i; - sqlite3VdbeAddOp(v, OP_Insert, pseudoTab, 0); + sqlite3VdbeAddOp2(v, OP_Integer, 1, regRowid); + sqlite3VdbeAddOp3(v, OP_Insert, pseudoTab, regRow, regRowid); for(i=0; i<nColumn; i++){ - sqlite3VdbeAddOp(v, OP_Column, pseudoTab, i); + sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i); } if( eDest==SRT_Callback ){ - sqlite3VdbeAddOp(v, OP_Callback, nColumn, 0); - }else{ - sqlite3VdbeAddOp(v, OP_Gosub, 0, iParm); + sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn); + }else{ + sqlite3VdbeAddOp2(v, OP_Gosub, 0, iParm); } break; } default: { /* Do nothing */ break; } } + sqlite3ReleaseTempReg(pParse, regRow); + sqlite3ReleaseTempReg(pParse, regRowid); /* Jump to the end of the loop when the LIMIT is reached */ if( p->iLimit>=0 ){ - sqlite3VdbeAddOp(v, OP_MemIncr, -1, p->iLimit); - sqlite3VdbeAddOp(v, OP_IfMemZero, p->iLimit, brk); + sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1); + sqlite3VdbeAddOp2(v, OP_IfZero, p->iLimit, brk); } /* The bottom of the loop */ sqlite3VdbeResolveLabel(v, cont); - sqlite3VdbeAddOp(v, OP_Next, iTab, addr); + sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); sqlite3VdbeResolveLabel(v, brk); if( eDest==SRT_Callback || eDest==SRT_Subroutine ){ - sqlite3VdbeAddOp(v, OP_Close, pseudoTab, 0); + sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0); } } /* @@ -58939,18 +60796,18 @@ const char *zOrigDb = 0; const char *zOrigTab = 0; const char *zOrigCol = 0; const char *zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol); - /* The vdbe must make it's own copy of the column-type and other + /* 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_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); + sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, P4_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, P4_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, P4_TRANSIENT); + sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, P4_TRANSIENT); } } /* ** Generate code that will tell the VDBE the names of columns @@ -59010,11 +60867,11 @@ char *zTab; zTab = pTabList->a[j].zAlias; if( fullNames || zTab==0 ) zTab = pTab->zName; sqlite3SetString(&zName, zTab, ".", zCol, (char*)0); - sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P3_DYNAMIC); + sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, P4_DYNAMIC); }else{ sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, strlen(zCol)); } }else if( p->span.z && p->span.z[0] ){ sqlite3VdbeSetColName(v, i, COLNAME_NAME, (char*)p->span.z, p->span.n); @@ -59222,11 +61079,11 @@ #endif }else{ /* An ordinary table or view name in the FROM clause */ assert( pFrom->pTab==0 ); pFrom->pTab = pTab = - sqlite3LocateTable(pParse,pFrom->zName,pFrom->zDatabase); + sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase); if( pTab==0 ){ return 1; } pTab->nRef++; #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE) @@ -59391,110 +61248,270 @@ rc = SQLITE_NOMEM; } return rc; } -#ifndef SQLITE_OMIT_COMPOUND_SELECT -/* -** This routine associates entries in an ORDER BY expression list with -** columns in a result. For each ORDER BY expression, the opcode of -** the top-level node is changed to TK_COLUMN and the iColumn value of -** the top-level node is filled in with column number and the iTable -** value of the top-level node is filled with iTable parameter. -** -** If there are prior SELECT clauses, they are processed first. A match -** in an earlier SELECT takes precedence over a later SELECT. -** -** Any entry that does not match is flagged as an error. The number -** of errors is returned. -*/ -static int matchOrderbyToColumn( - Parse *pParse, /* A place to leave error messages */ - Select *pSelect, /* Match to result columns of this SELECT */ - ExprList *pOrderBy, /* The ORDER BY values to match against columns */ - int iTable, /* Insert this value in iTable */ - int mustComplete /* If TRUE all ORDER BYs must match */ -){ - int nErr = 0; - int i, j; - ExprList *pEList; +/* +** pE is a pointer to an expression which is a single term in +** ORDER BY or GROUP BY clause. +** +** 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 +** caller that it should sort by the value of the ORDER BY +** expression. +** +** If the SELECT is compound, then attempt to match pE against +** result set columns in the left-most SELECT statement. Return +** the index i of the matching column, as an indication to the +** caller that it should sort by the i-th column. If there is +** no match, return -1 and leave an error message in pParse. +*/ +static int matchOrderByTermToExprList( + Parse *pParse, /* Parsing context for error messages */ + Select *pSelect, /* The SELECT statement with the ORDER BY clause */ + Expr *pE, /* The specific ORDER BY term */ + int idx, /* When ORDER BY term is this */ + int isCompound, /* True if this is a compound SELECT */ + u8 *pHasAgg /* True if expression contains aggregate functions */ +){ + int i; /* Loop counter */ + ExprList *pEList; /* The columns of the result set */ + NameContext nc; /* Name context for resolving pE */ + + + /* 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. + */ + if( pE->op==TK_ID || (pE->op==TK_STRING && pE->token.z[0]!='\'') ){ + sqlite3 *db = pParse->db; + char *zCol = sqlite3NameFromToken(db, &pE->token); + if( zCol==0 ){ + return -1; + } + for(i=0; i<pEList->nExpr; i++){ + char *zAs = pEList->a[i].zName; + if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ + sqlite3_free(zCol); + return i+1; + } + } + sqlite3_free(zCol); + } + + /* Resolve all names in the ORDER BY term expression + */ + memset(&nc, 0, sizeof(nc)); + nc.pParse = pParse; + nc.pSrcList = pSelect->pSrc; + nc.pEList = pEList; + nc.allowAgg = 1; + nc.nErr = 0; + if( sqlite3ExprResolveNames(&nc, pE) ){ + if( isCompound ){ + sqlite3ErrorClear(pParse); + return 0; + }else{ + return -1; + } + } + if( nc.hasAgg && pHasAgg ){ + *pHasAgg = 1; + } + + /* For a compound SELECT, we need to try to match the ORDER BY + ** expression against an expression in the result set + */ + if( isCompound ){ + for(i=0; i<pEList->nExpr; i++){ + if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){ + return i+1; + } + } + } + return 0; +} + + +/* +** Analyze and ORDER BY or GROUP BY clause in a simple SELECT statement. +** Return the number of errors seen. +** +** Every 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. +*/ +static int processOrderGroupBy( + Parse *pParse, /* Parsing context. Leave error messages here */ + Select *pSelect, /* The SELECT statement containing the clause */ + ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ + int isOrder, /* 1 for ORDER BY. 0 for GROUP BY */ + u8 *pHasAgg /* Set to TRUE if any term contains an aggregate */ +){ + int i; sqlite3 *db = pParse->db; - - if( pSelect==0 || pOrderBy==0 ) return 1; - if( mustComplete ){ - for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; } - } - if( prepSelectStmt(pParse, pSelect) ){ - return 1; - } - if( pSelect->pPrior ){ - if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){ - return 1; - } + ExprList *pEList; + + if( pOrderBy==0 || pParse->db->mallocFailed ) 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; } pEList = pSelect->pEList; + if( pEList==0 ){ + return 0; + } for(i=0; i<pOrderBy->nExpr; i++){ - struct ExprList_item *pItem; + int iCol; Expr *pE = pOrderBy->a[i].pExpr; - int iCol = -1; - char *zLabel; - - if( pOrderBy->a[i].done ) continue; - if( sqlite3ExprIsInteger(pE, &iCol) ){ - if( iCol<=0 || iCol>pEList->nExpr ){ - sqlite3ErrorMsg(pParse, - "ORDER BY position %d should be between 1 and %d", - iCol, pEList->nExpr); - nErr++; - break; - } - if( !mustComplete ) continue; - iCol--; - } - if( iCol<0 && (zLabel = sqlite3NameFromToken(db, &pE->token))!=0 ){ - for(j=0, pItem=pEList->a; j<pEList->nExpr; j++, pItem++){ - char *zName; - int isMatch; - if( pItem->zName ){ - zName = sqlite3DbStrDup(db, pItem->zName); - }else{ - zName = sqlite3NameFromToken(db, &pItem->pExpr->token); - } - isMatch = zName && sqlite3StrICmp(zName, zLabel)==0; - sqlite3_free(zName); - if( isMatch ){ - iCol = j; - break; - } - } - sqlite3_free(zLabel); - } - if( iCol>=0 ){ - pE->op = TK_COLUMN; - pE->iColumn = iCol; - pE->iTable = iTable; - pE->iAgg = -1; - pOrderBy->a[i].done = 1; - }else if( mustComplete ){ + 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, - "ORDER BY term number %d does not match any result column", i+1); - nErr++; - break; - } - } - return nErr; -} -#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */ + "%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; + int flags = pE->flags & EP_ExpCollate; + sqlite3ExprDelete(pE); + pE = sqlite3ExprDup(db, pEList->a[iCol-1].pExpr); + pOrderBy->a[i].pExpr = pE; + if( pE && pColl && flags ){ + pE->pColl = pColl; + pE->flags |= flags; + } + } + } + return 0; +} + +/* +** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return +** the number of errors seen. +** +** 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. +** +** 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 */ + int iTable /* Output table for compound SELECT statements */ +){ + int i; + ExprList *pOrderBy; + ExprList *pEList; + sqlite3 *db; + int moreToDo = 1; + + pOrderBy = pSelect->pOrderBy; + if( pOrderBy==0 ) return 0; + if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ + sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause"); + return 1; + } + db = pParse->db; + for(i=0; i<pOrderBy->nExpr; i++){ + pOrderBy->a[i].done = 0; + } + while( pSelect->pPrior ){ + pSelect = pSelect->pPrior; + } + while( pSelect && moreToDo ){ + moreToDo = 0; + for(i=0; i<pOrderBy->nExpr; i++){ + int iCol = -1; + Expr *pE, *pDup; + if( pOrderBy->a[i].done ) continue; + pE = pOrderBy->a[i].pExpr; + 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; + } + 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_COLUMN; + pE->iTable = iTable; + pE->iAgg = -1; + pE->iColumn = iCol-1; + pE->pTab = 0; + pOrderBy->a[i].done = 1; + }else{ + moreToDo = 1; + } + } + pSelect = pSelect->pNext; + } + for(i=0; i<pOrderBy->nExpr; i++){ + if( pOrderBy->a[i].done==0 ){ + sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any " + "column in the result set", i+1); + return 1; + } + } + return 0; +} /* ** Get a VDBE for the given parser context. Create a new one if necessary. ** If an error occurs, return NULL and leave a message in pParse. */ 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; } @@ -59518,55 +61535,47 @@ */ static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){ Vdbe *v = 0; int iLimit = 0; int iOffset; - int addr1, addr2; + int addr1; /* ** "LIMIT -1" always shows all rows. There is some ** contraversy about what the correct behavior should be. ** The current implementation interprets "LIMIT 0" to mean ** no rows. */ if( p->pLimit ){ - p->iLimit = iLimit = pParse->nMem; - pParse->nMem += 2; + p->iLimit = iLimit = ++pParse->nMem; v = sqlite3GetVdbe(pParse); if( v==0 ) return; - 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); + sqlite3ExprCode(pParse, p->pLimit, iLimit); + sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); + VdbeComment((v, "LIMIT counter")); + sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); } if( p->pOffset ){ - p->iOffset = iOffset = pParse->nMem++; + p->iOffset = iOffset = ++pParse->nMem; + if( p->pLimit ){ + pParse->nMem++; /* Allocate an extra register for limit+offset */ + } v = sqlite3GetVdbe(pParse); if( v==0 ) return; - 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); + 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); sqlite3VdbeJumpHere(v, addr1); if( p->pLimit ){ - 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); + 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); + } } } /* ** Allocate a virtual index to use for sorting. @@ -59574,11 +61583,11 @@ 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, + addr = sqlite3VdbeAddOp2(pParse->pVdbe, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+1); assert( p->addrOpenEphm[2] == -1 ); p->addrOpenEphm[2] = addr; } } @@ -59638,21 +61647,23 @@ ** individual selects always group from left to right. */ static int multiSelect( Parse *pParse, /* Parsing context */ Select *p, /* The right-most of SELECTs to be coded */ - int eDest, /* \___ Store query results as specified */ - int iParm, /* / by these two parameters. */ + SelectDest *pDest, /* What to do with query results */ 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 */ 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 */ + SelectDest dest; /* Alternative data destination */ + + dest = *pDest; /* 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. */ if( p==0 || p->pPrior==0 ){ @@ -59683,15 +61694,15 @@ goto multi_select_end; } /* Create the destination temporary table if necessary */ - if( eDest==SRT_EphemTab ){ + if( dest.eDest==SRT_EphemTab ){ assert( p->pEList ); assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); - aSetP2[nSetP2++] = sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, 0); - eDest = SRT_Table; + aSetP2[nSetP2++] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, 0); + dest.eDest = SRT_Table; } /* Generate code for the left and right SELECT statements. */ pOrderBy = p->pOrderBy; @@ -59700,24 +61711,24 @@ 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); + rc = sqlite3Select(pParse, pPrior, &dest, 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); + addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); + VdbeComment((v, "Jump ahead if LIMIT reached")); + } + rc = sqlite3Select(pParse, p, &dest, 0, 0, 0, aff); p->pPrior = pPrior; if( rc ){ goto multi_select_end; } if( addr ){ @@ -59732,27 +61743,28 @@ 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 = p->op==TK_ALL ? SRT_Table : SRT_Union; - if( eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ + if( dest.eDest==priorOp && pOrderBy==0 && !p->pLimit && !p->pOffset ){ /* We can reuse a temporary table generated by a SELECT to our ** right. */ - unionTab = iParm; + unionTab = dest.iParm; }else{ /* We will need to create our own temporary table to hold the ** intermediate results. */ unionTab = pParse->nTab++; - if( pOrderBy && matchOrderbyToColumn(pParse, p, pOrderBy, unionTab,1) ){ + if( processCompoundOrderBy(pParse, p, unionTab) ){ rc = 1; goto multi_select_end; } - addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, unionTab, 0); + addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0); if( priorOp==SRT_Table ){ assert( nSetP2<sizeof(aSetP2)/sizeof(aSetP2[0]) ); aSetP2[nSetP2++] = addr; }else{ assert( p->addrOpenEphm[0] == -1 ); @@ -59764,11 +61776,12 @@ } /* Code the SELECT statements to our left */ assert( !pPrior->pOrderBy ); - rc = sqlite3Select(pParse, pPrior, priorOp, unionTab, 0, 0, 0, aff); + sqlite3SelectDestInit(&uniondest, priorOp, unionTab); + rc = sqlite3Select(pParse, pPrior, &uniondest, 0, 0, 0, aff); if( rc ){ goto multi_select_end; } /* Code the current SELECT statement @@ -59783,11 +61796,12 @@ 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); + uniondest.eDest = op; + rc = sqlite3Select(pParse, p, &uniondest, 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; @@ -59802,79 +61816,78 @@ /* Convert the data in the temporary table into whatever form ** it is that we currently need. */ - if( eDest!=priorOp || unionTab!=iParm ){ + if( dest.eDest!=priorOp || unionTab!=dest.iParm ){ int iCont, iBreak, iStart; assert( p->pEList ); - if( eDest==SRT_Callback ){ + 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); - sqlite3VdbeAddOp(v, OP_Rewind, unionTab, iBreak); + sqlite3VdbeAddOp2(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; - } + selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr, + pOrderBy, -1, &dest, iCont, iBreak, 0); sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp(v, OP_Next, unionTab, iStart); + sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp(v, OP_Close, unionTab, 0); + 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++; - if( pOrderBy && matchOrderbyToColumn(pParse,p,pOrderBy,tab1,1) ){ + if( processCompoundOrderBy(pParse, p, tab1) ){ rc = 1; goto multi_select_end; } createSortingIndex(pParse, p, pOrderBy); - addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, tab1, 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". */ - rc = sqlite3Select(pParse, pPrior, SRT_Union, tab1, 0, 0, 0, aff); + sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1); + rc = sqlite3Select(pParse, pPrior, &intersectdest, 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); + 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; - rc = sqlite3Select(pParse, p, SRT_Union, tab2, 0, 0, 0, aff); + intersectdest.iParm = tab2; + rc = sqlite3Select(pParse, p, &intersectdest, 0, 0, 0, aff); p->pPrior = pPrior; sqlite3ExprDelete(p->pLimit); p->pLimit = pLimit; p->pOffset = pOffset; if( rc ){ @@ -59883,33 +61896,30 @@ /* Generate code to take the intersection of the two temporary ** tables. */ assert( p->pEList ); - if( eDest==SRT_Callback ){ + 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); - 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; - } + 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, + pOrderBy, -1, &dest, iCont, iBreak, 0); sqlite3VdbeResolveLabel(v, iCont); - sqlite3VdbeAddOp(v, OP_Next, tab1, iStart); + sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); sqlite3VdbeResolveLabel(v, iBreak); - sqlite3VdbeAddOp(v, OP_Close, tab2, 0); - sqlite3VdbeAddOp(v, OP_Close, tab1, 0); + sqlite3VdbeAddOp2(v, OP_Close, tab2, 0); + sqlite3VdbeAddOp2(v, OP_Close, tab1, 0); break; } } /* Make sure all SELECTs in the statement have the same number of elements @@ -59975,11 +61985,11 @@ ** always safely abort as soon as the first unused slot is found */ assert( pLoop->addrOpenEphm[1]<0 ); break; } sqlite3VdbeChangeP2(v, addr, nCol); - sqlite3VdbeChangeP3(v, addr, (char*)pKeyInfo, P3_KEYINFO); + sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO); pLoop->addrOpenEphm[i] = -1; } } if( pOrderBy ){ @@ -60019,19 +62029,20 @@ 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); + sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO_HANDOFF); pKeyInfo = 0; - generateSortTail(pParse, p, v, p->pEList->nExpr, eDest, iParm); + generateSortTail(pParse, p, v, p->pEList->nExpr, &dest); } sqlite3_free(pKeyInfo); } multi_select_end: + pDest->iMem = dest.iMem; return rc; } #endif /* SQLITE_OMIT_COMPOUND_SELECT */ #ifndef SQLITE_OMIT_VIEW @@ -60398,216 +62409,36 @@ return 1; } #endif /* SQLITE_OMIT_VIEW */ /* -** 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; -** -** A simply min() or max() query looks like this: -** -** 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 simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){ +** Analyze the SELECT statement passed as an argument to see if it +** is a min() or max() query. Return ORDERBY_MIN or ORDERBY_MAX if +** it is, or 0 otherwise. At present, a query is considered to be +** a min()/max() query if: +** +** 1. There is a single object in the FROM clause. +** +** 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. +*/ +static int minMaxQuery(Parse *pParse, Select *p){ Expr *pExpr; - 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; - - /* 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; + ExprList *pEList = p->pEList; + + if( pEList->nExpr!=1 ) return ORDERBY_NORMAL; pExpr = pEList->a[0].pExpr; - 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; + 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 ORDERBY_NORMAL; + if( pExpr->token.n!=3 ) return ORDERBY_NORMAL; if( sqlite3StrNICmp((char*)pExpr->token.z,"min",3)==0 ){ - seekOp = OP_Rewind; + return ORDERBY_MIN; }else if( sqlite3StrNICmp((char*)pExpr->token.z,"max",3)==0 ){ - seekOp = OP_Last; - }else{ - return 0; - } - 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; -} - -/* -** Analyze and ORDER BY or GROUP BY clause in a SELECT statement. Return -** the number of errors seen. -** -** An ORDER BY or GROUP BY is a list of expressions. If any expression -** is an integer constant, then that expression is replaced by the -** corresponding entry in the result set. -*/ -static int processOrderGroupBy( - NameContext *pNC, /* Name context of the SELECT statement. */ - ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */ - const char *zType /* Either "ORDER" or "GROUP", as appropriate */ -){ - int i; - ExprList *pEList = pNC->pEList; /* The result set of the SELECT */ - Parse *pParse = pNC->pParse; /* The result set of the SELECT */ - assert( pEList ); - - if( pOrderBy==0 ) return 0; - if( pOrderBy->nExpr>SQLITE_MAX_COLUMN ){ - sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType); - return 1; - } - for(i=0; i<pOrderBy->nExpr; i++){ - int iCol; - Expr *pE = pOrderBy->a[i].pExpr; - if( sqlite3ExprIsInteger(pE, &iCol) ){ - if( iCol>0 && iCol<=pEList->nExpr ){ - CollSeq *pColl = pE->pColl; - int flags = pE->flags & EP_ExpCollate; - sqlite3ExprDelete(pE); - pE = sqlite3ExprDup(pParse->db, pEList->a[iCol-1].pExpr); - pOrderBy->a[i].pExpr = pE; - if( pColl && flags ){ - pE->pColl = pColl; - pE->flags |= flags; - } - }else{ - sqlite3ErrorMsg(pParse, - "%s BY column number %d out of range - should be " - "between 1 and %d", zType, iCol, pEList->nExpr); - return 1; - } - } - if( sqlite3ExprResolveNames(pNC, pE) ){ - return 1; - } - } - return 0; + return ORDERBY_MAX; + } + return ORDERBY_NORMAL; } /* ** This routine resolves any names used in the result set of the ** supplied SELECT statement. If the SELECT statement being resolved @@ -60700,14 +62531,16 @@ if( sqlite3ExprResolveNames(&sNC, p->pWhere) || sqlite3ExprResolveNames(&sNC, p->pHaving) ){ return SQLITE_ERROR; } if( p->pPrior==0 ){ - if( processOrderGroupBy(&sNC, p->pOrderBy, "ORDER") || - processOrderGroupBy(&sNC, pGroupBy, "GROUP") ){ + if( processOrderGroupBy(pParse, p, p->pOrderBy, 1, &sNC.hasAgg) ){ return SQLITE_ERROR; } + } + if( processOrderGroupBy(pParse, p, pGroupBy, 0, &sNC.hasAgg) ){ + return SQLITE_ERROR; } if( pParse->db->mallocFailed ){ return SQLITE_NOMEM; } @@ -60749,24 +62582,24 @@ struct AggInfo_func *pFunc; if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){ return; } for(i=0; i<pAggInfo->nColumn; i++){ - sqlite3VdbeAddOp(v, OP_MemNull, pAggInfo->aCol[i].iMem, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem); } for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){ - sqlite3VdbeAddOp(v, OP_MemNull, pFunc->iMem, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem); if( pFunc->iDistinct>=0 ){ Expr *pE = pFunc->pExpr; if( pE->pList==0 || pE->pList->nExpr!=1 ){ sqlite3ErrorMsg(pParse, "DISTINCT in aggregate must be followed " "by an expression"); pFunc->iDistinct = -1; }else{ KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->pList); - sqlite3VdbeOp3(v, OP_OpenEphemeral, pFunc->iDistinct, 0, - (char*)pKeyInfo, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); } } } } @@ -60778,12 +62611,12 @@ Vdbe *v = pParse->pVdbe; int i; struct AggInfo_func *pF; for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ ExprList *pList = pF->pExpr->pList; - sqlite3VdbeOp3(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, - (void*)pF->pFunc, P3_FUNCDEF); + sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0, + (void*)pF->pFunc, P4_FUNCDEF); } } /* ** Update the accumulator memory cells for an aggregate based on @@ -60797,21 +62630,24 @@ pAggInfo->directMode = 1; for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){ int nArg; int addrNext = 0; + int regAgg; ExprList *pList = pF->pExpr->pList; if( pList ){ nArg = pList->nExpr; - sqlite3ExprCodeExprList(pParse, pList); + regAgg = sqlite3GetTempRange(pParse, nArg); + sqlite3ExprCodeExprList(pParse, pList, regAgg); }else{ nArg = 0; + regAgg = 0; } if( pF->iDistinct>=0 ){ addrNext = sqlite3VdbeMakeLabel(v); assert( nArg==1 ); - codeDistinct(v, pF->iDistinct, addrNext, 1); + codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg); } if( pF->pFunc->needCollSeq ){ CollSeq *pColl = 0; struct ExprList_item *pItem; int j; @@ -60820,48 +62656,90 @@ pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr); } if( !pColl ){ pColl = pParse->db->pDfltColl; } - sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ); - } - sqlite3VdbeOp3(v, OP_AggStep, pF->iMem, nArg, (void*)pF->pFunc, P3_FUNCDEF); + sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ); + } + sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem, + (void*)pF->pFunc, P4_FUNCDEF); + sqlite3VdbeChangeP5(v, nArg); + sqlite3ReleaseTempRange(pParse, regAgg, nArg); if( addrNext ){ sqlite3VdbeResolveLabel(v, addrNext); } } for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){ - sqlite3ExprCode(pParse, pC->pExpr); - sqlite3VdbeAddOp(v, OP_MemStore, pC->iMem, 1); + sqlite3ExprCode(pParse, pC->pExpr, pC->iMem); } pAggInfo->directMode = 0; } +#ifndef SQLITE_OMIT_TRIGGER +/* +** 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 && i<pEList->nExpr && i<32; i++){ + if( !(mask&((u32)1<<i)) ){ + sqlite3ExprDelete(pEList->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 -** value of eDest and iParm. -** -** eDest Value Result +** contents of the SelectDest structure pointed to by argument pDest +** as follows: +** +** pDest->eDest Result ** ------------ ------------------------------------------- ** SRT_Callback Invoke the callback for each row of the result. ** -** SRT_Mem Store first result in memory cell iParm -** -** SRT_Set Store results as keys of table iParm. -** -** SRT_Union Store results as a key in a temporary table iParm -** -** SRT_Except Remove results from the temporary table iParm. -** -** SRT_Table Store results in temporary table iParm -** -** 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. +** SRT_Mem Store first result in memory cell pDest->iParm +** +** SRT_Set Store non-null results as keys of table pDest->iParm. +** Apply the affinity pDest->affinity before storing them. +** +** SRT_Union Store results as a key in a temporary table pDest->iParm. +** +** SRT_Except Remove results from the temporary table pDest->iParm. +** +** SRT_Table Store results in temporary table pDest->iParm +** +** SRT_EphemTab Create an temporary table pDest->iParm and store +** the result there. The cursor is left open after +** returning. +** +** SRT_Subroutine For each row returned, push the results onto the +** vdbe stack and call the subroutine (via OP_Gosub) +** at address pDest->iParm. +** +** 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. ** ** This routine returns the number of errors. If any errors are ** encountered, then an appropriate error message is left in ** pParse->zErrMsg. ** @@ -60890,12 +62768,11 @@ ** be 1 (the 2nd value of a 0-indexed array.) */ SQLITE_PRIVATE int sqlite3Select( Parse *pParse, /* The parser context */ Select *p, /* The SELECT statement being coded. */ - int eDest, /* How to dispose of the results */ - int iParm, /* A parameter used by the eDest disposal method */ + SelectDest *pDest, /* What to do with the query results */ 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 */ char *aff /* If eDest is SRT_Union, the affinity string */ ){ @@ -60922,37 +62799,46 @@ return 1; } if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1; memset(&sAggInfo, 0, sizeof(sAggInfo)); + pOrderBy = p->pOrderBy; + if( IgnorableOrderby(pDest) ){ + 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; + 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 - - pOrderBy = p->pOrderBy; - if( IgnorableOrderby(eDest) ){ - p->pOrderBy = 0; - } - if( sqlite3SelectResolve(pParse, p, 0) ){ - goto select_end; - } - p->pOrderBy = pOrderBy; + return multiSelect(pParse, p, pDest, aff); + } +#endif /* Make local copies of the parameters for this query. */ pTabList = p->pSrc; pWhere = p->pWhere; @@ -60971,18 +62857,18 @@ /* 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) ){ + if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){ goto select_end; } #endif /* ORDER BY is ignored for some destinations. */ - if( IgnorableOrderby(eDest) ){ + if( IgnorableOrderby(pDest) ){ pOrderBy = 0; } /* Begin generating code. */ @@ -60994,10 +62880,11 @@ #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) for(i=0; i<pTabList->nSrc; i++){ const char *zSavedAuthContext = 0; int needRestoreContext; struct SrcList_item *pItem = &pTabList->a[i]; + SelectDest dest; if( pItem->pSelect==0 || pItem->isPopulated ) continue; if( pItem->zName!=0 ){ zSavedAuthContext = pParse->zAuthContext; pParse->zAuthContext = pItem->zName; @@ -61013,12 +62900,12 @@ ** more conservative than necessary, but much easier than enforcing ** an exact limit. */ pParse->nHeight += sqlite3SelectExprHeight(p); #endif - sqlite3Select(pParse, pItem->pSelect, SRT_EphemTab, - pItem->iCursor, p, i, &isAgg, 0); + sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor); + sqlite3Select(pParse, pItem->pSelect, &dest, p, i, &isAgg, 0); if( db->mallocFailed ){ goto select_end; } #if defined(SQLITE_TEST) || SQLITE_MAX_EXPR_DEPTH>0 pParse->nHeight -= sqlite3SelectExprHeight(p); @@ -61026,11 +62913,11 @@ if( needRestoreContext ){ pParse->zAuthContext = zSavedAuthContext; } pTabList = p->pSrc; pWhere = p->pWhere; - if( !IgnorableOrderby(eDest) ){ + if( !IgnorableOrderby(pDest) ){ pOrderBy = p->pOrderBy; } pGroupBy = p->pGroupBy; pHaving = p->pHaving; isDistinct = p->isDistinct; @@ -61038,14 +62925,16 @@ #endif /* Check for the special case of a min() or max() function by itself ** in the result set. */ - if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){ +#if 0 + if( simpleMinMaxQuery(pParse, p, pDest) ){ rc = 0; goto select_end; } +#endif /* 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 @@ -61073,25 +62962,24 @@ ** we figure out that the sorting index is not needed. The addrSortIndex ** variable is used to facilitate that change. */ if( pOrderBy ){ KeyInfo *pKeyInfo; - if( pParse->nErr ){ - goto select_end; - } pKeyInfo = keyInfoFromExprList(pParse, pOrderBy); pOrderBy->iECursor = pParse->nTab++; p->addrOpenEphm[2] = addrSortIndex = - sqlite3VdbeOp3(v, OP_OpenEphemeral, pOrderBy->iECursor, pOrderBy->nExpr+2, (char*)pKeyInfo, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, + pOrderBy->iECursor, pOrderBy->nExpr+2, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); }else{ addrSortIndex = -1; } /* If the output is destined for a temporary table, open that table. */ - if( eDest==SRT_EphemTab ){ - sqlite3VdbeAddOp(v, OP_OpenEphemeral, iParm, pEList->nExpr); + if( pDest->eDest==SRT_EphemTab ){ + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr); } /* Set the limiter. */ iEnd = sqlite3VdbeMakeLabel(v); @@ -61102,22 +62990,22 @@ if( isDistinct ){ KeyInfo *pKeyInfo; assert( isAgg || pGroupBy ); distinct = pParse->nTab++; pKeyInfo = keyInfoFromExprList(pParse, p->pEList); - sqlite3VdbeOp3(v, OP_OpenEphemeral, distinct, 0, - (char*)pKeyInfo, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); }else{ distinct = -1; } /* Aggregate and non-aggregate queries are handled differently */ if( !isAgg && pGroupBy==0 ){ /* This case is for non-aggregate queries ** Begin the database scan */ - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0); if( pWInfo==0 ) goto select_end; /* If sorting index that was created by a prior OP_OpenEphemeral ** instruction ended up not being needed, then change the OP_OpenEphemeral ** into an OP_Noop. @@ -61128,14 +63016,12 @@ } /* Use the standard inner loop */ assert(!isDistinct); - if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, eDest, - iParm, pWInfo->iContinue, pWInfo->iBreak, aff) ){ - goto select_end; - } + selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest, + pWInfo->iContinue, pWInfo->iBreak, aff); /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); }else{ @@ -61172,24 +63058,18 @@ sNC.pParse = pParse; sNC.pSrcList = pTabList; sNC.pAggInfo = &sAggInfo; sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0; sAggInfo.pGroupBy = pGroupBy; - if( sqlite3ExprAnalyzeAggList(&sNC, pEList) ){ - goto select_end; - } - if( sqlite3ExprAnalyzeAggList(&sNC, pOrderBy) ){ - goto select_end; - } - if( pHaving && sqlite3ExprAnalyzeAggregates(&sNC, pHaving) ){ - goto select_end; + sqlite3ExprAnalyzeAggList(&sNC, pEList); + sqlite3ExprAnalyzeAggList(&sNC, pOrderBy); + if( pHaving ){ + sqlite3ExprAnalyzeAggregates(&sNC, pHaving); } sAggInfo.nAccumulator = sAggInfo.nColumn; for(i=0; i<sAggInfo.nFunc; i++){ - if( sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList) ){ - goto select_end; - } + sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->pList); } if( db->mallocFailed ) goto select_end; /* Processing for aggregates with GROUP BY is very different and ** much more complex than aggregates without a GROUP BY. @@ -61210,70 +63090,67 @@ ** will be converted into a Noop. */ sAggInfo.sortingIdx = pParse->nTab++; pKeyInfo = keyInfoFromExprList(pParse, pGroupBy); addrSortingIdx = - sqlite3VdbeOp3(v, OP_OpenEphemeral, sAggInfo.sortingIdx, - sAggInfo.nSortingColumn, - (char*)pKeyInfo, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp4(v, OP_OpenEphemeral, sAggInfo.sortingIdx, + sAggInfo.nSortingColumn, 0, + (char*)pKeyInfo, P4_KEYINFO_HANDOFF); /* Initialize memory locations used by GROUP BY aggregate processing */ - iUseFlag = pParse->nMem++; - iAbortFlag = pParse->nMem++; - iAMem = pParse->nMem; + iUseFlag = ++pParse->nMem; + iAbortFlag = ++pParse->nMem; + iAMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; - iBMem = pParse->nMem; + iBMem = pParse->nMem + 1; pParse->nMem += pGroupBy->nExpr; - 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); + 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); /* Generate a subroutine that outputs a single row of the result ** set. This subroutine first looks at the iUseFlag. If iUseFlag ** is less than or equal to zero, the subroutine is a no-op. If ** the processing calls for the query to abort, this subroutine ** increments the iAbortFlag memory location before returning in ** order to signal the caller to abort. */ addrSetAbort = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp(v, OP_MemInt, 1, iAbortFlag); - VdbeComment((v, "# set abort flag")); - sqlite3VdbeAddOp(v, OP_Return, 0, 0); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag); + VdbeComment((v, "set abort flag")); + sqlite3VdbeAddOp2(v, OP_Return, 0, 0); addrOutputRow = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp(v, OP_IfMemPos, iUseFlag, addrOutputRow+2); - VdbeComment((v, "# Groupby result generator entry point")); - sqlite3VdbeAddOp(v, OP_Return, 0, 0); + sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); + VdbeComment((v, "Groupby result generator entry point")); + sqlite3VdbeAddOp2(v, OP_Return, 0, 0); finalizeAggFunctions(pParse, &sAggInfo); if( pHaving ){ - sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, 1); - } - 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")); + sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL); + } + selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy, + distinct, pDest, + addrOutputRow+1, addrSetAbort, aff); + sqlite3VdbeAddOp2(v, OP_Return, 0, 0); + VdbeComment((v, "end groupby result generator")); /* Generate a subroutine that will reset the group-by accumulator */ addrReset = sqlite3VdbeCurrentAddr(v); resetAccumulator(pParse, &sAggInfo); - sqlite3VdbeAddOp(v, OP_Return, 0, 0); + sqlite3VdbeAddOp2(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 ** it might be a single loop that uses an index to extract information ** in the right order to begin with. */ sqlite3VdbeResolveLabel(v, addrInitializeLoop); - sqlite3VdbeAddOp(v, OP_Gosub, 0, addrReset); - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy); + sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0); if( pWInfo==0 ) goto select_end; if( pGroupBy==0 ){ /* The optimizer is able to deliver rows in group by order so ** we do not have to sort. The OP_OpenEphemeral table will be ** cancelled later because we still need to use the pKeyInfo @@ -61284,25 +63161,45 @@ /* Rows are coming out in undetermined order. We have to push ** each row into a sorting index, terminate the first loop, ** 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; - sqlite3ExprCodeExprList(pParse, pGroupBy); - sqlite3VdbeAddOp(v, OP_Sequence, sAggInfo.sortingIdx, 0); - j = pGroupBy->nExpr+1; + nGroupBy = pGroupBy->nExpr; + nCol = nGroupBy + 1; + j = nGroupBy+1; + for(i=0; i<sAggInfo.nColumn; i++){ + if( sAggInfo.aCol[i].iSorterColumn>=j ){ + nCol++; + j++; + } + } + regBase = sqlite3GetTempRange(pParse, nCol); + sqlite3ExprCodeExprList(pParse, pGroupBy, regBase); + sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy); + j = nGroupBy+1; for(i=0; i<sAggInfo.nColumn; i++){ struct AggInfo_col *pCol = &sAggInfo.aCol[i]; - if( pCol->iSorterColumn<j ) continue; - sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable); - j++; - } - sqlite3VdbeAddOp(v, OP_MakeRecord, j, 0); - sqlite3VdbeAddOp(v, OP_IdxInsert, sAggInfo.sortingIdx, 0); + if( pCol->iSorterColumn>=j ){ + sqlite3ExprCodeGetColumn(v, pCol->pTab, pCol->iColumn, pCol->iTable, + j + regBase); + 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); sqlite3WhereEnd(pWInfo); - sqlite3VdbeAddOp(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); - VdbeComment((v, "# GROUP BY sort")); + sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd); + VdbeComment((v, "GROUP BY sort")); sAggInfo.useSortingIdx = 1; } /* Evaluate the current GROUP BY terms and store in b0, b1, b2... ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth) @@ -61310,28 +63207,24 @@ ** from the previous row currently stored in a0, a1, a2... */ addrTopOfLoop = sqlite3VdbeCurrentAddr(v); for(j=0; j<pGroupBy->nExpr; j++){ if( groupBySort ){ - sqlite3VdbeAddOp(v, OP_Column, sAggInfo.sortingIdx, j); + sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j); }else{ sAggInfo.directMode = 1; - sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr); - } - sqlite3VdbeAddOp(v, OP_MemStore, iBMem+j, j<pGroupBy->nExpr-1); + sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j); + } } for(j=pGroupBy->nExpr-1; j>=0; j--){ - if( j<pGroupBy->nExpr-1 ){ - sqlite3VdbeAddOp(v, OP_MemLoad, iBMem+j, 0); - } - sqlite3VdbeAddOp(v, OP_MemLoad, iAMem+j, 0); if( j==0 ){ - sqlite3VdbeAddOp(v, OP_Eq, 0x200, addrProcessRow); + sqlite3VdbeAddOp3(v, OP_Eq, iAMem+j, addrProcessRow, iBMem+j); }else{ - sqlite3VdbeAddOp(v, OP_Ne, 0x200, addrGroupByChange); - } - sqlite3VdbeChangeP3(v, -1, (void*)pKeyInfo->aColl[j], P3_COLLSEQ); + sqlite3VdbeAddOp3(v, OP_Ne, iAMem+j, addrGroupByChange, iBMem+j); + } + sqlite3VdbeChangeP4(v, -1, (void*)pKeyInfo->aColl[j], P4_COLLSEQ); + sqlite3VdbeChangeP5(v, SQLITE_NULLEQUAL); } /* Generate code that runs whenever the GROUP BY changes. ** Change in the GROUP BY are detected by the previous code ** block. If there were no changes, this block is skipped. @@ -61341,69 +63234,116 @@ ** and resets the aggregate accumulator registers in preparation ** for the next GROUP BY batch. */ sqlite3VdbeResolveLabel(v, addrGroupByChange); for(j=0; j<pGroupBy->nExpr; 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")); + sqlite3VdbeAddOp2(v, OP_Move, iBMem+j, iAMem+j); + } + sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrOutputRow); + VdbeComment((v, "output one row")); + sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); + VdbeComment((v, "check abort flag")); + sqlite3VdbeAddOp2(v, OP_Gosub, 0, addrReset); + VdbeComment((v, "reset accumulator")); /* Update the aggregate accumulators based on the content of ** the current row */ sqlite3VdbeResolveLabel(v, addrProcessRow); updateAccumulator(pParse, &sAggInfo); - sqlite3VdbeAddOp(v, OP_MemInt, 1, iUseFlag); - VdbeComment((v, "# indicate data in accumulator")); + sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag); + VdbeComment((v, "indicate data in accumulator")); /* End of the loop */ if( groupBySort ){ - sqlite3VdbeAddOp(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); + sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop); }else{ sqlite3WhereEnd(pWInfo); sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1); } /* Output the final row of result */ - sqlite3VdbeAddOp(v, OP_Gosub, 0, addrOutputRow); - VdbeComment((v, "# output final row")); + sqlite3VdbeAddOp2(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==ORDERBY_MIN)?0:1); + 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, 0); - if( pWInfo==0 ) goto select_end; + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag); + if( pWInfo==0 ){ + sqlite3ExprListDelete(pDel); + goto select_end; + } updateAccumulator(pParse, &sAggInfo); + if( !pMinMax && flag ){ + sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak); + VdbeComment((v, "%s() by index", (flag==ORDERBY_MIN?"min":"max"))); + } sqlite3WhereEnd(pWInfo); finalizeAggFunctions(pParse, &sAggInfo); pOrderBy = 0; if( pHaving ){ - sqlite3ExprIfFalse(pParse, pHaving, addrEnd, 1); + sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL); } selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, - eDest, iParm, addrEnd, addrEnd, aff); + pDest, addrEnd, addrEnd, aff); + + sqlite3ExprListDelete(pDel); } sqlite3VdbeResolveLabel(v, addrEnd); } /* endif aggregate query */ /* If there is an ORDER BY clause, then we need to sort the results ** and send them to the callback one by one. */ if( pOrderBy ){ - generateSortTail(pParse, p, v, pEList->nExpr, eDest, iParm); + generateSortTail(pParse, p, v, pEList->nExpr, pDest); } #ifndef SQLITE_OMIT_SUBQUERY /* If this was a subquery, we have now converted the subquery into a ** temporary table. So set the SrcList_item.isPopulated flag to prevent @@ -61432,11 +63372,11 @@ 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 && eDest==SRT_Callback ){ + if( rc==SQLITE_OK && pDest->eDest==SRT_Callback ){ generateColumnNames(pParse, pTabList, pEList); } sqlite3_free(sAggInfo.aCol); sqlite3_free(sAggInfo.aFunc); @@ -61608,21 +63548,19 @@ ** the names of all columns. */ if( p->nRow==0 ){ p->nColumn = nCol; for(i=0; i<nCol; i++){ - if( colv[i]==0 ){ - z = sqlite3_mprintf(""); - }else{ - z = sqlite3_mprintf("%s", colv[i]); - } + z = sqlite3_mprintf("%s", colv[i]); + if( z==0 ) goto malloc_failed; p->azResult[p->nData++] = z; } }else if( p->nColumn!=nCol ){ - sqlite3SetString(&p->zErrMsg, - "sqlite3_get_table() called with two or more incompatible queries", - (char*)0); + sqlite3_free(p->zErrMsg); + p->zErrMsg = sqlite3_mprintf( + "sqlite3_get_table() called with two or more incompatible queries" + ); p->rc = SQLITE_ERROR; return 1; } /* Copy over the row data @@ -61666,11 +63604,11 @@ int *pnColumn, /* Write the number of columns of result here */ char **pzErrMsg /* Write error messages here */ ){ int rc; TabResult res; - if( pazResult==0 ){ return SQLITE_ERROR; } + *pazResult = 0; if( pnColumn ) *pnColumn = 0; if( pnRow ) *pnRow = 0; res.zErrMsg = 0; res.nResult = 0; @@ -61677,35 +63615,29 @@ res.nRow = 0; res.nColumn = 0; res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; - res.azResult = sqlite3_malloc( sizeof(char*)*res.nAlloc ); - if( res.azResult==0 ) return SQLITE_NOMEM; + res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc ); + if( res.azResult==0 ){ + db->errCode = SQLITE_NOMEM; + return SQLITE_NOMEM; + } res.azResult[0] = 0; rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg); -#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; - } + 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 ){ if( pzErrMsg ){ sqlite3_free(*pzErrMsg); *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); } sqlite3_free(res.zErrMsg); } - sqlite3_mutex_enter(db->mutex); - db->errCode = res.rc; - sqlite3_mutex_leave(db->mutex); + db->errCode = res.rc; /* Assume 32-bit assignment is atomic */ return res.rc; } sqlite3_free(res.zErrMsg); if( rc!=SQLITE_OK ){ sqlite3_free_table(&res.azResult[1]); @@ -61714,10 +63646,11 @@ if( res.nAlloc>res.nData ){ char **azNew; 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; res.azResult = azNew; } @@ -61734,11 +63667,11 @@ char **azResult /* Result returned from from sqlite3_get_table() */ ){ if( azResult ){ int i, n; azResult--; - if( azResult==0 ) return; + assert( azResult!=0 ); n = (int)azResult[0]; for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); } sqlite3_free(azResult); } } @@ -61973,38 +63906,26 @@ /* if we are not initializing, and this trigger is not on a TEMP table, ** build the sqlite_master entry */ if( !db->init.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); - 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 + 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 ); } if( db->init.busy ){ int n; @@ -62281,27 +64202,28 @@ assert( pTable!=0 ); if( (v = sqlite3GetVdbe(pParse))!=0 ){ int base; static const VdbeOpList dropTrigger[] = { { OP_Rewind, 0, ADDR(9), 0}, - { 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_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_Delete, 0, 0, 0}, { OP_Next, 0, ADDR(1), 0}, /* 8 */ }; sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3OpenMasterTable(pParse, iDb); base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger); - 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); + 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); } } /* ** Remove a trigger from the hash tables of the sqlite* pointer. @@ -62422,62 +64344,65 @@ Vdbe *v = pParse->pVdbe; sqlite3 *db = pParse->db; assert( pTriggerStep!=0 ); assert( v!=0 ); - sqlite3VdbeAddOp(v, OP_ContextPush, 0, 0); - VdbeComment((v, "# begin trigger %s", pStepList->pTrig->name)); + sqlite3VdbeAddOp2(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; switch( pTriggerStep->op ){ 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, SRT_Discard, 0, 0, 0, 0, 0); + sqlite3Select(pParse, ss, &dest, 0, 0, 0, 0); sqlite3SelectDelete(ss); } break; } case TK_UPDATE: { SrcList *pSrc; pSrc = targetSrcList(pParse, pTriggerStep); - sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0); + sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db, pTriggerStep->pExprList), sqlite3ExprDup(db, pTriggerStep->pWhere), orconf); - sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0); + sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); break; } case TK_INSERT: { SrcList *pSrc; pSrc = targetSrcList(pParse, pTriggerStep); - sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0); + sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); sqlite3Insert(pParse, pSrc, sqlite3ExprListDup(db, pTriggerStep->pExprList), sqlite3SelectDup(db, pTriggerStep->pSelect), sqlite3IdListDup(db, pTriggerStep->pIdList), orconf); - sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0); + sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); break; } case TK_DELETE: { SrcList *pSrc; - sqlite3VdbeAddOp(v, OP_ResetCount, 0, 0); + sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0); pSrc = targetSrcList(pParse, pTriggerStep); sqlite3DeleteFrom(pParse, pSrc, sqlite3ExprDup(db, pTriggerStep->pWhere)); - sqlite3VdbeAddOp(v, OP_ResetCount, 1, 0); + sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0); break; } default: assert(0); } pTriggerStep = pTriggerStep->pNext; } - sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0); - VdbeComment((v, "# end trigger %s", pStepList->pTrig->name)); + sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0); + VdbeComment((v, "end trigger %s", pStepList->pTrig->name)); return 0; } /* @@ -62497,10 +64422,17 @@ ** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then ** a temporary vdbe cursor (index oldIdx) must be open and pointing at ** 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 */ int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */ ExprList *pChanges, /* Changes list for any UPDATE OF triggers */ @@ -62507,23 +64439,28 @@ int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */ Table *pTab, /* The table to code triggers from */ 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) */ + 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 */ ){ 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 ); assert(newIdx != -1 || oldIdx != -1); for(p=pTab->pTrigger; p; p=p->pNext){ int fire_this = 0; - sqlite3 *db = pParse->db; /* Determine whether we should code this trigger */ if( p->op==op && p->tr_tm==tr_tm && @@ -62548,10 +64485,15 @@ int endTrigger; Expr * whenExpr; 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; /* Push an entry on to the trigger stack */ trigStackEntry.pTrigger = p; @@ -62569,11 +64511,11 @@ if( db->mallocFailed || sqlite3ExprResolveNames(&sNC, whenExpr) ){ pParse->trigStack = trigStackEntry.pNext; sqlite3ExprDelete(whenExpr); return 1; } - sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, 1); + sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL); sqlite3ExprDelete(whenExpr); codeTriggerProgram(pParse, p->step_list, orconf); /* Pop the entry off the trigger stack */ @@ -62581,10 +64523,12 @@ sqlite3AuthContextPop(&sContext); sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger); } } + if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask; + if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask; return 0; } #endif /* !defined(SQLITE_OMIT_TRIGGER) */ /************** End of trigger.c *********************************************/ @@ -62601,11 +64545,11 @@ ** ************************************************************************* ** This file contains C code routines that are called by the parser ** to handle UPDATE statements. ** -** $Id: update.c,v 1.141 2007/11/11 18:36:34 drh Exp $ +** $Id: update.c,v 1.170 2008/01/19 03:35:59 drh Exp $ */ #ifndef SQLITE_OMIT_VIRTUALTABLE /* Forward declaration */ static void updateVirtualTable( @@ -62619,44 +64563,44 @@ ); #endif /* SQLITE_OMIT_VIRTUALTABLE */ /* ** The most recently coded instruction was an OP_Column to retrieve the -** i-th column of table pTab. This routine sets the P3 parameter of the +** i-th column of table pTab. This routine sets the P4 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 ** column definition. This was either supplied by the user when the table ** 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 P3 parameter of the OP_Column instruction, is returned instead. +** from the P4 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 P3 value is not required. +** for the column and the P4 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 ** complicated default expression value was provided, it is evaluated ** when the ALTER TABLE is executed and one of the literal values written ** into the sqlite_master table.) ** -** Therefore, the P3 parameter is only required if the default value for +** Therefore, the P4 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. */ SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){ if( pTab && !pTab->pSelect ){ sqlite3_value *pValue; u8 enc = ENC(sqlite3VdbeDb(v)); Column *pCol = &pTab->aCol[i]; + VdbeComment((v, "%s.%s", pTab->zName, pCol->zName)); assert( i<pTab->nCol ); - sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, pCol->affinity, &pValue); + sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, + pCol->affinity, &pValue); if( pValue ){ - sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM); - }else{ - VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName)); + sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM); } } } /* @@ -62678,33 +64622,43 @@ int addr = 0; /* VDBE instruction address of the start of the loop */ WhereInfo *pWInfo; /* Information about the WHERE clause */ 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 */ - 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 *aRegIdx = 0; /* One register assigned to each index to be updated */ 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. */ int chngRowid; /* True if the record number is being changed */ Expr *pRowidExpr = 0; /* Expression defining the new record number */ int openAll = 0; /* True if all indices need to be opened */ AuthContext sContext; /* The authorization context */ NameContext sNC; /* The name-context to resolve expressions in */ int iDb; /* Database containing the table being updated */ - int memCnt = 0; /* Memory cell used for counting rows changed */ + int j1; /* Addresses of jump instructions */ #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 ){ goto update_cleanup; @@ -62807,45 +64761,51 @@ } } #endif } - /* 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=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){ - if( chngRowid ){ - i = 0; - }else { - for(i=0; i<pIdx->nColumn; i++){ - if( aXRef[pIdx->aiColumn[i]]>=0 ) break; - } - } - if( i<pIdx->nColumn ) nIdx++; - } - 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++){ + /* 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. + */ + 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; if( chngRowid ){ - i = 0; - }else{ + reg = ++pParse->nMem; + }else{ + reg = 0; for(i=0; i<pIdx->nColumn; i++){ - if( aXRef[pIdx->aiColumn[i]]>=0 ) break; - } - } - if( i<pIdx->nColumn ){ - apIdx[nIdx++] = pIdx; - aIdxUsed[j] = 1; - }else{ - aIdxUsed[j] = 0; - } - } + if( aXRef[pIdx->aiColumn[i]]>=0 ){ + reg = ++pParse->nMem; + break; + } + } + } + aRegIdx[j] = reg; + } + + /* 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++; + } + regData = regNewRowid+1; + /* Begin generating code. */ v = sqlite3GetVdbe(pParse); if( v==0 ) goto update_cleanup; @@ -62874,112 +64834,72 @@ */ 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_OpenPseudo, oldIdx, 0); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, oldIdx, pTab->nCol); + sqlite3VdbeAddOp2(v, OP_OpenPseudo, newIdx, 0); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, newIdx, pTab->nCol); + + 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 ){ Select *pView; + SelectDest dest; + pView = sqlite3SelectDup(db, pTab->pSelect); - sqlite3Select(pParse, pView, SRT_EphemTab, iCur, 0, 0, 0, 0); + sqlite3SelectMask(pParse, pView, old_col_mask|new_col_mask); + sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur); + sqlite3Select(pParse, pView, &dest, 0, 0, 0, 0); sqlite3SelectDelete(pView); } /* Begin the database scan */ - pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0); + pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0); if( pWInfo==0 ) goto update_cleanup; /* Remember the rowid of every item to be updated. */ - sqlite3VdbeAddOp(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid, iCur, 0); - sqlite3VdbeAddOp(v, OP_FifoWrite, 0, 0); + sqlite3VdbeAddOp2(v, IsVirtual(pTab) ? OP_VRowid : OP_Rowid,iCur,regOldRowid); + sqlite3VdbeAddOp2(v, OP_FifoWrite, regOldRowid, 0); /* End the database scan loop. */ sqlite3WhereEnd(pWInfo); /* Initialize the count of updated rows */ if( db->flags & SQLITE_CountRows && !pParse->trigStack ){ - memCnt = pParse->nMem++; - sqlite3VdbeAddOp(v, OP_MemInt, 0, memCnt); - } - - if( triggers_exist ){ - int mem1; /* Memory address storing the rowid for next row to update */ - - /* 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); - mem1 = pParse->nMem++; - 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_MoveGe, iCur, 0); - - /* 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; i<pTab->nCol; 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); - sqlite3VdbeAddOp(v, OP_Dup, 0, 0); - } + regRowCount = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount); } if( !isView && !IsVirtual(pTab) ){ /* ** Open every index that needs updating. Note that if any @@ -62998,133 +64918,191 @@ break; } } } for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){ - if( openAll || aIdxUsed[i] ){ + if( openAll || aRegIdx[i]>0 ){ KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx); - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); - sqlite3VdbeOp3(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, - (char*)pKey, P3_KEYINFO_HANDOFF); + sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb, + (char*)pKey, P4_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 */ + 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; i<pTab->nCol; i++){ + if( i==pTab->iPKey ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, regCols+i); + continue; + } + j = aXRef[i]; + if( new_col_mask&((u32)1<<i) || new_col_mask==0xffffffff ){ + if( j<0 ){ + sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regCols+i); + sqlite3ColumnDefault(v, pTab, i); + }else{ + sqlite3ExprCodeAndCache(pParse, pChanges->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); + } + 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. */ - if( !triggers_exist ){ - addr = sqlite3VdbeAddOp(v, OP_FifoRead, 0, 0); - sqlite3VdbeAddOp(v, OP_Dup, 0, 0); - } - sqlite3VdbeAddOp(v, OP_NotExists, iCur, addr); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid); /* 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); - sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0); + sqlite3ExprCode(pParse, pRowidExpr, regNewRowid); + sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); } /* Compute new data for this record. */ for(i=0; i<pTab->nCol; i++){ if( i==pTab->iPKey ){ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, regData+i); continue; } j = aXRef[i]; if( j<0 ){ - sqlite3VdbeAddOp(v, OP_Column, iCur, i); + sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regData+i); sqlite3ColumnDefault(v, pTab, i); }else{ - sqlite3ExprCode(pParse, pChanges->a[j].pExpr); + sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regData+i); } } /* Do constraint checks */ - sqlite3GenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, - onError, addr); + sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid, + aRegIdx, chngRowid, 1, + onError, addr); /* Delete the old indices for the current record. */ - sqlite3GenerateRowIndexDelete(v, pTab, iCur, aIdxUsed); + j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid); + sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx); /* If changing the record number, delete the old record. */ if( chngRowid ){ - sqlite3VdbeAddOp(v, OP_Delete, iCur, 0); - } + sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0); + } + sqlite3VdbeJumpHere(v, j1); /* Create the new index entries and the new record. */ - sqlite3CompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRowid, 1, -1, 0); + sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, + aRegIdx, chngRowid, 1, -1, 0); } /* Increment the row counter */ if( db->flags & SQLITE_CountRows && !pParse->trigStack){ - sqlite3VdbeAddOp(v, OP_MemIncr, 1, memCnt); + sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1); } /* If there are triggers, close all the cursors after each iteration ** through the loop. The fire the after triggers. */ if( triggers_exist ){ - 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; - } + sqlite3VdbeAddOp2(v, OP_Goto, 0, iBeginAfterTrigger); + sqlite3VdbeJumpHere(v, iEndAfterTrigger); } /* Repeat the above with the next record to be updated, until ** all record selected by the WHERE clause have been updated. */ - sqlite3VdbeAddOp(v, OP_Goto, 0, addr); + sqlite3VdbeAddOp2(v, OP_Goto, 0, addr); sqlite3VdbeJumpHere(v, addr); - /* 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); - } - } - sqlite3VdbeAddOp(v, OP_Close, iCur, 0); - }else{ - sqlite3VdbeAddOp(v, OP_Close, newIdx, 0); - sqlite3VdbeAddOp(v, OP_Close, oldIdx, 0); + /* 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); + } + } + sqlite3VdbeAddOp2(v, OP_Close, iCur, 0); + if( triggers_exist ){ + sqlite3VdbeAddOp2(v, OP_Close, newIdx, 0); + sqlite3VdbeAddOp2(v, OP_Close, oldIdx, 0); } /* ** Return the number of rows that were changed. If this routine is ** generating code because of a call to sqlite3NestedParse(), do not ** invoke the callback function. */ if( db->flags & SQLITE_CountRows && !pParse->trigStack && pParse->nested==0 ){ - sqlite3VdbeAddOp(v, OP_MemLoad, memCnt, 0); - sqlite3VdbeAddOp(v, OP_Callback, 1, 0); + sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1); sqlite3VdbeSetNumCols(v, 1); - sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P3_STATIC); + sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", P4_STATIC); } update_cleanup: sqlite3AuthContextPop(&sContext); - sqlite3_free(apIdx); + sqlite3_free(aRegIdx); sqlite3_free(aXRef); sqlite3SrcListDelete(pTabList); sqlite3ExprListDelete(pChanges); sqlite3ExprDelete(pWhere); return; @@ -63164,11 +65142,14 @@ Select *pSelect = 0; /* The SELECT statement */ Expr *pExpr; /* Temporary expression */ 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. */ pEList = sqlite3ExprListAppend(pParse, 0, @@ -63191,37 +65172,32 @@ /* Create the ephemeral table into which the update results will ** be stored. */ assert( v ); ephemTab = pParse->nTab++; - sqlite3VdbeAddOp(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0)); + sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0)); /* fill the ephemeral table */ - sqlite3Select(pParse, pSelect, SRT_Table, ephemTab, 0, 0, 0, 0); - - /* - ** Generate code to scan the ephemeral table and call VDelete and - ** VInsert - */ - sqlite3VdbeAddOp(v, OP_Rewind, ephemTab, 0); + sqlite3SelectDestInit(&dest, SRT_Table, ephemTab); + sqlite3Select(pParse, pSelect, &dest, 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); addr = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp(v, OP_Column, ephemTab, 0); - if( pRowid ){ - sqlite3VdbeAddOp(v, OP_Column, ephemTab, 1); - }else{ - sqlite3VdbeAddOp(v, OP_Dup, 0, 0); - } + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg); + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1); for(i=0; i<pTab->nCol; i++){ - sqlite3VdbeAddOp(v, OP_Column, ephemTab, i+1+(pRowid!=0)); + sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i); } pParse->pVirtualLock = pTab; - sqlite3VdbeOp3(v, OP_VUpdate, 0, pTab->nCol+2, - (const char*)pTab->pVtab, P3_VTAB); - sqlite3VdbeAddOp(v, OP_Next, ephemTab, addr); + sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVtab, P4_VTAB); + sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr); sqlite3VdbeJumpHere(v, addr-1); - sqlite3VdbeAddOp(v, OP_Close, ephemTab, 0); + sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0); /* Cleanup */ sqlite3SelectDelete(pSelect); } #endif /* SQLITE_OMIT_VIRTUALTABLE */ @@ -63242,11 +65218,11 @@ ** This file contains code used to implement the VACUUM command. ** ** Most of the code in this file may be omitted by defining the ** SQLITE_OMIT_VACUUM macro. ** -** $Id: vacuum.c,v 1.74 2007/10/20 20:58:57 drh Exp $ +** $Id: vacuum.c,v 1.76 2008/01/03 00:01:25 drh Exp $ */ #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) /* ** Execute zSql on database db. Return an error code. @@ -63296,11 +65272,11 @@ ** become a no-op. */ SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){ Vdbe *v = sqlite3GetVdbe(pParse); if( v ){ - sqlite3VdbeAddOp(v, OP_Vacuum, 0, 0); + sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0); } return; } /* @@ -63351,11 +65327,12 @@ if( rc!=SQLITE_OK ){ goto end_of_vacuum; } #ifndef SQLITE_OMIT_AUTOVACUUM - sqlite3BtreeSetAutoVacuum(pTemp, sqlite3BtreeGetAutoVacuum(pMain)); + sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac : + sqlite3BtreeGetAutoVacuum(pMain)); #endif /* Begin a transaction */ rc = execSql(db, "BEGIN EXCLUSIVE;"); if( rc!=SQLITE_OK ) goto end_of_vacuum; @@ -63502,11 +65479,11 @@ ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to help implement virtual tables. ** -** $Id: vtab.c,v 1.59 2007/09/20 11:32:18 rse Exp $ +** $Id: vtab.c,v 1.63 2008/01/23 03:03:05 drh Exp $ */ #ifndef SQLITE_OMIT_VIRTUALTABLE static int createModule( sqlite3 *db, /* Database in which module is registered */ @@ -63583,16 +65560,16 @@ ** disconnect the virtual table. */ SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){ pVtab->nRef--; assert(db); - assert(!sqlite3SafetyCheck(db)); + assert( sqlite3SafetyCheckOk(db) ); if( pVtab->nRef==0 ){ if( db->magic==SQLITE_MAGIC_BUSY ){ - sqlite3SafetyOff(db); + (void)sqlite3SafetyOff(db); pVtab->pModule->xDisconnect(pVtab); - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); } else { pVtab->pModule->xDisconnect(pVtab); } } } @@ -63749,33 +65726,34 @@ /* A slot for the record has already been allocated in the ** SQLITE_MASTER table. We just need to update that slot with all ** the information we've collected. ** - ** 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. + ** 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(). */ iDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3NestedParse(pParse, "UPDATE %Q.%s " "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q " - "WHERE rowid=#1", + "WHERE rowid=#%d", db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTab->zName, pTab->zName, - zStmt + zStmt, + pParse->regRowid ); sqlite3_free(zStmt); v = sqlite3GetVdbe(pParse); - sqlite3ChangeCookie(db, v, iDb); - - sqlite3VdbeAddOp(v, OP_Expire, 0, 0); + sqlite3ChangeCookie(pParse, iDb); + + sqlite3VdbeAddOp2(v, OP_Expire, 0, 0); zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName); - sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 1, zWhere, P3_DYNAMIC); - sqlite3VdbeOp3(v, OP_VCreate, iDb, 0, pTab->zName, strlen(pTab->zName) + 1); + sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC); + sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, + pTab->zName, strlen(pTab->zName) + 1); } /* If we are rereading the sqlite_master table create the in-memory ** record of the table. If the module has already been registered, ** also call the xConnect method here. @@ -64083,11 +66061,11 @@ rc = sqlite3SafetyOff(db); assert( rc==SQLITE_OK ); if( xDestroy ){ rc = xDestroy(pTab->pVtab); } - sqlite3SafetyOn(db); + (void)sqlite3SafetyOn(db); if( rc==SQLITE_OK ){ pTab->pVtab = 0; } } @@ -64306,11 +66284,11 @@ ** 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.262 2007/11/05 05:12:53 danielk1977 Exp $ +** $Id: where.c,v 1.286 2008/01/23 12:52:41 drh Exp $ */ /* ** The number of bits in a Bitmask. "BMS" means "BitMask Size". */ @@ -64523,10 +66501,11 @@ if( pWC->a==0 ){ pWC->pParse->db->mallocFailed = 1; if( flags & TERM_DYNAMIC ){ sqlite3ExprDelete(p); } + pWC->a = pOld; return 0; } memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm); if( pOld!=pWC->aStatic ){ sqlite3_free(pOld); @@ -64828,24 +66807,25 @@ pLeft = pList->a[1].pExpr; if( pLeft->op!=TK_COLUMN ){ return 0; } pColl = pLeft->pColl; + assert( pColl!=0 || pLeft->iColumn==-1 ); if( pColl==0 ){ - /* 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? - */ + /* No collation is defined for the ROWID. Use the default. */ pColl = db->pDfltColl; } if( (pColl->type!=SQLITE_COLL_BINARY || noCase) && (pColl->type!=SQLITE_COLL_NOCASE || !noCase) ){ return 0; } sqlite3DequoteExpr(db, pRight); z = (char *)pRight->token.z; - for(cnt=0; (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2]; cnt++){} + cnt = 0; + if( z ){ + while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){ cnt++; } + } if( cnt==0 || 255==(u8)z[cnt] ){ return 0; } *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0; *pnPattern = cnt; @@ -64996,22 +66976,27 @@ static void exprAnalyze( SrcList *pSrc, /* the FROM clause */ WhereClause *pWC, /* the WHERE clause */ int idxTerm /* Index of the term to be analyzed */ ){ - WhereTerm *pTerm = &pWC->a[idxTerm]; - ExprMaskSet *pMaskSet = pWC->pMaskSet; - Expr *pExpr = pTerm->pExpr; + WhereTerm *pTerm; + ExprMaskSet *pMaskSet; + Expr *pExpr; Bitmask prereqLeft; Bitmask prereqAll; int nPattern; int isComplete; int op; Parse *pParse = pWC->pParse; sqlite3 *db = pParse->db; - if( db->mallocFailed ) return; + if( db->mallocFailed ){ + return; + } + pTerm = &pWC->a[idxTerm]; + pMaskSet = pWC->pMaskSet; + pExpr = pTerm->pExpr; prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft); op = pExpr->op; if( op==TK_IN ){ assert( pExpr->pRight==0 ); pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->pList) @@ -65184,11 +67169,11 @@ sqlite3TokenCopy(db, &pStr1->token, &pRight->token); pStr1->token.n = nPattern; pStr1->flags = EP_Dequoted; } pStr2 = sqlite3ExprDup(db, pStr1); - if( pStr2 ){ + if( !db->mallocFailed ){ assert( pStr2->token.dyn ); ++*(u8*)&pStr2->token.z[nPattern-1]; } pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft), pStr1, 0); idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC); @@ -65661,11 +67646,11 @@ nOrderBy = pIdxInfo->nOrderBy; if( pIdxInfo->nOrderBy && !orderByUsable ){ *(int*)&pIdxInfo->nOrderBy = 0; } - sqlite3SafetyOff(pParse->db); + (void)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); if( rc!=SQLITE_OK ){ @@ -65672,14 +67657,12 @@ if( rc==SQLITE_NOMEM ){ pParse->db->mallocFailed = 1; }else { sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc)); } - sqlite3SafetyOn(pParse->db); - }else{ - rc = sqlite3SafetyOn(pParse->db); - } + } + (void)sqlite3SafetyOn(pParse->db); *(int*)&pIdxInfo->nOrderBy = nOrderBy; return pIdxInfo->estimatedCost; } #endif /* SQLITE_OMIT_VIRTUALTABLE */ @@ -65985,49 +67968,57 @@ ** problem. */ 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); + Index *pIdx, /* Index that we will be searching */ + int regSrc, /* Take values from this register */ + int regDest /* Write the result into this register */ +){ + assert( regSrc>0 ); + assert( regDest>0 ); + sqlite3VdbeAddOp3(v, OP_MakeRecord, regSrc, nColumn, regDest); sqlite3IndexAffinityStr(v, pIdx); } /* ** Generate code for a single equality term of the WHERE clause. An equality ** term can be either X=expr or X IN (...). pTerm is the term to be ** coded. ** -** The current value for the constraint is left on the top of the stack. +** The current value for the constraint is left in register iReg. ** ** 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 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 */ + WhereLevel *pLevel, /* When level of the FROM clause we are working on */ + int iReg /* Leave results in this register */ ){ Expr *pX = pTerm->pExpr; Vdbe *v = pParse->pVdbe; + + assert( iReg>0 && iReg<=pParse->nMem ); if( pX->op==TK_EQ ){ - sqlite3ExprCode(pParse, pX->pRight); + sqlite3ExprCode(pParse, pX->pRight, iReg); }else if( pX->op==TK_ISNULL ){ - sqlite3VdbeAddOp(v, OP_Null, 0, 0); + sqlite3VdbeAddOp2(v, OP_Null, 0, iReg); #ifndef SQLITE_OMIT_SUBQUERY }else{ + int eType; int iTab; struct InLoop *pIn; assert( pX->op==TK_IN ); - sqlite3CodeSubselect(pParse, pX); + eType = sqlite3FindInIndex(pParse, pX, 1); iTab = pX->iTable; - sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0); - VdbeComment((v, "# %.*s", pX->span.n, pX->span.z)); + sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); + VdbeComment((v, "%.*s", pX->span.n, pX->span.z)); if( pLevel->nIn==0 ){ pLevel->nxt = sqlite3VdbeMakeLabel(v); } pLevel->nIn++; pLevel->aInLoop = sqlite3DbReallocOrFree(pParse->db, pLevel->aInLoop, @@ -66034,12 +68025,16 @@ sizeof(pLevel->aInLoop[0])*pLevel->nIn); pIn = pLevel->aInLoop; if( pIn ){ pIn += pLevel->nIn - 1; pIn->iCur = iTab; - pIn->topAddr = sqlite3VdbeAddOp(v, OP_Column, iTab, 0); - sqlite3VdbeAddOp(v, OP_IsNull, -1, 0); + 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); }else{ pLevel->nIn = 0; } #endif } @@ -66067,59 +68062,48 @@ ** calls this routine will use pLevel->iMem to store the termination ** key value of the loop. If one or more IN operators appear, then ** this routine allocates an additional nEq memory cells for internal ** use. */ -static void codeAllEqualityTerms( +static int 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 nEq = pLevel->nEq; /* The number of == or IN constraints to code */ - int termsInMem = 0; /* If true, store value in mem[] cells */ + Bitmask notReady, /* Which parts of FROM have not yet been coded */ + int nExtraReg /* Number of extra registers to allocate */ +){ + int nEq = pLevel->nEq; /* The number of == or IN constraints to code */ 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++; - if( pLevel->flags & WHERE_COLUMN_IN ){ - pParse->nMem += pLevel->nEq; - termsInMem = 1; - } + pLevel->iMem = pParse->nMem + 1; + regBase = pParse->nMem + 2; + pParse->nMem += pLevel->nEq + 2 + nExtraReg; /* Evaluate the equality constraints */ assert( pIdx->nColumn>=nEq ); for(j=0; j<nEq; j++){ int k = pIdx->aiColumn[j]; pTerm = findTerm(pWC, iCur, k, notReady, pLevel->flags, pIdx); if( pTerm==0 ) break; assert( (pTerm->flags & TERM_CODED)==0 ); - codeEqualityTerm(pParse, pTerm, pLevel); + codeEqualityTerm(pParse, pTerm, pLevel, regBase+j); if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){ - 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; j<nEq; j++){ - sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem+j+1, 0); - } - } + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->brk); + } + } + return regBase; } #if defined(SQLITE_TEST) /* ** The following variable holds a text description of query plan generated @@ -66140,17 +68124,11 @@ if( pWInfo ){ int i; for(i=0; i<pWInfo->nLevel; i++){ sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo; if( pInfo ){ - 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); - } + assert( pInfo->needToFreeIdxStr==0 ); sqlite3_free(pInfo); } } sqlite3_free(pWInfo); } @@ -66247,11 +68225,12 @@ */ 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 */ + ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */ + u8 obflag /* One of ORDERBY_MIN, ORDERBY_MAX or ORDERBY_NORMAL */ ){ int i; /* Loop counter */ WhereInfo *pWInfo; /* Will become the return value of this function */ Vdbe *v = pParse->pVdbe; /* The virtual database engine */ int brk, cont = 0; /* Addresses used during code generation */ @@ -66262,17 +68241,22 @@ struct SrcList_item *pTabItem; /* A single entry from pTabList */ WhereLevel *pLevel; /* A single level in the pWInfo list */ 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 */ if( pTabList->nSrc>BMS ){ sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS); return 0; + } + + if( ppOrderBy ){ + pOrderBy = *ppOrderBy; } /* Split the WHERE clause into separate subexpressions where each ** subexpression is separated by an AND operator. */ @@ -66296,11 +68280,11 @@ /* Special case: a WHERE clause that is constant. Evaluate the ** expression and either jump over all of the code or fall thru. */ if( pWhere && (pTabList->nSrc==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){ - sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1); + sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL); pWhere = 0; } /* Analyze all of the subexpressions. Note that exprAnalyze() might ** add new virtual terms onto the end of the WHERE clause. We do not @@ -66460,21 +68444,22 @@ } #endif if( pLevel->flags & WHERE_ORDERBY ){ zMsg = sqlite3MPrintf(db, "%z ORDER BY", zMsg); } - sqlite3VdbeOp3(v, OP_Explain, i, pLevel->iFrom, zMsg, P3_DYNAMIC); + sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC); } #endif /* SQLITE_OMIT_EXPLAIN */ pTabItem = &pTabList->a[pLevel->iFrom]; pTab = pTabItem->pTab; iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); if( pTab->isEphem || pTab->pSelect ) continue; #ifndef SQLITE_OMIT_VIRTUALTABLE if( pLevel->pBestIdx ){ int iCur = pTabItem->iCursor; - sqlite3VdbeOp3(v, OP_VOpen, iCur, 0, (const char*)pTab->pVtab, P3_VTAB); + sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, + (const char*)pTab->pVtab, P4_VTAB); }else #endif if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){ sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, OP_OpenRead); if( pTab->nCol<(sizeof(Bitmask)*8) ){ @@ -66489,19 +68474,14 @@ } pLevel->iTabCur = pTabItem->iCursor; if( (pIx = pLevel->pIdx)!=0 ){ KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx); assert( pIx->pSchema==pTab->pSchema ); - sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); - VdbeComment((v, "# %s", pIx->zName)); - sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIx->tnum, - (char*)pKey, P3_KEYINFO_HANDOFF); - } - if( (pLevel->flags & (WHERE_IDX_ONLY|WHERE_COLUMN_RANGE))!=0 ){ - /* Only call OP_SetNumColumns on the index if we might later use - ** OP_Column on the index. */ - sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1); + sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb, + (char*)pKey, P4_KEYINFO_HANDOFF); + VdbeComment((v, "%s", pIx->zName)); + sqlite3VdbeAddOp2(v, OP_SetNumColumns, iIdxCur, pIx->nColumn+1); } sqlite3CodeVerifySchema(pParse, iDb); } pWInfo->iTop = sqlite3VdbeCurrentAddr(v); @@ -66542,44 +68522,46 @@ /* If this is the right table of a LEFT OUTER JOIN, allocate and ** initialize a memory cell that records if this table matches any ** row of the left table of the join. */ if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){ - if( !pParse->nMem ) pParse->nMem++; - pLevel->iLeftJoin = pParse->nMem++; - sqlite3VdbeAddOp(v, OP_MemInt, 0, pLevel->iLeftJoin); - VdbeComment((v, "# init LEFT JOIN no-match flag")); + pLevel->iLeftJoin = ++pParse->nMem; + sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin); + VdbeComment((v, "init LEFT JOIN no-match flag")); } #ifndef SQLITE_OMIT_VIRTUALTABLE if( pLevel->pBestIdx ){ /* Case 0: The table is a virtual-table. Use the VFilter and VNext ** 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 = pBestIdx->aConstraintUsage; const struct sqlite3_index_constraint *aConstraint = pBestIdx->aConstraint; + iReg = sqlite3GetTempRange(pParse, nConstraint+2); for(j=1; j<=nConstraint; j++){ int k; for(k=0; k<nConstraint; k++){ if( aUsage[k].argvIndex==j ){ int iTerm = aConstraint[k].iTermOffset; - sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight); + sqlite3ExprCode(pParse, wc.a[iTerm].pExpr->pRight, iReg+j+1); break; } } if( k==nConstraint ) break; } - 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); + 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); pBestIdx->needToFreeIdxStr = 0; for(j=0; j<pBestIdx->nConstraint; j++){ if( aUsage[j].omit ){ int iTerm = aConstraint[j].iTermOffset; disableTerm(pLevel, &wc.a[iTerm]); @@ -66595,20 +68577,23 @@ /* Case 1: We can directly reference a single row using an ** equality comparison against the ROWID field. Or ** 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 ); - codeEqualityTerm(pParse, pTerm, pLevel); + r1 = sqlite3GetTempReg(pParse); + codeEqualityTerm(pParse, pTerm, pLevel, r1); nxt = pLevel->nxt; - sqlite3VdbeAddOp(v, OP_MustBeInt, 1, nxt); - sqlite3VdbeAddOp(v, OP_NotExists, iCur, nxt); + sqlite3VdbeAddOp3(v, OP_MustBeInt, r1, nxt, 1); + sqlite3VdbeAddOp3(v, OP_NotExists, iCur, nxt, r1); VdbeComment((v, "pk")); + sqlite3ReleaseTempReg(pParse, r1); pLevel->op = OP_Noop; }else if( pLevel->flags & WHERE_ROWID_RANGE ){ /* Case 2: We have an inequality comparison against the ROWID field. */ int testOp = OP_Noop; @@ -66623,29 +68608,31 @@ pStart = pEnd; pEnd = pTerm; } if( pStart ){ Expr *pX; + int r1, regFree1; pX = pStart->pExpr; assert( pX!=0 ); assert( pStart->leftCursor==iCur ); - 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); + 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); VdbeComment((v, "pk")); + sqlite3ReleaseTempReg(pParse, regFree1); disableTerm(pLevel, pStart); }else{ - sqlite3VdbeAddOp(v, bRev ? OP_Last : OP_Rewind, iCur, brk); + sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, brk); } if( pEnd ){ Expr *pX; pX = pEnd->pExpr; assert( pX!=0 ); assert( pEnd->leftCursor==iCur ); - sqlite3ExprCode(pParse, pX->pRight); - pLevel->iMem = pParse->nMem++; - sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); + pLevel->iMem = ++pParse->nMem; + sqlite3ExprCode(pParse, pX->pRight, pLevel->iMem); if( pX->op==TK_LT || pX->op==TK_GT ){ testOp = bRev ? OP_Le : OP_Ge; }else{ testOp = bRev ? OP_Lt : OP_Gt; } @@ -66654,13 +68641,16 @@ start = sqlite3VdbeCurrentAddr(v); pLevel->op = bRev ? OP_Prev : OP_Next; pLevel->p1 = iCur; pLevel->p2 = start; if( testOp!=OP_Noop ){ - sqlite3VdbeAddOp(v, OP_Rowid, iCur, 0); - sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); - sqlite3VdbeAddOp(v, testOp, SQLITE_AFF_NUMERIC|0x100, brk); + 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); } }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 @@ -66678,23 +68668,18 @@ 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; + int isMinQuery = 0; /* If this is an optimized SELECT min(x) ... */ + int regBase; /* Base register holding constraint values */ + int r1; /* Temp register */ /* Generate code to evaluate all constraint terms using == or IN ** 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<nEq; j++){ - sqlite3VdbeAddOp(v, OP_Dup, nEq-1, 0); - } + regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 2); /* Figure out what comparison operators to use for top and bottom ** search bounds. For an ascending index, the bottom bound is a > or >= ** operator and the top bound is a < or <= operator. For a descending ** index the operators are reversed. @@ -66706,10 +68691,26 @@ topOp = WO_GT|WO_GE; btmOp = WO_LT|WO_LE; SWAP(int, topLimit, btmLimit); } + /* 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( (obflag==ORDERBY_MIN) + && (pLevel->flags&WHERE_ORDERBY) + && (pIdx->nColumn>nEq) + && (pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq]) + ){ + isMinQuery = 1; + } + /* 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" @@ -66716,36 +68717,38 @@ ** key computed here really ends up being the start key. */ nxt = pLevel->nxt; if( topLimit ){ Expr *pX; - int k = pIdx->aiColumn[j]; + int k = pIdx->aiColumn[nEq]; 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); + sqlite3ExprCode(pParse, pX->pRight, regBase+nEq); + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt); topEq = pTerm->eOperator & (WO_LE|WO_GE); disableTerm(pLevel, pTerm); testOp = OP_IdxGE; }else{ testOp = nEq>0 ? OP_IdxGE : OP_Noop; topEq = 1; } - if( testOp!=OP_Noop ){ + if( testOp!=OP_Noop || (isMinQuery&&bRev) ){ int nCol = nEq + topLimit; - pLevel->iMem = pParse->nMem++; - buildIndexProbe(v, nCol, pIdx); + if( isMinQuery && !topLimit ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nCol); + nCol++; + topEq = 0; + } + buildIndexProbe(v, nCol, pIdx, regBase, pLevel->iMem); if( bRev ){ int op = topEq ? OP_MoveLe : OP_MoveLt; - sqlite3VdbeAddOp(v, op, iIdxCur, nxt); - }else{ - sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); + sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, pLevel->iMem); } }else if( bRev ){ - sqlite3VdbeAddOp(v, OP_Last, iIdxCur, brk); + sqlite3VdbeAddOp2(v, OP_Last, iIdxCur, brk); } /* 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 @@ -66755,59 +68758,68 @@ ** 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. */ if( btmLimit ){ Expr *pX; - int k = pIdx->aiColumn[j]; + int k = pIdx->aiColumn[nEq]; 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); + sqlite3ExprCode(pParse, pX->pRight, regBase+nEq); + sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, nxt); btmEq = pTerm->eOperator & (WO_LE|WO_GE); disableTerm(pLevel, pTerm); }else{ btmEq = 1; } - if( nEq>0 || btmLimit ){ + if( nEq>0 || btmLimit || (isMinQuery&&!bRev) ){ int nCol = nEq + btmLimit; - buildIndexProbe(v, nCol, pIdx); + if( isMinQuery && !btmLimit ){ + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nCol); + nCol++; + btmEq = 0; + } if( bRev ){ - pLevel->iMem = pParse->nMem++; - sqlite3VdbeAddOp(v, OP_MemStore, pLevel->iMem, 1); + r1 = pLevel->iMem; testOp = OP_IdxLT; }else{ + r1 = sqlite3GetTempReg(pParse); + } + buildIndexProbe(v, nCol, pIdx, regBase, r1); + if( !bRev ){ int op = btmEq ? OP_MoveGe : OP_MoveGt; - sqlite3VdbeAddOp(v, op, iIdxCur, nxt); + sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, r1); + sqlite3ReleaseTempReg(pParse, r1); } }else if( bRev ){ testOp = OP_Noop; }else{ - sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, brk); + sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, brk); } /* 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. */ start = sqlite3VdbeCurrentAddr(v); if( testOp!=OP_Noop ){ - sqlite3VdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0); - sqlite3VdbeAddOp(v, testOp, iIdxCur, nxt); + sqlite3VdbeAddOp3(v, testOp, iIdxCur, nxt, pLevel->iMem); if( (topEq && !bRev) || (!btmEq && bRev) ){ - sqlite3VdbeChangeP3(v, -1, "+", P3_STATIC); - } - } + sqlite3VdbeChangeP5(v, 1); + } + } + r1 = sqlite3GetTempReg(pParse); if( topLimit | btmLimit ){ - sqlite3VdbeAddOp(v, OP_Column, iIdxCur, nEq); - sqlite3VdbeAddOp(v, OP_IsNull, 1, cont); + sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1); + sqlite3VdbeAddOp2(v, OP_IsNull, r1, cont); } if( !omitTable ){ - sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0); - sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0); - } + sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1); + sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1); /* Deferred seek */ + } + sqlite3ReleaseTempReg(pParse, r1); /* Record the instruction used to terminate the loop. */ pLevel->op = bRev ? OP_Prev : OP_Next; pLevel->p1 = iIdxCur; @@ -66816,44 +68828,72 @@ /* 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; + int isMinQuery = 0; /* If this is an optimized SELECT min(x) ... */ + int regBase; /* Base register of array holding constraints */ + int r1; /* 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); + regBase = codeAllEqualityTerms(pParse, pLevel, &wc, notReady, 1); 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); + if( (obflag==ORDERBY_MIN) + && (pLevel->flags&WHERE_ORDERBY) + && (pIdx->nColumn>nEq) + && (pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq]) + ){ + isMinQuery = 1; + buildIndexProbe(v, nEq, pIdx, regBase, pLevel->iMem); + sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq); + r1 = ++pParse->nMem; + buildIndexProbe(v, nEq+1, pIdx, regBase, r1); + }else{ + /* Generate a single key that will be used to both start and + ** terminate the search + */ + r1 = pLevel->iMem; + buildIndexProbe(v, nEq, pIdx, regBase, r1); + } /* 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); + int op; + if( isMinQuery ){ + op = OP_MoveLt; + }else{ + op = OP_MoveLe; + } + sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, r1); + start = sqlite3VdbeAddOp3(v, OP_IdxLT, iIdxCur, nxt, pLevel->iMem); 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); + int op; + if( isMinQuery ){ + op = OP_MoveGt; + }else{ + op = OP_MoveGe; + } + sqlite3VdbeAddOp3(v, op, iIdxCur, nxt, r1); + start = sqlite3VdbeAddOp3(v, OP_IdxGE, iIdxCur, nxt, pLevel->iMem); + sqlite3VdbeChangeP5(v, 1); pLevel->op = OP_Next; } if( !omitTable ){ - sqlite3VdbeAddOp(v, OP_IdxRowid, iIdxCur, 0); - sqlite3VdbeAddOp(v, OP_MoveGe, iCur, 0); + r1 = sqlite3GetTempReg(pParse); + sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, r1); + sqlite3VdbeAddOp3(v, OP_MoveGe, iCur, 0, r1); /* Deferred seek */ + sqlite3ReleaseTempReg(pParse, r1); } pLevel->p1 = iIdxCur; pLevel->p2 = start; }else{ /* Case 5: There is no usable index. We must do a complete @@ -66861,11 +68901,11 @@ */ assert( omitTable==0 ); assert( bRev==0 ); pLevel->op = OP_Next; pLevel->p1 = iCur; - pLevel->p2 = 1 + sqlite3VdbeAddOp(v, OP_Rewind, iCur, brk); + pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, OP_Rewind, iCur, brk); } notReady &= ~getMask(&maskSet, iCur); /* Insert code to test every subexpression that can be completely ** computed using the current set of tables. @@ -66877,26 +68917,26 @@ pE = pTerm->pExpr; assert( pE!=0 ); if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){ continue; } - sqlite3ExprIfFalse(pParse, pE, cont, 1); + sqlite3ExprIfFalse(pParse, pE, cont, SQLITE_JUMPIFNULL); pTerm->flags |= TERM_CODED; } /* For a LEFT OUTER JOIN, generate code that will record the fact that ** at least one row of the right table has matched the left table. */ if( pLevel->iLeftJoin ){ pLevel->top = sqlite3VdbeCurrentAddr(v); - sqlite3VdbeAddOp(v, OP_MemInt, 1, pLevel->iLeftJoin); - VdbeComment((v, "# record LEFT JOIN hit")); + sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin); + VdbeComment((v, "record LEFT JOIN hit")); for(pTerm=wc.a, j=0; j<wc.nTerm; j++, pTerm++){ if( pTerm->flags & (TERM_VIRTUAL|TERM_CODED) ) continue; if( (pTerm->prereqAll & notReady)!=0 ) continue; assert( pTerm->pExpr ); - sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, 1); + sqlite3ExprIfFalse(pParse, pTerm->pExpr, cont, SQLITE_JUMPIFNULL); pTerm->flags |= TERM_CODED; } } } @@ -66975,32 +69015,32 @@ */ for(i=pTabList->nSrc-1; i>=0; i--){ pLevel = &pWInfo->a[i]; sqlite3VdbeResolveLabel(v, pLevel->cont); if( pLevel->op!=OP_Noop ){ - sqlite3VdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2); + sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2); } if( pLevel->nIn ){ struct InLoop *pIn; int j; sqlite3VdbeResolveLabel(v, pLevel->nxt); for(j=pLevel->nIn, pIn=&pLevel->aInLoop[j-1]; j>0; j--, pIn--){ sqlite3VdbeJumpHere(v, pIn->topAddr+1); - sqlite3VdbeAddOp(v, OP_Next, pIn->iCur, pIn->topAddr); + sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->topAddr); sqlite3VdbeJumpHere(v, pIn->topAddr-1); } sqlite3_free(pLevel->aInLoop); } sqlite3VdbeResolveLabel(v, pLevel->brk); if( pLevel->iLeftJoin ){ int addr; - addr = sqlite3VdbeAddOp(v, OP_IfMemPos, pLevel->iLeftJoin, 0); - sqlite3VdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0); + addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); + sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor); if( pLevel->iIdxCur>=0 ){ - sqlite3VdbeAddOp(v, OP_NullRow, pLevel->iIdxCur, 0); - } - sqlite3VdbeAddOp(v, OP_Goto, 0, pLevel->top); + sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur); + } + sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->top); sqlite3VdbeJumpHere(v, addr); } } /* The "break" point is here, just past the end of the outer loop. @@ -67014,47 +69054,53 @@ struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom]; Table *pTab = pTabItem->pTab; assert( pTab!=0 ); if( pTab->isEphem || pTab->pSelect ) continue; if( (pLevel->flags & WHERE_IDX_ONLY)==0 ){ - sqlite3VdbeAddOp(v, OP_Close, pTabItem->iCursor, 0); + sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor); } if( pLevel->pIdx!=0 ){ - sqlite3VdbeAddOp(v, OP_Close, pLevel->iIdxCur, 0); - } - - /* Make cursor substitutions for cases where we want to use - ** just the index and never reference the table. + sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur); + } + + /* If this scan uses an index, make code substitutions to read data + ** from the index in preference to the table. Sometimes, this means + ** the table need never be read from. This is a performance boost, + ** as the vdbe level waits until the table is read before actually + ** seeking the table cursor to the record corresponding to the current + ** position in the index. ** ** Calls to the code generator in between sqlite3WhereBegin and ** sqlite3WhereEnd will have created code that references the table ** directly. This loop scans all that code looking for opcodes ** that reference the table and converts them into opcodes that ** reference the index. */ - if( pLevel->flags & WHERE_IDX_ONLY ){ + if( pLevel->pIdx ){ int k, j, last; VdbeOp *pOp; Index *pIdx = pLevel->pIdx; + int useIndexOnly = pLevel->flags & WHERE_IDX_ONLY; assert( pIdx!=0 ); pOp = sqlite3VdbeGetOp(v, pWInfo->iTop); last = sqlite3VdbeCurrentAddr(v); for(k=pWInfo->iTop; k<last; k++, pOp++){ if( pOp->p1!=pLevel->iTabCur ) continue; if( pOp->opcode==OP_Column ){ - pOp->p1 = pLevel->iIdxCur; for(j=0; j<pIdx->nColumn; j++){ if( pOp->p2==pIdx->aiColumn[j] ){ pOp->p2 = j; + pOp->p1 = pLevel->iIdxCur; break; } } + assert(!useIndexOnly || j<pIdx->nColumn); }else if( pOp->opcode==OP_Rowid ){ pOp->p1 = pLevel->iIdxCur; pOp->opcode = OP_IdxRowid; - }else if( pOp->opcode==OP_NullRow ){ + }else if( pOp->opcode==OP_NullRow && useIndexOnly ){ pOp->opcode = OP_Noop; } } } } @@ -67171,15 +69217,13 @@ Select* yy219; struct LimitVal yy234; 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 #endif #define sqlite3ParserARG_SDECL Parse *pParse; @@ -67186,12 +69230,10 @@ #define sqlite3ParserARG_PDECL ,Parse *pParse #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse #define sqlite3ParserARG_STORE yypParser->pParse = pParse #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) @@ -67241,420 +69283,420 @@ ** yy_reduce_ofst[] For each state, the offset into yy_action for ** shifting non-terminals after a reduce. ** yy_default[] Default action for each state. */ static const YYACTIONTYPE yy_action[] = { - /* 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, + /* 0 */ 292, 901, 124, 587, 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, 573, 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, 488, 60, 59, 297, 435, + /* 160 */ 436, 432, 432, 62, 62, 61, 61, 61, 61, 490, + /* 170 */ 63, 63, 63, 63, 64, 64, 65, 65, 65, 66, + /* 180 */ 210, 292, 257, 524, 295, 571, 113, 408, 522, 451, + /* 190 */ 331, 317, 407, 20, 418, 340, 519, 396, 532, 531, + /* 200 */ 505, 447, 212, 570, 569, 208, 530, 425, 431, 149, + /* 210 */ 150, 397, 398, 414, 41, 211, 151, 533, 372, 489, + /* 220 */ 261, 568, 259, 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, 418, + /* 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, 230, 397, 398, 181, 547, + /* 350 */ 494, 345, 348, 349, 67, 152, 69, 154, 339, 524, + /* 360 */ 414, 35, 350, 241, 221, 370, 425, 431, 578, 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, 525, 345, 348, 349, 252, + /* 430 */ 223, 415, 155, 464, 511, 425, 431, 350, 414, 34, + /* 440 */ 465, 211, 177, 175, 160, 237, 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, 571, 302, 19, 331, 144, + /* 490 */ 317, 390, 317, 330, 2, 362, 457, 294, 483, 373, + /* 500 */ 269, 268, 252, 570, 425, 431, 588, 391, 388, 458, + /* 510 */ 208, 495, 414, 49, 414, 49, 303, 585, 892, 159, + /* 520 */ 892, 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, 582, 308, 251, + /* 560 */ 309, 452, 76, 350, 78, 382, 211, 426, 427, 415, + /* 570 */ 414, 27, 319, 425, 431, 440, 1, 22, 585, 891, + /* 580 */ 396, 891, 544, 478, 320, 263, 438, 438, 429, 430, + /* 590 */ 415, 60, 59, 297, 435, 436, 432, 432, 62, 62, + /* 600 */ 61, 61, 61, 61, 328, 63, 63, 63, 63, 64, + /* 610 */ 64, 65, 65, 65, 66, 210, 292, 428, 582, 374, + /* 620 */ 224, 93, 517, 9, 336, 396, 557, 396, 456, 67, + /* 630 */ 396, 69, 154, 399, 400, 401, 320, 238, 438, 438, + /* 640 */ 457, 318, 425, 431, 299, 397, 398, 320, 433, 438, + /* 650 */ 438, 581, 291, 458, 225, 327, 5, 222, 546, 292, + /* 660 */ 60, 59, 297, 435, 436, 432, 432, 62, 62, 61, + /* 670 */ 61, 61, 61, 395, 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, 824, 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, 119, 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, 128, 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, 177, + /* 860 */ 4, 317, 263, 317, 296, 263, 415, 414, 28, 317, + /* 870 */ 263, 317, 321, 72, 324, 317, 4, 421, 445, 445, + /* 880 */ 296, 397, 398, 414, 23, 414, 32, 418, 321, 326, + /* 890 */ 329, 414, 53, 414, 52, 317, 158, 414, 98, 451, + /* 900 */ 317, 194, 317, 277, 317, 326, 378, 471, 502, 317, + /* 910 */ 478, 279, 478, 165, 294, 451, 317, 414, 96, 75, + /* 920 */ 74, 469, 414, 101, 414, 102, 414, 112, 73, 315, + /* 930 */ 316, 414, 114, 420, 448, 75, 74, 481, 414, 16, + /* 940 */ 381, 317, 183, 467, 73, 315, 316, 72, 324, 420, + /* 950 */ 4, 208, 317, 186, 296, 317, 499, 500, 476, 208, + /* 960 */ 173, 341, 321, 414, 99, 422, 422, 422, 423, 424, + /* 970 */ 11, 361, 380, 307, 414, 33, 415, 414, 97, 326, + /* 980 */ 460, 422, 422, 422, 423, 424, 11, 415, 413, 451, + /* 990 */ 413, 162, 412, 317, 412, 468, 226, 227, 228, 104, + /* 1000 */ 84, 473, 317, 509, 508, 317, 622, 477, 317, 75, + /* 1010 */ 74, 249, 205, 21, 281, 414, 24, 418, 73, 315, + /* 1020 */ 316, 282, 317, 420, 414, 54, 507, 414, 115, 317, + /* 1030 */ 414, 116, 506, 203, 147, 549, 244, 512, 526, 202, + /* 1040 */ 317, 513, 204, 317, 414, 117, 317, 245, 317, 18, + /* 1050 */ 317, 414, 25, 317, 256, 422, 422, 422, 423, 424, + /* 1060 */ 11, 258, 414, 36, 260, 414, 37, 317, 414, 26, + /* 1070 */ 414, 38, 414, 39, 262, 414, 40, 317, 514, 317, + /* 1080 */ 128, 317, 418, 317, 189, 377, 278, 268, 267, 414, + /* 1090 */ 42, 293, 317, 254, 317, 128, 208, 365, 8, 414, + /* 1100 */ 43, 414, 44, 414, 29, 414, 30, 352, 368, 128, + /* 1110 */ 317, 545, 317, 128, 414, 45, 414, 46, 317, 583, + /* 1120 */ 383, 553, 317, 173, 554, 317, 91, 317, 564, 369, + /* 1130 */ 91, 357, 414, 47, 414, 48, 580, 270, 290, 271, + /* 1140 */ 414, 31, 272, 556, 414, 10, 566, 414, 50, 414, + /* 1150 */ 51, 280, 283, 284, 577, 146, 463, 405, 584, 231, + /* 1160 */ 325, 419, 444, 466, 446, 246, 505, 552, 563, 515, + /* 1170 */ 516, 520, 163, 518, 394, 347, 7, 402, 403, 404, + /* 1180 */ 314, 84, 232, 334, 332, 83, 79, 416, 170, 57, + /* 1190 */ 213, 461, 125, 85, 337, 342, 492, 301, 233, 498, + /* 1200 */ 497, 105, 502, 219, 354, 247, 521, 234, 501, 235, + /* 1210 */ 287, 417, 503, 218, 527, 528, 529, 358, 240, 535, + /* 1220 */ 475, 242, 288, 479, 356, 184, 185, 121, 187, 132, + /* 1230 */ 188, 548, 537, 88, 190, 193, 364, 142, 375, 376, + /* 1240 */ 555, 133, 220, 562, 134, 310, 135, 138, 136, 574, + /* 1250 */ 575, 141, 576, 265, 579, 100, 538, 217, 393, 92, + /* 1260 */ 103, 95, 406, 623, 624, 166, 434, 167, 437, 71, + /* 1270 */ 453, 441, 450, 17, 143, 157, 169, 6, 111, 13, + /* 1280 */ 454, 455, 459, 472, 126, 81, 12, 127, 161, 485, + /* 1290 */ 486, 216, 86, 122, 106, 182, 253, 346, 312, 107, + /* 1300 */ 120, 87, 351, 108, 245, 355, 145, 536, 359, 129, + /* 1310 */ 173, 266, 191, 109, 289, 551, 130, 539, 195, 543, + /* 1320 */ 131, 14, 197, 199, 198, 558, 137, 139, 140, 110, + /* 1330 */ 15, 285, 572, 206, 389, 565, 385, 148, 586, 902, + /* 1340 */ 902, 902, 902, 902, 902, 89, 90, }; static const YYCODETYPE yy_lookahead[] = { - /* 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, + /* 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, /* 30 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - /* 40 */ 58, 99, 100, 101, 60, 61, 62, 63, 64, 65, - /* 50 */ 66, 67, 68, 69, 70, 71, 72, 84, 74, 75, + /* 40 */ 1, 2, 23, 58, 60, 61, 62, 63, 64, 65, + /* 50 */ 66, 67, 68, 69, 70, 71, 72, 147, 74, 75, /* 60 */ 76, 77, 78, 79, 80, 81, 82, 83, 84, 16, - /* 70 */ 88, 16, 88, 147, 92, 22, 42, 43, 185, 186, + /* 70 */ 185, 186, 88, 88, 110, 22, 217, 92, 219, 220, /* 80 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - /* 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, + /* 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, 169, 60, 61, 62, 63, + /* 160 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 169, + /* 170 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, + /* 180 */ 84, 16, 14, 147, 150, 147, 21, 167, 168, 58, + /* 190 */ 211, 147, 156, 157, 23, 216, 176, 23, 181, 176, + /* 200 */ 177, 78, 79, 165, 166, 110, 183, 42, 43, 78, + /* 210 */ 79, 88, 89, 169, 170, 228, 180, 181, 123, 88, + /* 220 */ 52, 98, 54, 92, 16, 60, 61, 62, 63, 64, + /* 230 */ 65, 66, 67, 68, 69, 70, 71, 72, 147, 74, /* 240 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, - /* 250 */ 42, 43, 23, 49, 92, 14, 158, 189, 133, 161, - /* 260 */ 162, 163, 19, 19, 155, 103, 23, 23, 60, 61, + /* 250 */ 42, 43, 78, 209, 210, 124, 125, 126, 224, 88, + /* 260 */ 169, 170, 88, 89, 230, 227, 228, 16, 60, 61, /* 270 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, - /* 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, + /* 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, 190, 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, 147, 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, 147, + /* 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, 186, 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, 147, 108, 109, + /* 640 */ 24, 147, 42, 43, 208, 88, 89, 106, 92, 108, + /* 650 */ 109, 244, 245, 37, 145, 39, 191, 182, 94, 16, /* 660 */ 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, - /* 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, + /* 670 */ 70, 71, 72, 147, 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, /* 720 */ 77, 78, 79, 80, 81, 82, 83, 84, 42, 43, - /* 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, + /* 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, /* 760 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - /* 770 */ 84, 42, 43, 92, 147, 182, 22, 225, 182, 182, - /* 780 */ 113, 169, 170, 0, 1, 2, 124, 125, 16, 80, + /* 770 */ 84, 42, 43, 188, 188, 182, 182, 225, 189, 106, + /* 780 */ 188, 108, 109, 188, 99, 100, 101, 241, 16, 155, /* 790 */ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, - /* 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 (-99) + /* 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, 22, 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, 43, + /* 860 */ 19, 147, 147, 147, 23, 147, 189, 169, 170, 147, + /* 870 */ 147, 147, 31, 16, 17, 147, 19, 147, 124, 125, + /* 880 */ 23, 88, 89, 169, 170, 169, 170, 88, 31, 48, + /* 890 */ 147, 169, 170, 169, 170, 147, 89, 169, 170, 58, + /* 900 */ 147, 22, 147, 188, 147, 48, 188, 114, 97, 147, + /* 910 */ 147, 188, 147, 19, 98, 58, 147, 169, 170, 78, + /* 920 */ 79, 114, 169, 170, 169, 170, 169, 170, 87, 88, + /* 930 */ 89, 169, 170, 92, 161, 78, 79, 80, 169, 170, + /* 940 */ 91, 147, 155, 22, 87, 88, 89, 16, 17, 92, + /* 950 */ 19, 110, 147, 155, 23, 147, 7, 8, 20, 110, + /* 960 */ 22, 80, 31, 169, 170, 124, 125, 126, 127, 128, + /* 970 */ 129, 208, 123, 208, 169, 170, 189, 169, 170, 48, + /* 980 */ 147, 124, 125, 126, 127, 128, 129, 189, 107, 58, + /* 990 */ 107, 5, 111, 147, 111, 203, 10, 11, 12, 13, + /* 1000 */ 121, 147, 147, 91, 92, 147, 112, 147, 147, 78, + /* 1010 */ 79, 147, 26, 19, 28, 169, 170, 23, 87, 88, + /* 1020 */ 89, 35, 147, 92, 169, 170, 178, 169, 170, 147, + /* 1030 */ 169, 170, 147, 47, 113, 49, 92, 178, 147, 53, + /* 1040 */ 147, 178, 56, 147, 169, 170, 147, 103, 147, 19, + /* 1050 */ 147, 169, 170, 147, 147, 124, 125, 126, 127, 128, + /* 1060 */ 129, 147, 169, 170, 147, 169, 170, 147, 169, 170, + /* 1070 */ 169, 170, 169, 170, 147, 169, 170, 147, 20, 147, + /* 1080 */ 22, 147, 88, 147, 232, 99, 100, 101, 147, 169, + /* 1090 */ 170, 105, 147, 20, 147, 22, 110, 147, 68, 169, + /* 1100 */ 170, 169, 170, 169, 170, 169, 170, 20, 147, 22, + /* 1110 */ 147, 20, 147, 22, 169, 170, 169, 170, 147, 20, + /* 1120 */ 134, 20, 147, 22, 20, 147, 22, 147, 20, 147, + /* 1130 */ 22, 233, 169, 170, 169, 170, 20, 147, 22, 147, + /* 1140 */ 169, 170, 147, 147, 169, 170, 147, 169, 170, 169, + /* 1150 */ 170, 147, 147, 147, 147, 191, 172, 149, 59, 193, + /* 1160 */ 223, 161, 229, 172, 229, 172, 177, 194, 194, 172, + /* 1170 */ 161, 161, 6, 172, 146, 173, 22, 146, 146, 146, + /* 1180 */ 154, 121, 194, 118, 116, 119, 130, 189, 112, 120, + /* 1190 */ 222, 152, 152, 98, 115, 98, 171, 40, 195, 179, + /* 1200 */ 171, 19, 97, 84, 15, 171, 179, 196, 173, 197, + /* 1210 */ 174, 198, 171, 226, 171, 171, 171, 38, 204, 152, + /* 1220 */ 205, 204, 174, 205, 152, 151, 151, 60, 151, 19, + /* 1230 */ 152, 184, 152, 130, 151, 184, 152, 214, 152, 15, + /* 1240 */ 194, 187, 226, 194, 187, 152, 187, 184, 187, 33, + /* 1250 */ 152, 214, 152, 234, 137, 159, 235, 175, 1, 237, + /* 1260 */ 175, 237, 20, 112, 112, 112, 92, 112, 107, 19, + /* 1270 */ 11, 20, 20, 231, 19, 19, 22, 117, 240, 117, + /* 1280 */ 20, 20, 20, 114, 19, 22, 22, 20, 112, 20, + /* 1290 */ 20, 44, 19, 243, 19, 96, 20, 44, 246, 19, + /* 1300 */ 32, 19, 44, 19, 103, 16, 21, 17, 36, 98, + /* 1310 */ 22, 133, 98, 19, 5, 1, 45, 51, 122, 45, + /* 1320 */ 102, 19, 113, 115, 14, 17, 113, 102, 122, 14, + /* 1330 */ 19, 136, 20, 135, 3, 123, 57, 19, 4, 247, + /* 1340 */ 247, 247, 247, 247, 247, 68, 68, +}; +#define YY_SHIFT_USE_DFLT (-62) #define YY_SHIFT_MAX 389 static const short yy_shift_ofst[] = { - /* 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, + /* 0 */ 39, 841, 986, -16, 841, 931, 931, 258, 123, -36, + /* 10 */ 96, 931, 931, 931, 931, 931, -45, 400, 174, 19, + /* 20 */ 171, -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, /* 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 */ 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 (-218) + /* 100 */ 280, 22, 61, 399, 564, 19, 19, 19, 19, 19, + /* 110 */ 19, 19, 216, 171, 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, 95, -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, 883, 921, + /* 210 */ 171, 754, 754, 432, 406, 406, 406, 816, 406, 171, + /* 220 */ 406, 171, 811, 879, 879, 1166, 1166, 1166, 1166, 1154, + /* 230 */ -36, 1060, 1065, 1066, 1068, 1069, 1056, 1076, 1076, 1095, + /* 240 */ 1079, 1095, 1079, 1097, 1097, 1157, 1097, 1105, 1097, 1182, + /* 250 */ 1119, 1119, 1157, 1097, 1097, 1097, 1182, 1189, 1076, 1189, + /* 260 */ 1076, 1189, 1076, 1076, 1179, 1103, 1189, 1076, 1167, 1167, + /* 270 */ 1210, 1060, 1076, 1224, 1224, 1224, 1224, 1060, 1167, 1210, + /* 280 */ 1076, 1216, 1216, 1076, 1076, 1117, -62, -62, -62, -62, + /* 290 */ -62, -62, 525, 684, 727, 168, 894, 556, 555, 938, + /* 300 */ 944, 949, 912, 1058, 1073, 1087, 1091, 1101, 1104, 1108, + /* 310 */ 1030, 1116, 1099, 1257, 1242, 1151, 1152, 1153, 1155, 1174, + /* 320 */ 1161, 1250, 1251, 1252, 1255, 1259, 1256, 1260, 1254, 1261, + /* 330 */ 1262, 1263, 1160, 1264, 1162, 1263, 1169, 1265, 1267, 1176, + /* 340 */ 1269, 1270, 1268, 1247, 1273, 1253, 1275, 1276, 1280, 1282, + /* 350 */ 1258, 1284, 1199, 1201, 1289, 1290, 1285, 1211, 1272, 1266, + /* 360 */ 1271, 1288, 1274, 1178, 1214, 1294, 1309, 1314, 1218, 1277, + /* 370 */ 1278, 1196, 1302, 1209, 1310, 1208, 1308, 1213, 1225, 1206, + /* 380 */ 1311, 1212, 1312, 1315, 1279, 1198, 1195, 1318, 1331, 1334, +}; +#define YY_REDUCE_USE_DFLT (-165) #define YY_REDUCE_MAX 291 static const short yy_reduce_ofst[] = { - /* 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, + /* 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, 436, 163, 596, -90, + /* 130 */ 763, 218, 765, 438, 586, 592, 595, 715, 718, 408, + /* 140 */ 723, 380, 634, 677, 787, 798, 144, 529, 588, -14, + /* 150 */ 0, 17, 244, 155, 298, 155, 155, 418, 372, 477, + /* 160 */ 490, 494, 509, 526, 590, 465, 494, 730, 773, 743, + /* 170 */ 833, 792, 854, 860, 155, 792, 864, 885, 848, 859, + /* 180 */ 863, 891, 907, 155, 914, 917, 155, 927, 852, 898, + /* 190 */ 941, 950, 155, 961, 982, 990, 155, 992, 995, 996, + /* 200 */ 155, 155, 999, 1004, 1005, 1006, 1007, 1008, 964, 966, + /* 210 */ 1000, 933, 935, 937, 984, 991, 993, 989, 997, 1009, + /* 220 */ 1001, 1010, 1002, 973, 974, 1028, 1031, 1032, 1033, 1026, + /* 230 */ 998, 988, 1003, 1011, 1012, 1013, 968, 1039, 1040, 1014, + /* 240 */ 1015, 1017, 1018, 1025, 1029, 1020, 1034, 1035, 1041, 1036, + /* 250 */ 987, 1016, 1027, 1043, 1044, 1045, 1048, 1074, 1067, 1075, + /* 260 */ 1072, 1077, 1078, 1080, 1019, 1021, 1083, 1084, 1047, 1051, + /* 270 */ 1023, 1046, 1086, 1054, 1057, 1059, 1061, 1049, 1063, 1037, + /* 280 */ 1093, 1022, 1024, 1098, 1100, 1038, 1096, 1082, 1085, 1042, + /* 290 */ 1050, 1052, }; static const YYACTIONTYPE yy_default[] = { - /* 0 */ 594, 819, 900, 709, 900, 900, 819, 900, 846, 713, - /* 10 */ 875, 900, 817, 900, 900, 900, 791, 900, 846, 900, + /* 0 */ 594, 819, 900, 709, 900, 819, 900, 900, 846, 713, + /* 10 */ 875, 817, 900, 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, + /* 30 */ 900, 900, 743, 900, 821, 816, 812, 814, 813, 820, + /* 40 */ 744, 733, 740, 747, 725, 859, 749, 750, 756, 757, + /* 50 */ 876, 874, 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, + /* 100 */ 618, 782, 783, 678, 613, 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, + /* 120 */ 900, 900, 900, 900, 594, 709, 900, 709, 900, 900, + /* 130 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 140 */ 900, 900, 900, 900, 900, 900, 703, 713, 893, 900, + /* 150 */ 900, 669, 900, 900, 900, 900, 900, 900, 900, 900, + /* 160 */ 900, 900, 601, 599, 900, 701, 900, 900, 627, 900, + /* 170 */ 900, 711, 900, 900, 716, 717, 900, 900, 900, 900, + /* 180 */ 900, 900, 900, 615, 900, 900, 690, 900, 852, 900, + /* 190 */ 900, 900, 866, 900, 900, 900, 864, 900, 900, 900, + /* 200 */ 692, 752, 833, 900, 879, 881, 900, 900, 701, 710, + /* 210 */ 900, 900, 900, 815, 736, 736, 736, 648, 736, 900, + /* 220 */ 736, 900, 651, 746, 746, 598, 598, 598, 598, 668, + /* 230 */ 900, 746, 737, 739, 729, 741, 900, 718, 718, 726, + /* 240 */ 728, 726, 728, 680, 680, 665, 680, 651, 680, 825, + /* 250 */ 830, 830, 665, 680, 680, 680, 825, 610, 718, 610, + /* 260 */ 718, 610, 718, 718, 856, 858, 610, 718, 682, 682, + /* 270 */ 758, 746, 718, 689, 689, 689, 689, 746, 682, 758, + /* 280 */ 718, 878, 878, 718, 718, 886, 635, 653, 653, 861, + /* 290 */ 893, 898, 900, 900, 900, 900, 765, 900, 900, 900, /* 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, + /* 310 */ 839, 900, 900, 900, 900, 770, 766, 900, 767, 900, + /* 320 */ 695, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 330 */ 900, 818, 900, 730, 900, 738, 900, 900, 900, 900, + /* 340 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 350 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 360 */ 854, 855, 900, 900, 900, 900, 900, 900, 900, 900, + /* 370 */ 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, + /* 380 */ 900, 900, 900, 900, 885, 900, 900, 888, 595, 900, + /* 390 */ 589, 592, 591, 593, 597, 600, 622, 623, 624, 602, + /* 400 */ 603, 604, 605, 606, 607, 608, 614, 616, 634, 636, + /* 410 */ 620, 638, 699, 700, 762, 693, 694, 698, 621, 773, + /* 420 */ 764, 768, 769, 771, 772, 786, 787, 789, 795, 802, + /* 430 */ 805, 788, 793, 794, 796, 801, 804, 696, 697, 808, + /* 440 */ 628, 629, 632, 633, 842, 844, 843, 845, 631, 630, + /* 450 */ 774, 777, 810, 811, 867, 868, 869, 870, 871, 806, + /* 460 */ 719, 809, 792, 731, 734, 735, 732, 702, 712, 721, + /* 470 */ 722, 723, 724, 707, 708, 714, 727, 760, 761, 715, + /* 480 */ 704, 705, 706, 807, 763, 775, 776, 639, 640, 770, + /* 490 */ 641, 642, 643, 681, 684, 685, 686, 644, 663, 666, + /* 500 */ 667, 645, 652, 646, 647, 654, 655, 656, 659, 660, + /* 510 */ 661, 662, 657, 658, 826, 827, 831, 829, 828, 649, + /* 520 */ 650, 664, 637, 626, 619, 670, 673, 674, 675, 676, + /* 530 */ 677, 679, 671, 672, 617, 609, 611, 720, 848, 857, + /* 540 */ 853, 849, 850, 851, 612, 822, 823, 683, 754, 755, + /* 550 */ 847, 860, 862, 759, 863, 865, 890, 687, 688, 691, + /* 560 */ 832, 872, 745, 748, 751, 753, 834, 835, 836, 837, + /* 570 */ 840, 841, 838, 873, 877, 880, 882, 883, 884, 887, + /* 580 */ 889, 894, 895, 896, 899, 897, 596, 590, }; #define YY_SZ_ACTTAB (int)(sizeof(yy_action)/sizeof(yy_action[0])) /* The next table maps tokens into fallback tokens. If a construct ** like the following: @@ -68327,61 +70369,59 @@ ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ - case 155: - case 189: - case 206: + case 155: /* select */ + case 189: /* oneselect */ + case 206: /* seltablist_paren */ {sqlite3SelectDelete((yypminor->yy219));} break; - case 169: - case 170: - case 194: - case 196: - case 204: - case 210: - case 218: - case 221: - case 223: - case 235: + 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));} break; - case 174: - case 182: - case 192: - case 195: - case 197: - case 199: - case 209: - case 211: - case 212: - case 215: - case 216: - case 222: + 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));} break; - case 188: - case 193: - case 201: - case 202: + case 188: /* fullname */ + case 193: /* from */ + case 201: /* seltablist */ + case 202: /* stl_prefix */ {sqlite3SrcListDelete((yypminor->yy373));} break; - case 205: - case 208: - case 214: + case 205: /* using_opt */ + case 208: /* inscollist */ + case 214: /* inscollist_opt */ {sqlite3IdListDelete((yypminor->yy432));} break; - case 231: - case 236: + case 231: /* trigger_cmd_list */ + case 236: /* trigger_cmd */ {sqlite3DeleteTriggerStep((yypminor->yy243));} break; - case 233: -{sqlite3IdListDelete((yypminor->yy370).b);} - break; - case 238: -{sqlite3ExprDelete((yypminor->yy386));} + case 233: /* trigger_event */ +{sqlite3IdListDelete((yypminor->yy370).b);} break; default: break; /* If no destructor action specified: do nothing */ } } @@ -68452,13 +70492,11 @@ int stateno = pParser->yystack[pParser->yyidx].stateno; if( stateno>YY_SHIFT_MAX || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){ return yy_default[stateno]; } - if( iLookAhead==YYNOCODE ){ - return YY_NO_ACTION; - } + assert( iLookAhead!=YYNOCODE ); i += iLookAhead; if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ if( iLookAhead>0 ){ #ifdef YYFALLBACK int iFallback; /* Fallback token */ @@ -68505,25 +70543,18 @@ static int yy_find_reduce_action( int stateno, /* Current state number */ YYCODETYPE iLookAhead /* The look-ahead token */ ){ int i; - /* 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]; - } - if( iLookAhead==YYNOCODE ){ - return YY_NO_ACTION; - } + assert( stateno<=YY_REDUCE_MAX ); + i = yy_reduce_ofst[stateno]; + assert( i!=YY_REDUCE_USE_DFLT ); + assert( iLookAhead!=YYNOCODE ); i += iLookAhead; - if( i<0 || i>=YY_SZ_ACTTAB || yy_lookahead[i]!=iLookAhead ){ - return yy_default[stateno]; - }else{ - return yy_action[i]; - } + assert( i>=0 && i<YY_SZ_ACTTAB ); + assert( yy_lookahead[i]==iLookAhead ); + return yy_action[i]; } /* ** The following routine is called if the stack overflows. */ @@ -68955,307 +70986,308 @@ ** #line <lineno> <grammarfile> ** { ... } // User supplied code ** #line <lineno> <thisfile> ** break; */ - 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: + 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 257: /* plus_opt ::= PLUS */ + case 258: /* plus_opt ::= */ + case 268: /* foreach_clause ::= */ + case 269: /* foreach_clause ::= FOR EACH ROW */ + case 289: /* database_kw_opt ::= DATABASE */ + case 290: /* database_kw_opt ::= */ + case 298: /* kwcolumn_opt ::= */ + case 299: /* kwcolumn_opt ::= COLUMNKW */ + case 303: /* vtabarglist ::= vtabarg */ + case 304: /* vtabarglist ::= vtabarglist COMMA vtabarg */ + case 306: /* vtabarg ::= vtabarg vtabargtoken */ + case 310: /* anylist ::= */ +{ +} + break; + case 3: /* cmdx ::= cmd */ { sqlite3FinishCoding(pParse); } break; - case 6: + case 6: /* explain ::= */ { sqlite3BeginParse(pParse, 0); } break; - case 7: + case 7: /* explain ::= EXPLAIN */ { sqlite3BeginParse(pParse, 1); } break; - case 8: + case 8: /* explain ::= EXPLAIN QUERY PLAN */ { sqlite3BeginParse(pParse, 2); } break; - case 9: + case 9: /* cmd ::= BEGIN transtype trans_opt */ {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy46);} break; - case 13: + case 13: /* transtype ::= */ {yygotominor.yy46 = TK_DEFERRED;} break; - case 14: - case 15: - case 16: - case 107: - case 109: + case 14: /* transtype ::= DEFERRED */ + case 15: /* transtype ::= IMMEDIATE */ + case 16: /* transtype ::= EXCLUSIVE */ + case 107: /* multiselect_op ::= UNION */ + case 109: /* multiselect_op ::= EXCEPT|INTERSECT */ {yygotominor.yy46 = yymsp[0].major;} break; - case 17: - case 18: + case 17: /* cmd ::= COMMIT trans_opt */ + case 18: /* cmd ::= END trans_opt */ {sqlite3CommitTransaction(pParse);} break; - case 19: + case 19: /* cmd ::= ROLLBACK trans_opt */ {sqlite3RollbackTransaction(pParse);} break; - case 21: + case 21: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */ { sqlite3StartTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,yymsp[-4].minor.yy46,0,0,yymsp[-2].minor.yy46); } break; - case 22: - case 25: - case 63: - case 77: - case 79: - case 90: - case 101: - case 112: - case 113: - case 213: - case 216: + 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 */ {yygotominor.yy46 = 0;} break; - case 23: - case 24: - case 64: - case 78: - case 100: - case 111: - case 214: - case 217: + 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 */ {yygotominor.yy46 = 1;} break; - case 26: + case 26: /* create_table_args ::= LP columnlist conslist_opt RP */ { sqlite3EndTable(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy0,0); } break; - case 27: + case 27: /* create_table_args ::= AS select */ { sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy219); sqlite3SelectDelete(yymsp[0].minor.yy219); } break; - case 30: + case 30: /* column ::= columnid type carglist */ { 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: + case 31: /* columnid ::= nm */ { sqlite3AddColumn(pParse,&yymsp[0].minor.yy410); yygotominor.yy410 = yymsp[0].minor.yy410; } break; - case 32: - case 33: - case 34: - case 35: - case 36: - case 256: + case 32: /* id ::= ID */ + case 33: /* ids ::= ID|STRING */ + case 34: /* nm ::= ID */ + case 35: /* nm ::= STRING */ + case 36: /* nm ::= JOIN_KW */ + case 256: /* number ::= INTEGER|FLOAT */ {yygotominor.yy410 = yymsp[0].minor.yy0;} break; - case 38: + case 38: /* type ::= typetoken */ {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy410);} break; - case 39: - case 42: - case 119: - case 120: - case 131: - case 241: - case 243: - case 252: - case 253: - case 254: - case 255: + 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 252: /* nmnum ::= plus_num */ + case 253: /* nmnum ::= nm */ + case 254: /* plus_num ::= plus_opt number */ + case 255: /* minus_num ::= MINUS number */ {yygotominor.yy410 = yymsp[0].minor.yy410;} break; - case 40: + case 40: /* typetoken ::= typename LP signed RP */ { 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: + case 41: /* typetoken ::= typename LP signed COMMA signed RP */ { 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: + case 43: /* typename ::= typename ids */ {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: - case 52: + case 50: /* ccons ::= DEFAULT term */ + case 52: /* ccons ::= DEFAULT PLUS term */ {sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy172);} break; - case 51: + case 51: /* ccons ::= DEFAULT LP expr RP */ {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy172);} break; - case 53: + case 53: /* ccons ::= DEFAULT MINUS term */ { Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy172, 0, 0); sqlite3AddDefaultValue(pParse,p); } break; - case 54: + case 54: /* ccons ::= DEFAULT id */ { Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy410); sqlite3AddDefaultValue(pParse,p); } break; - case 56: + case 56: /* ccons ::= NOT NULL onconf */ {sqlite3AddNotNull(pParse, yymsp[0].minor.yy46);} break; - case 57: + case 57: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */ {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy46,yymsp[0].minor.yy46,yymsp[-2].minor.yy46);} break; - case 58: + case 58: /* ccons ::= UNIQUE onconf */ {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy46,0,0,0,0);} break; - case 59: + case 59: /* ccons ::= CHECK LP expr RP */ {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy172);} break; - case 60: + case 60: /* ccons ::= REFERENCES nm idxlist_opt refargs */ {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy410,yymsp[-1].minor.yy174,yymsp[0].minor.yy46);} break; - case 61: + case 61: /* ccons ::= defer_subclause */ {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy46);} break; - case 62: + case 62: /* ccons ::= COLLATE ids */ {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy410);} break; - case 65: + case 65: /* refargs ::= */ { yygotominor.yy46 = OE_Restrict * 0x010101; } break; - case 66: + case 66: /* refargs ::= refargs refarg */ { yygotominor.yy46 = (yymsp[-1].minor.yy46 & yymsp[0].minor.yy405.mask) | yymsp[0].minor.yy405.value; } break; - case 67: + case 67: /* refarg ::= MATCH nm */ { yygotominor.yy405.value = 0; yygotominor.yy405.mask = 0x000000; } break; - case 68: + case 68: /* refarg ::= ON DELETE refact */ { yygotominor.yy405.value = yymsp[0].minor.yy46; yygotominor.yy405.mask = 0x0000ff; } break; - case 69: + case 69: /* refarg ::= ON UPDATE refact */ { yygotominor.yy405.value = yymsp[0].minor.yy46<<8; yygotominor.yy405.mask = 0x00ff00; } break; - case 70: + case 70: /* refarg ::= ON INSERT refact */ { yygotominor.yy405.value = yymsp[0].minor.yy46<<16; yygotominor.yy405.mask = 0xff0000; } break; - case 71: + case 71: /* refact ::= SET NULL */ { yygotominor.yy46 = OE_SetNull; } break; - case 72: + case 72: /* refact ::= SET DEFAULT */ { yygotominor.yy46 = OE_SetDflt; } break; - case 73: + case 73: /* refact ::= CASCADE */ { yygotominor.yy46 = OE_Cascade; } break; - case 74: + case 74: /* refact ::= RESTRICT */ { yygotominor.yy46 = OE_Restrict; } break; - case 75: - case 76: - case 91: - case 93: - case 95: - case 96: - case 166: + 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 */ {yygotominor.yy46 = yymsp[0].minor.yy46;} break; - case 80: + case 80: /* conslist_opt ::= */ {yygotominor.yy410.n = 0; yygotominor.yy410.z = 0;} break; - case 81: + case 81: /* conslist_opt ::= COMMA conslist */ {yygotominor.yy410 = yymsp[-1].minor.yy0;} break; - case 86: + case 86: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */ {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy174,yymsp[0].minor.yy46,yymsp[-2].minor.yy46,0);} break; - case 87: + case 87: /* tcons ::= UNIQUE LP idxlist RP onconf */ {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy174,yymsp[0].minor.yy46,0,0,0,0);} break; - case 88: + case 88: /* tcons ::= CHECK LP expr RP onconf */ {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy172);} break; - case 89: + case 89: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */ { 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: - case 94: + case 92: /* onconf ::= */ + case 94: /* orconf ::= */ {yygotominor.yy46 = OE_Default;} break; - case 97: + case 97: /* resolvetype ::= IGNORE */ {yygotominor.yy46 = OE_Ignore;} break; - case 98: - case 167: + case 98: /* resolvetype ::= REPLACE */ + case 167: /* insert_cmd ::= REPLACE */ {yygotominor.yy46 = OE_Replace;} break; - case 99: + case 99: /* cmd ::= DROP TABLE ifexists fullname */ { sqlite3DropTable(pParse, yymsp[0].minor.yy373, 0, yymsp[-1].minor.yy46); } break; - case 102: + case 102: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */ { 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: + case 103: /* cmd ::= DROP VIEW ifexists fullname */ { sqlite3DropTable(pParse, yymsp[0].minor.yy373, 1, yymsp[-1].minor.yy46); } break; - case 104: -{ - sqlite3Select(pParse, yymsp[0].minor.yy219, SRT_Callback, 0, 0, 0, 0, 0); + case 104: /* cmd ::= select */ +{ + SelectDest dest = {SRT_Callback, 0, 0}; + sqlite3Select(pParse, yymsp[0].minor.yy219, &dest, 0, 0, 0, 0); sqlite3SelectDelete(yymsp[0].minor.yy219); } break; - case 105: - case 128: + case 105: /* select ::= oneselect */ + case 128: /* seltablist_paren ::= select */ {yygotominor.yy219 = yymsp[0].minor.yy219;} break; - case 106: + case 106: /* select ::= select multiselect_op oneselect */ { if( yymsp[0].minor.yy219 ){ yymsp[0].minor.yy219->op = yymsp[-1].minor.yy46; yymsp[0].minor.yy219->pPrior = yymsp[-2].minor.yy219; }else{ @@ -69262,253 +71294,253 @@ sqlite3SelectDelete(yymsp[-2].minor.yy219); } yygotominor.yy219 = yymsp[0].minor.yy219; } break; - case 108: + case 108: /* multiselect_op ::= UNION ALL */ {yygotominor.yy46 = TK_ALL;} break; - case 110: + case 110: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */ { 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: - case 238: + case 114: /* sclp ::= selcollist COMMA */ + case 238: /* idxlist_opt ::= LP idxlist RP */ {yygotominor.yy174 = yymsp[-1].minor.yy174;} break; - case 115: - case 141: - case 149: - case 231: - case 237: + case 115: /* sclp ::= */ + case 141: /* orderby_opt ::= */ + case 149: /* groupby_opt ::= */ + case 231: /* exprlist ::= */ + case 237: /* idxlist_opt ::= */ {yygotominor.yy174 = 0;} break; - case 116: + case 116: /* selcollist ::= sclp expr as */ { 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: + case 117: /* selcollist ::= sclp STAR */ { Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0); yygotominor.yy174 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy174, p, 0); } break; - case 118: + case 118: /* selcollist ::= sclp nm DOT STAR */ { Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0); 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: + case 121: /* as ::= */ {yygotominor.yy410.n = 0;} break; - case 122: + case 122: /* from ::= */ {yygotominor.yy373 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy373));} break; - case 123: + case 123: /* from ::= FROM seltablist */ { yygotominor.yy373 = yymsp[0].minor.yy373; sqlite3SrcListShiftJoinType(yygotominor.yy373); } break; - case 124: + case 124: /* stl_prefix ::= seltablist joinop */ { 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: + case 125: /* stl_prefix ::= */ {yygotominor.yy373 = 0;} break; - case 126: + case 126: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */ { 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: + case 127: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */ { 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: + case 129: /* seltablist_paren ::= seltablist */ { sqlite3SrcListShiftJoinType(yymsp[0].minor.yy373); yygotominor.yy219 = sqlite3SelectNew(pParse,0,yymsp[0].minor.yy373,0,0,0,0,0,0,0); } break; - case 130: + case 130: /* dbnm ::= */ {yygotominor.yy410.z=0; yygotominor.yy410.n=0;} break; - case 132: + case 132: /* fullname ::= nm dbnm */ {yygotominor.yy373 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410);} break; - case 133: + case 133: /* joinop ::= COMMA|JOIN */ { yygotominor.yy46 = JT_INNER; } break; - case 134: + case 134: /* joinop ::= JOIN_KW JOIN */ { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); } break; - case 135: + case 135: /* joinop ::= JOIN_KW nm JOIN */ { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy410,0); } break; - case 136: + case 136: /* joinop ::= JOIN_KW nm nm JOIN */ { yygotominor.yy46 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy410,&yymsp[-1].minor.yy410); } break; - case 137: - case 145: - case 152: - case 159: - case 174: - case 202: - case 226: - case 228: + 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 */ {yygotominor.yy172 = yymsp[0].minor.yy172;} break; - case 138: - case 151: - case 158: - case 203: - case 227: - case 229: + case 138: /* on_opt ::= */ + case 151: /* having_opt ::= */ + case 158: /* where_opt ::= */ + case 203: /* escape ::= */ + case 227: /* case_else ::= */ + case 229: /* case_operand ::= */ {yygotominor.yy172 = 0;} break; - case 139: - case 171: + case 139: /* using_opt ::= USING LP inscollist RP */ + case 171: /* inscollist_opt ::= LP inscollist RP */ {yygotominor.yy432 = yymsp[-1].minor.yy432;} break; - case 140: - case 170: + case 140: /* using_opt ::= */ + case 170: /* inscollist_opt ::= */ {yygotominor.yy432 = 0;} break; - case 142: - case 150: - case 230: + case 142: /* orderby_opt ::= ORDER BY sortlist */ + case 150: /* groupby_opt ::= GROUP BY nexprlist */ + case 230: /* exprlist ::= nexprlist */ {yygotominor.yy174 = yymsp[0].minor.yy174;} break; - case 143: + case 143: /* sortlist ::= sortlist COMMA sortitem sortorder */ { 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: + case 144: /* sortlist ::= sortitem sortorder */ { 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: - case 148: + case 146: /* sortorder ::= ASC */ + case 148: /* sortorder ::= */ {yygotominor.yy46 = SQLITE_SO_ASC;} break; - case 147: + case 147: /* sortorder ::= DESC */ {yygotominor.yy46 = SQLITE_SO_DESC;} break; - case 153: + case 153: /* limit_opt ::= */ {yygotominor.yy234.pLimit = 0; yygotominor.yy234.pOffset = 0;} break; - case 154: + case 154: /* limit_opt ::= LIMIT expr */ {yygotominor.yy234.pLimit = yymsp[0].minor.yy172; yygotominor.yy234.pOffset = 0;} break; - case 155: + case 155: /* limit_opt ::= LIMIT expr OFFSET expr */ {yygotominor.yy234.pLimit = yymsp[-2].minor.yy172; yygotominor.yy234.pOffset = yymsp[0].minor.yy172;} break; - case 156: + case 156: /* limit_opt ::= LIMIT expr COMMA expr */ {yygotominor.yy234.pOffset = yymsp[-2].minor.yy172; yygotominor.yy234.pLimit = yymsp[0].minor.yy172;} break; - case 157: + case 157: /* cmd ::= DELETE FROM fullname where_opt */ {sqlite3DeleteFrom(pParse,yymsp[-1].minor.yy373,yymsp[0].minor.yy172);} break; - case 160: + case 160: /* cmd ::= UPDATE orconf fullname SET setlist where_opt */ { 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: + case 161: /* setlist ::= setlist COMMA nm EQ expr */ {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy174,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);} break; - case 162: + case 162: /* setlist ::= nm EQ expr */ {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,&yymsp[-2].minor.yy410);} break; - case 163: + case 163: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */ {sqlite3Insert(pParse, yymsp[-5].minor.yy373, yymsp[-1].minor.yy174, 0, yymsp[-4].minor.yy432, yymsp[-7].minor.yy46);} break; - case 164: + case 164: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */ {sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);} break; - case 165: + case 165: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */ {sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);} break; - case 168: - case 232: + case 168: /* itemlist ::= itemlist COMMA expr */ + case 232: /* nexprlist ::= nexprlist COMMA expr */ {yygotominor.yy174 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);} break; - case 169: - case 233: + case 169: /* itemlist ::= expr */ + case 233: /* nexprlist ::= expr */ {yygotominor.yy174 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy172,0);} break; - case 172: + case 172: /* inscollist ::= inscollist COMMA nm */ {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);} break; - case 173: + case 173: /* inscollist ::= nm */ {yygotominor.yy432 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy410);} break; - case 175: + case 175: /* expr ::= LP expr RP */ {yygotominor.yy172 = yymsp[-1].minor.yy172; sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); } break; - case 176: - case 181: - case 182: + case 176: /* term ::= NULL */ + case 181: /* term ::= INTEGER|FLOAT|BLOB */ + case 182: /* term ::= STRING */ {yygotominor.yy172 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);} break; - case 177: - case 178: + case 177: /* expr ::= ID */ + case 178: /* expr ::= JOIN_KW */ {yygotominor.yy172 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);} break; - case 179: + case 179: /* expr ::= nm DOT nm */ { 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: + case 180: /* expr ::= nm DOT nm DOT nm */ { 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: + case 183: /* expr ::= REGISTER */ {yygotominor.yy172 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);} break; - case 184: + case 184: /* expr ::= VARIABLE */ { Token *pToken = &yymsp[0].minor.yy0; Expr *pExpr = yygotominor.yy172 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken); sqlite3ExprAssignVarNumber(pParse, pExpr); } break; - case 185: + case 185: /* expr ::= expr COLLATE ids */ { yygotominor.yy172 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy172, &yymsp[0].minor.yy410); } break; - case 186: + case 186: /* expr ::= CAST LP expr AS typetoken RP */ { 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: + case 187: /* expr ::= ID LP distinct exprlist RP */ { 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); } yygotominor.yy172 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy174, &yymsp[-4].minor.yy0); @@ -69516,17 +71548,17 @@ if( yymsp[-2].minor.yy46 && yygotominor.yy172 ){ yygotominor.yy172->flags |= EP_Distinct; } } break; - case 188: + case 188: /* expr ::= ID LP STAR RP */ { yygotominor.yy172 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); } break; - case 189: + case 189: /* term ::= CTIME_KW */ { /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are ** treated as functions that return constants */ yygotominor.yy172 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0); if( yygotominor.yy172 ){ @@ -69533,29 +71565,29 @@ yygotominor.yy172->op = TK_CONST_FUNC; yygotominor.yy172->span = yymsp[0].minor.yy0; } } break; - case 190: - case 191: - case 192: - case 193: - case 194: - case 195: - case 196: - case 197: + 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 */ {yygotominor.yy172 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy172,yymsp[0].minor.yy172,0);} break; - case 198: - case 200: + case 198: /* likeop ::= LIKE_KW */ + case 200: /* likeop ::= MATCH */ {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 0;} break; - case 199: - case 201: + case 199: /* likeop ::= NOT LIKE_KW */ + case 201: /* likeop ::= NOT MATCH */ {yygotominor.yy72.eOperator = yymsp[0].minor.yy0; yygotominor.yy72.not = 1;} break; - case 204: + case 204: /* expr ::= expr likeop expr escape */ { ExprList *pList; pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy172, 0); pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy172, 0); if( yymsp[0].minor.yy172 ){ @@ -69565,54 +71597,54 @@ if( yymsp[-2].minor.yy72.not ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy172->span, &yymsp[-1].minor.yy172->span); if( yygotominor.yy172 ) yygotominor.yy172->flags |= EP_InfixFunc; } break; - case 205: + case 205: /* expr ::= expr ISNULL|NOTNULL */ { 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: + case 206: /* expr ::= expr IS NULL */ { 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: + case 207: /* expr ::= expr NOT NULL */ { 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: + case 208: /* expr ::= expr IS NOT NULL */ { 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: - case 210: + case 209: /* expr ::= NOT expr */ + case 210: /* expr ::= BITNOT expr */ { 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: + case 211: /* expr ::= MINUS expr */ { 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: + case 212: /* expr ::= PLUS expr */ { 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: + case 215: /* expr ::= expr between_op expr AND expr */ { ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0); pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy172, 0); yygotominor.yy172 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy172, 0, 0); if( yygotominor.yy172 ){ @@ -69622,11 +71654,11 @@ } if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy172->span); } break; - case 218: + case 218: /* expr ::= expr in_op LP exprlist RP */ { yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pList = yymsp[-1].minor.yy174; sqlite3ExprSetHeight(yygotominor.yy172); @@ -69635,11 +71667,11 @@ } if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 219: + case 219: /* expr ::= LP select RP */ { yygotominor.yy172 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pSelect = yymsp[-1].minor.yy219; sqlite3ExprSetHeight(yygotominor.yy172); @@ -69647,11 +71679,11 @@ sqlite3SelectDelete(yymsp[-1].minor.yy219); } sqlite3ExprSpan(yygotominor.yy172,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); } break; - case 220: + case 220: /* expr ::= expr in_op LP select RP */ { yygotominor.yy172 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy172, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->pSelect = yymsp[-1].minor.yy219; sqlite3ExprSetHeight(yygotominor.yy172); @@ -69660,11 +71692,11 @@ } if( yymsp[-3].minor.yy46 ) yygotominor.yy172 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy172, 0, 0); sqlite3ExprSpan(yygotominor.yy172,&yymsp[-4].minor.yy172->span,&yymsp[0].minor.yy0); } break; - case 221: + case 221: /* expr ::= expr in_op nm dbnm */ { 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); @@ -69674,11 +71706,11 @@ } 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.yy410.z?&yymsp[0].minor.yy410:&yymsp[-1].minor.yy410); } break; - case 222: + case 222: /* expr ::= EXISTS LP select RP */ { 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); @@ -69686,11 +71718,11 @@ }else{ sqlite3SelectDelete(yymsp[-1].minor.yy219); } } break; - case 223: + case 223: /* expr ::= CASE case_operand case_exprlist case_else END */ { 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(yygotominor.yy172); @@ -69698,37 +71730,37 @@ sqlite3ExprListDelete(yymsp[-2].minor.yy174); } sqlite3ExprSpan(yygotominor.yy172, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0); } break; - case 224: + case 224: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */ { 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 225: /* case_exprlist ::= WHEN expr THEN expr */ { yygotominor.yy174 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy172, 0); yygotominor.yy174 = sqlite3ExprListAppend(pParse,yygotominor.yy174, yymsp[0].minor.yy172, 0); } break; - case 234: + case 234: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */ { 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: - case 282: + case 235: /* uniqueflag ::= UNIQUE */ + case 282: /* raisetype ::= ABORT */ {yygotominor.yy46 = OE_Abort;} break; - case 236: + case 236: /* uniqueflag ::= */ {yygotominor.yy46 = OE_None;} break; - case 239: + case 239: /* idxlist ::= idxlist COMMA idxitem collate sortorder */ { Expr *p = 0; if( yymsp[-1].minor.yy410.n>0 ){ p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0); sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410); @@ -69736,11 +71768,11 @@ 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: + case 240: /* idxlist ::= idxitem collate sortorder */ { Expr *p = 0; if( yymsp[-1].minor.yy410.n>0 ){ p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0); sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy410); @@ -69748,75 +71780,77 @@ 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: + case 242: /* collate ::= */ {yygotominor.yy410.z = 0; yygotominor.yy410.n = 0;} break; - case 244: + case 244: /* cmd ::= DROP INDEX ifexists fullname */ {sqlite3DropIndex(pParse, yymsp[0].minor.yy373, yymsp[-1].minor.yy46);} break; - case 245: - case 246: + case 245: /* cmd ::= VACUUM */ + case 246: /* cmd ::= VACUUM nm */ {sqlite3Vacuum(pParse);} break; - case 247: + case 247: /* cmd ::= PRAGMA nm dbnm EQ nmnum */ {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,0);} break; - case 248: + case 248: /* cmd ::= PRAGMA nm dbnm EQ ON */ {sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy0,0);} break; - case 249: + case 249: /* cmd ::= PRAGMA nm dbnm EQ minus_num */ { sqlite3Pragma(pParse,&yymsp[-3].minor.yy410,&yymsp[-2].minor.yy410,&yymsp[0].minor.yy410,1); } break; - case 250: + case 250: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */ {sqlite3Pragma(pParse,&yymsp[-4].minor.yy410,&yymsp[-3].minor.yy410,&yymsp[-1].minor.yy410,0);} break; - case 251: + case 251: /* cmd ::= PRAGMA nm dbnm */ {sqlite3Pragma(pParse,&yymsp[-1].minor.yy410,&yymsp[0].minor.yy410,0,0);} break; - case 259: + case 259: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */ { Token all; 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 260: + case 260: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */ { 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 261: - case 264: + case 261: /* trigger_time ::= BEFORE */ + case 264: /* trigger_time ::= */ { yygotominor.yy46 = TK_BEFORE; } break; - case 262: + case 262: /* trigger_time ::= AFTER */ { yygotominor.yy46 = TK_AFTER; } break; - case 263: + case 263: /* trigger_time ::= INSTEAD OF */ { yygotominor.yy46 = TK_INSTEAD;} break; - case 265: - case 266: + case 265: /* trigger_event ::= DELETE|INSERT */ + case 266: /* trigger_event ::= UPDATE */ {yygotominor.yy370.a = yymsp[0].major; yygotominor.yy370.b = 0;} break; - case 267: + case 267: /* trigger_event ::= UPDATE OF inscollist */ {yygotominor.yy370.a = TK_UPDATE; yygotominor.yy370.b = yymsp[0].minor.yy432;} break; - case 270: + case 270: /* when_clause ::= */ + case 287: /* key_opt ::= */ { yygotominor.yy172 = 0; } break; - case 271: + case 271: /* when_clause ::= WHEN expr */ + case 288: /* key_opt ::= KEY expr */ { yygotominor.yy172 = yymsp[0].minor.yy172; } break; - case 272: + case 272: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */ { if( yymsp[-2].minor.yy243 ){ yymsp[-2].minor.yy243->pLast->pNext = yymsp[-1].minor.yy243; }else{ yymsp[-2].minor.yy243 = yymsp[-1].minor.yy243; @@ -69823,118 +71857,112 @@ } yymsp[-2].minor.yy243->pLast = yymsp[-1].minor.yy243; yygotominor.yy243 = yymsp[-2].minor.yy243; } break; - case 273: + case 273: /* trigger_cmd_list ::= */ { yygotominor.yy243 = 0; } break; - case 274: + case 274: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */ { yygotominor.yy243 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy410, yymsp[-1].minor.yy174, yymsp[0].minor.yy172, yymsp[-4].minor.yy46); } break; - case 275: + case 275: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */ {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy410, yymsp[-4].minor.yy432, yymsp[-1].minor.yy174, 0, yymsp[-7].minor.yy46);} break; - case 276: + case 276: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */ {yygotominor.yy243 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy410, yymsp[-1].minor.yy432, 0, yymsp[0].minor.yy219, yymsp[-4].minor.yy46);} break; - case 277: + case 277: /* trigger_cmd ::= DELETE FROM nm where_opt */ {yygotominor.yy243 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy410, yymsp[0].minor.yy172);} break; - case 278: + case 278: /* trigger_cmd ::= select */ {yygotominor.yy243 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy219); } break; - case 279: + case 279: /* expr ::= RAISE LP IGNORE RP */ { yygotominor.yy172 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); if( yygotominor.yy172 ){ yygotominor.yy172->iColumn = OE_Ignore; sqlite3ExprSpan(yygotominor.yy172, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0); } } break; - case 280: + case 280: /* expr ::= RAISE LP raisetype COMMA nm RP */ { 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 281: + case 281: /* raisetype ::= ROLLBACK */ {yygotominor.yy46 = OE_Rollback;} break; - case 283: + case 283: /* raisetype ::= FAIL */ {yygotominor.yy46 = OE_Fail;} break; - case 284: + case 284: /* cmd ::= DROP TRIGGER ifexists fullname */ { sqlite3DropTrigger(pParse,yymsp[0].minor.yy373,yymsp[-1].minor.yy46); } break; - case 285: + case 285: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */ { - sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy386); -} - break; - case 286: + sqlite3Attach(pParse, yymsp[-3].minor.yy172, yymsp[-1].minor.yy172, yymsp[0].minor.yy172); +} + break; + case 286: /* cmd ::= DETACH database_kw_opt expr */ { sqlite3Detach(pParse, yymsp[0].minor.yy172); } break; - case 287: -{ yygotominor.yy386 = 0; } - break; - case 288: -{ yygotominor.yy386 = yymsp[0].minor.yy172; } - break; - case 291: + case 291: /* cmd ::= REINDEX */ {sqlite3Reindex(pParse, 0, 0);} break; - case 292: + case 292: /* cmd ::= REINDEX nm dbnm */ {sqlite3Reindex(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);} break; - case 293: + case 293: /* cmd ::= ANALYZE */ {sqlite3Analyze(pParse, 0, 0);} break; - case 294: + case 294: /* cmd ::= ANALYZE nm dbnm */ {sqlite3Analyze(pParse, &yymsp[-1].minor.yy410, &yymsp[0].minor.yy410);} break; - case 295: + case 295: /* cmd ::= ALTER TABLE fullname RENAME TO nm */ { sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy373,&yymsp[0].minor.yy410); } break; - case 296: + case 296: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */ { sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy410); } break; - case 297: + case 297: /* add_column_fullname ::= fullname */ { sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy373); } break; - case 300: + case 300: /* cmd ::= create_vtab */ {sqlite3VtabFinishParse(pParse,0);} break; - case 301: + case 301: /* cmd ::= create_vtab LP vtabarglist RP */ {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);} break; - case 302: + case 302: /* create_vtab ::= CREATE VIRTUAL TABLE nm dbnm USING nm */ { sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy410, &yymsp[-2].minor.yy410, &yymsp[0].minor.yy410); } break; - case 305: + case 305: /* vtabarg ::= */ {sqlite3VtabArgInit(pParse);} break; - case 307: - case 308: - case 309: - case 311: + case 307: /* vtabargtoken ::= ANY */ + case 308: /* vtabargtoken ::= lp anylist RP */ + case 309: /* lp ::= LP */ + case 311: /* anylist ::= anylist ANY */ {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);} break; }; yygoto = yyRuleInfo[yyruleno].lhs; yysize = yyRuleInfo[yyruleno].nrhs; @@ -69955,11 +71983,12 @@ }else #endif { yy_shift(yypParser,yyact,yygoto,&yygotominor); } - }else if( yyact == YYNSTATE + YYNRULE + 1 ){ + }else{ + assert( yyact == YYNSTATE + YYNRULE + 1 ); yy_accept(yypParser); } } /* @@ -69989,18 +72018,13 @@ YYMINORTYPE yyminor /* The minor type of the error token */ ){ sqlite3ParserARG_FETCH; #define TOKEN (yyminor.yy0) - if( !pParse->parseError ){ - if( TOKEN.z[0] ){ - sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); - }else{ - sqlite3ErrorMsg(pParse, "incomplete SQL statement"); - } - pParse->parseError = 1; - } + assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */ + sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN); + pParse->parseError = 1; sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */ } /* ** The following is executed when the parser accepts @@ -70046,11 +72070,13 @@ sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */ ){ 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 */ yypParser = (yyParser*)yyp; if( yypParser->yyidx<0 ){ @@ -70077,21 +72103,21 @@ #endif do{ yyact = yy_find_shift_action(yypParser,yymajor); if( yyact<YYNSTATE ){ + assert( !yyendofinput ); /* Impossible to shift the $ token */ yy_shift(yypParser,yyact,yymajor,&yyminorunion); yypParser->yyerrcnt--; - if( yyendofinput && yypParser->yyidx>=0 ){ - yymajor = 0; - }else{ - yymajor = YYNOCODE; - } + yymajor = YYNOCODE; }else if( yyact < YYNSTATE + YYNRULE ){ yy_reduce(yypParser,yyact-YYNSTATE); - }else if( yyact == YY_ERROR_ACTION ){ + }else{ + assert( yyact == YY_ERROR_ACTION ); +#ifdef YYERRORSYMBOL int yymx; +#endif #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt); } #endif @@ -70168,13 +72194,10 @@ if( yyendofinput ){ yy_parse_failed(yypParser); } yymajor = YYNOCODE; #endif - }else{ - yy_accept(yypParser); - yymajor = YYNOCODE; } }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 ); return; } @@ -70195,11 +72218,11 @@ ** ** This file contains C code that splits an SQL input string up into ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. ** -** $Id: tokenize.c,v 1.136 2007/08/27 23:26:59 drh Exp $ +** $Id: tokenize.c,v 1.138 2008/01/22 23:37:10 drh Exp $ */ /* ** The charMap() macro maps alphabetic characters into their ** lower-case ASCII equivalent. On ASCII machines, this is just @@ -70271,12 +72294,12 @@ "WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICT" "CROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOB" "YIFINTOFFSETISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUM" "VIEWINITIALLY"; static const unsigned char aHash[127] = { - 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, + 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, 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, 83, 0, 0, 116, 93, 47, 115, 41, 12, 44, 0, 78, 0, 87, 29, 0, 86, 0, 0, 0, 82, 79, 84, 75, 96, 6, @@ -70286,26 +72309,26 @@ }; static const unsigned char aNext[116] = { 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, 38, 0, 0, 25, 0, 0, 31, 0, + 17, 0, 0, 0, 36, 39, 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, - 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, + 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, 0, 0, 105, 23, 30, 60, 70, 0, 0, 59, 0, 0, }; static const unsigned char aLen[116] = { - 6, 3, 7, 6, 6, 7, 7, 3, 4, 6, 4, 5, 3, + 6, 7, 3, 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, 9, 4, + 5, 4, 6, 7, 10, 6, 5, 6, 6, 5, 6, 4, 9, 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, 2, 6, 3, 6, + 2, 4, 4, 4, 4, 4, 2, 2, 4, 6, 2, 3, 6, 5, 8, 5, 5, 8, 3, 5, 5, 6, 4, 9, 3, }; static const unsigned short int aOffset[116] = { 0, 2, 2, 6, 10, 13, 18, 23, 25, 26, 31, 33, 37, 40, 47, 55, 58, 61, 63, 65, 70, 71, 76, 85, 86, 91, @@ -70316,11 +72339,11 @@ 346, 348, 350, 359, 363, 369, 375, 383, 388, 388, 404, 411, 418, 419, 426, 430, 434, 438, 442, 445, 447, 449, 452, 452, 455, 458, 464, 468, 476, 480, 485, 493, 496, 501, 506, 512, 516, 521, }; static const unsigned char aCode[116] = { - TK_BEFORE, TK_FOR, TK_FOREIGN, TK_IGNORE, TK_LIKE_KW, + TK_BEFORE, TK_FOREIGN, TK_FOR, 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, TK_AS, TK_SELECT, TK_TRANSACTION,TK_ON, TK_JOIN_KW, TK_ALTER, TK_RAISE, TK_ELSE, TK_EXCEPT, TK_TRIGGER, @@ -70336,11 +72359,11 @@ TK_REPLACE, TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, 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_OF, TK_OFFSET, TK_SET, TK_ISNULL, TK_ORDER, + TK_OFFSET, TK_OF, 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, }; int h, i; @@ -70585,11 +72608,11 @@ } return i; } case '[': { for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){} - *tokenType = TK_ID; + *tokenType = c==']' ? TK_ID : TK_ILLEGAL; return i; } case '?': { *tokenType = TK_VARIABLE; for(i=1; isdigit(z[i]); i++){} @@ -70637,23 +72660,18 @@ if( n==0 ) *tokenType = TK_ILLEGAL; return i; } #ifndef SQLITE_OMIT_BLOB_LITERAL case 'x': case 'X': { - if( (c=z[1])=='\'' || c=='"' ){ - int delim = c; + if( z[1]=='\'' ){ *tokenType = TK_BLOB; - for(i=2; (c=z[i])!=0; i++){ - if( c==delim ){ - if( i%2 ) *tokenType = TK_ILLEGAL; - break; - } + for(i=2; (c=z[i])!=0 && c!='\''; i++){ if( !isxdigit(c) ){ *tokenType = TK_ILLEGAL; - return i; } } + if( i%2 || !c ) *tokenType = TK_ILLEGAL; if( c ) i++; return i; } /* Otherwise fall through to the next case */ } @@ -70711,11 +72729,11 @@ assert( i>=0 ); pParse->sLastToken.z = (u8*)&zSql[i]; assert( pParse->sLastToken.dyn==0 ); pParse->sLastToken.n = getToken((unsigned char*)&zSql[i],&tokenType); i += pParse->sLastToken.n; - if( i>SQLITE_MAX_SQL_LENGTH ){ + if( SQLITE_MAX_SQL_LENGTH>0 && i>SQLITE_MAX_SQL_LENGTH ){ pParse->rc = SQLITE_TOOBIG; break; } switch( tokenType ){ case TK_SPACE: @@ -70770,11 +72788,11 @@ *pzErrMsg = pParse->zErrMsg; }else{ sqlite3_free(pParse->zErrMsg); } pParse->zErrMsg = 0; - if( !nErr ) nErr++; + nErr++; } if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){ sqlite3VdbeDelete(pParse->pVdbe); pParse->pVdbe = 0; } @@ -71091,12 +73109,44 @@ ** Main file for the SQLite library. The routines in this file ** implement the programmer interface to the library. Routines in ** other files are for internal use by SQLite and should not be ** accessed by users of the library. ** -** $Id: main.c,v 1.407 2007/10/12 19:35:49 drh Exp $ -*/ +** $Id: main.c,v 1.417 2008/01/31 15:31:02 danielk1977 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 /* ** The version of the library */ SQLITE_API const char sqlite3_version[] = SQLITE_VERSION; @@ -71121,23 +73171,41 @@ */ SQLITE_API char *sqlite3_temp_directory = 0; /* +** 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]==' ' ){} + 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 *NotUsed, + void *padFlag, int nKey1, const void *pKey1, int nKey2, const void *pKey2 ){ int rc, n; n = nKey1<nKey2 ? nKey1 : nKey2; rc = memcmp(pKey1, pKey2, n); if( rc==0 ){ - rc = nKey1 - nKey2; + if( padFlag + && allSpaces(((char*)pKey1)+n, nKey1-n) + && allSpaces(((char*)pKey2)+n, nKey2-n) + ){ + /* Leave rc unchanged at 0 */ + }else{ + rc = nKey1 - nKey2; + } } return rc; } /* @@ -71191,11 +73259,11 @@ int j; if( !db ){ return SQLITE_OK; } - if( sqlite3SafetyCheck(db) ){ + if( !sqlite3SafetyCheckSickOrOk(db) ){ return SQLITE_MISUSE; } sqlite3_mutex_enter(db->mutex); #ifdef SQLITE_SSE @@ -71221,25 +73289,11 @@ sqlite3Error(db, SQLITE_BUSY, "Unable to close due to unfinalised statements"); sqlite3_mutex_leave(db->mutex); return SQLITE_BUSY; } - 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; - } + assert( sqlite3SafetyCheckSickOrOk(db) ); for(j=0; j<db->nDb; j++){ struct Db *pDb = &db->aDb[j]; if( pDb->pBt ){ sqlite3BtreeClose(pDb->pBt); @@ -71297,10 +73351,11 @@ ** the same sqliteMalloc() as the one that allocates the database ** structure? */ 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; } @@ -71309,11 +73364,11 @@ */ SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){ int i; int inTrans = 0; assert( sqlite3_mutex_held(db->mutex) ); - sqlite3MallocEnterBenignBlock(1); /* Enter benign region */ + sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 1); for(i=0; i<db->nDb; i++){ if( db->aDb[i].pBt ){ if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){ inTrans = 1; } @@ -71320,11 +73375,11 @@ sqlite3BtreeRollback(db->aDb[i].pBt); db->aDb[i].inTrans = 0; } } sqlite3VtabRollback(db); - sqlite3MallocLeaveBenignBlock(); /* Leave benign region */ + sqlite3FaultBenign(SQLITE_FAULTINJECTOR_MALLOC, 0); if( db->flags&SQLITE_InternChanges ){ sqlite3ExpirePreparedStatements(db); sqlite3ResetInternalSchema(db, 0); } @@ -71444,13 +73499,10 @@ SQLITE_API int sqlite3_busy_handler( sqlite3 *db, 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; db->busyHandler.nBusy = 0; sqlite3_mutex_leave(db->mutex); @@ -71467,11 +73519,11 @@ sqlite3 *db, int nOps, int (*xProgress)(void*), void *pArg ){ - if( !sqlite3SafetyCheck(db) ){ + if( sqlite3SafetyCheckOk(db) ){ sqlite3_mutex_enter(db->mutex); if( nOps>0 ){ db->xProgress = xProgress; db->nProgressOps = nOps; db->pProgressArg = pArg; @@ -71489,13 +73541,10 @@ /* ** This routine installs a default busy handler that waits for the ** 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); }else{ sqlite3_busy_handler(db, 0, 0); @@ -71505,11 +73554,11 @@ /* ** Cause any pending operation to stop at its earliest opportunity. */ SQLITE_API void sqlite3_interrupt(sqlite3 *db){ - if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){ + if( sqlite3SafetyCheckOk(db) ){ db->u1.isInterrupted = 1; } } @@ -71531,13 +73580,10 @@ ){ FuncDef *p; 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>127) || @@ -71841,11 +73887,10 @@ if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){ vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB; } rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags); if( rc==SQLITE_OK ){ - sqlite3BtreeSetBusyHandler(*ppBtree, (void*)&db->busyHandler); sqlite3BtreeSetCacheSize(*ppBtree, nCache); } return rc; } @@ -71856,11 +73901,11 @@ SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){ const char *z; if( !db ){ return sqlite3ErrStr(SQLITE_NOMEM); } - if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){ + if( !sqlite3SafetyCheckSickOrOk(db) || db->errCode==SQLITE_MISUSE ){ return sqlite3ErrStr(SQLITE_MISUSE); } sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); z = (char*)sqlite3_value_text(db->pErr); @@ -71898,11 +73943,11 @@ const void *z; if( !db ){ return (void *)(&outOfMemBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]); } - if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){ + if( !sqlite3SafetyCheckSickOrOk(db) || db->errCode==SQLITE_MISUSE ){ return (void *)(&misuseBe[SQLITE_UTF16NATIVE==SQLITE_UTF16LE?1:0]); } sqlite3_mutex_enter(db->mutex); assert( !db->mallocFailed ); z = sqlite3_value_text16(db->pErr); @@ -71920,15 +73965,15 @@ /* ** Return the most recent error code generated by an SQLite routine. If NULL is ** 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; } /* @@ -71944,13 +73989,10 @@ void(*xDel)(void*) ){ CollSeq *pColl; int enc2; - if( sqlite3SafetyCheck(db) ){ - return SQLITE_MISUSE; - } assert( sqlite3_mutex_held(db->mutex) ); /* If SQLITE_UTF16 is specified as the encoding type, transform this ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally. @@ -72040,10 +74082,11 @@ db->priorNewRowid = 0; db->nDb = 2; db->magic = SQLITE_MAGIC_BUSY; db->aDb = db->aDbStatic; db->autoCommit = 1; + db->nextAutovac = -1; db->flags |= SQLITE_ShortColNames #if SQLITE_DEFAULT_FILE_FORMAT<4 | SQLITE_LegacyFileFmt #endif #ifdef SQLITE_ENABLE_LOAD_EXTENSION @@ -72057,11 +74100,11 @@ #endif db->pVfs = sqlite3_vfs_find(zVfs); if( !db->pVfs ){ rc = SQLITE_ERROR; - db->magic = SQLITE_MAGIC_CLOSED; + db->magic = SQLITE_MAGIC_SICK; sqlite3Error(db, rc, "no such vfs: %s", (zVfs?zVfs:"(null)")); goto opendb_out; } /* Add the default collation sequence BINARY. BINARY works for both UTF-8 @@ -72069,14 +74112,15 @@ ** conversions. The only error that can occur here is a malloc() failure. */ 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) || + createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0) || (db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 6, 0))==0 ){ assert( db->mallocFailed ); - db->magic = SQLITE_MAGIC_CLOSED; + db->magic = SQLITE_MAGIC_SICK; goto opendb_out; } /* Also add a UTF-8 case-insensitive collation sequence. */ createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0); @@ -72093,11 +74137,11 @@ rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, flags | SQLITE_OPEN_MAIN_DB, &db->aDb[0].pBt); if( rc!=SQLITE_OK ){ sqlite3Error(db, rc, 0); - db->magic = SQLITE_MAGIC_CLOSED; + db->magic = SQLITE_MAGIC_SICK; goto opendb_out; } db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt); db->aDb[1].pSchema = sqlite3SchemaGet(db, 0); @@ -72146,11 +74190,10 @@ } #endif #ifdef SQLITE_ENABLE_FTS3 if( !db->mallocFailed && rc==SQLITE_OK ){ - extern int sqlite3Fts3Init(sqlite3*); rc = sqlite3Fts3Init(db); } #endif #ifdef SQLITE_ENABLE_ICU @@ -72309,13 +74352,10 @@ SQLITE_API int sqlite3_collation_needed( sqlite3 *db, 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; db->pCollNeededArg = pCollNeededArg; sqlite3_mutex_leave(db->mutex); @@ -72330,13 +74370,10 @@ SQLITE_API int sqlite3_collation_needed16( sqlite3 *db, 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; db->pCollNeededArg = pCollNeededArg; sqlite3_mutex_leave(db->mutex); @@ -72414,13 +74451,11 @@ int notnull = 0; int primarykey = 0; int autoinc = 0; /* Ensure the database schema has been loaded */ - if( sqlite3SafetyOn(db) ){ - return SQLITE_MISUSE; - } + (void)sqlite3SafetyOn(db); sqlite3_mutex_enter(db->mutex); rc = sqlite3Init(db, &zErrMsg); if( SQLITE_OK!=rc ){ goto error_out; } @@ -72474,13 +74509,11 @@ if( !zCollSeq ){ zCollSeq = "BINARY"; } error_out: - if( sqlite3SafetyOff(db) ){ - rc = SQLITE_MISUSE; - } + (void)sqlite3SafetyOff(db); /* Whether the function call succeeded or failed, set the output parameters ** to whatever their local counterparts contain. If an error did occur, ** this has the effect of zeroing all output parameters. */ @@ -72544,36 +74577,64 @@ } if( iDb<db->nDb ){ Btree *pBtree = db->aDb[iDb].pBt; if( pBtree ){ Pager *pPager; + sqlite3_file *fd; sqlite3BtreeEnter(pBtree); pPager = sqlite3BtreePager(pBtree); - if( pPager ){ - sqlite3_file *fd = sqlite3PagerFile(pPager); - if( fd ){ - rc = sqlite3OsFileControl(fd, op, pArg); - } + assert( pPager!=0 ); + fd = sqlite3PagerFile(pPager); + assert( fd!=0 ); + if( fd->pMethods ){ + rc = sqlite3OsFileControl(fd, op, pArg); } sqlite3BtreeLeave(pBtree); } } sqlite3_mutex_leave(db->mutex); 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 2007-11-25 16:04:39 UTC. -*/ +/* +** Interface to the testing logic. +*/ +SQLITE_API int sqlite3_test_control(int op, ...){ + va_list ap; + int rc = 0; + va_start(ap, op); + switch( op ){ +#ifndef SQLITE_OMIT_FAULTINJECTOR + case SQLITE_TESTCTRL_FAULT_CONFIG: { + int id = va_arg(ap, int); + int nDelay = va_arg(ap, int); + int nRepeat = va_arg(ap, int); + sqlite3FaultConfig(id, nDelay, nRepeat); + break; + } + case SQLITE_TESTCTRL_FAULT_FAILURES: { + int id = va_arg(ap, int); + rc = sqlite3FaultFailures(id); + break; + } + case SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES: { + int id = va_arg(ap, int); + rc = sqlite3FaultBenignFailures(id); + break; + } + case SQLITE_TESTCTRL_FAULT_PENDING: { + int id = va_arg(ap, int); + rc = sqlite3FaultPending(id); + break; + } +#endif /* SQLITE_OMIT_FAULTINJECTOR */ + } + va_end(ap); + return rc; +} + +/************** End of main.c ************************************************/ /************** Begin file fts3.c ********************************************/ /* ** 2006 Oct 10 ** ** The author disclaims copyright to this source code. In place of @@ -72823,11 +74884,11 @@ ** frequent terms (which are somewhat dominated by segment merge ** costs), and infrequent and non-existent terms still seem to be fast ** even with many segments. ** ** TODO(shess) That said, it would be nice to have a better query-side -** argument for MERGE_COUNT of 16. Also, it's possible/likely that +** argument for MERGE_COUNT of 16. Also, it is possible/likely that ** optimizations to things like doclist merging will swing the sweet ** spot around. ** ** ** @@ -72851,3581 +74912,11 @@ #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE) # define SQLITE_CORE 1 #endif -#include <assert.h> -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <ctype.h> - -/************** 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh Exp $ -*/ -#ifndef _SQLITE3_H_ -#define _SQLITE3_H_ -#include <stdarg.h> /* 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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 -** -** 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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 ***************************************/ /* ** 2001 September 22 ** @@ -76497,14 +74988,14 @@ #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*); +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*); /* ** Shorthand for the functions above */ #define fts3HashInit sqlite3Fts3HashInit @@ -76565,3759 +75056,224 @@ /* 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh Exp $ -*/ -#ifndef _SQLITE3_H_ -#define _SQLITE3_H_ - -/* -** Make sure we can call this stuff from C++. -*/ + +/* +** 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 <tokenizer-name> 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.c ***********************/ +#ifndef SQLITE_CORE + SQLITE_EXTENSION_INIT1 +#endif + + +/* TODO(shess) MAN, this thing needs some refactoring. At minimum, it +** would be nice to order the file better, perhaps something along the +** lines of: +** +** - utility functions +** - table setup functions +** - table update functions +** - table query functions +** +** Put the query functions last because they're likely to reference +** typedefs or functions from the table update section. +*/ + #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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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; +# define FTSTRACE(A) printf A; fflush(stdout) #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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 */ +# define FTSTRACE(A) +#endif + +/* +** Default span for NEAR operators. +*/ +#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 + +/* It is not safe to call isspace(), tolower(), or isalnum() on +** hi-bit-set characters. This is the same solution used in the +** tokenizer. +*/ +/* TODO(shess) The snippet-generation code should be using the +** tokenizer-generated tokens rather than doing its own local +** tokenization. +*/ +/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */ +static int safe_isspace(char c){ + return (c&0x80)==0 ? isspace(c) : 0; +} +static int safe_tolower(char c){ + return (c&0x80)==0 ? tolower(c) : c; +} +static int safe_isalnum(char c){ + return (c&0x80)==0 ? isalnum(c) : 0; +} + +typedef enum DocListType { + DL_DOCIDS, /* docids only */ + DL_POSITIONS, /* docids + positions */ + DL_POSITIONS_OFFSETS /* docids + positions + offsets */ +} DocListType; + +/* +** By default, only positions and not offsets are stored in the doclists. +** To change this so that offsets are stored too, compile with +** +** -DDL_DEFAULT=DL_POSITIONS_OFFSETS +** +** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted +** into (no deletes or updates). +*/ +#ifndef DL_DEFAULT +# define DL_DEFAULT DL_POSITIONS +#endif + +enum { + POS_END = 0, /* end of this position list */ + POS_COLUMN, /* followed by new column number */ + POS_BASE }; -/* -** CAPI3REF: OS Interface File Virtual Methods 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 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 +/* MERGE_COUNT controls how often we merge segments (see comment at +** top of file). +*/ +#define MERGE_COUNT 16 + +/* utility functions */ + +/* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single +** record to prevent errors of the form: +** +** my_function(SomeType *b){ +** memset(b, '\0', sizeof(b)); // sizeof(b)!=sizeof(*b) +** } +*/ +/* TODO(shess) Obvious candidates for a header file. */ +#define CLEAR(b) memset(b, '\0', sizeof(*(b))) + +#ifndef NDEBUG +# define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b))) #else -# define SQLITE_TEXT 3 -#endif -#define SQLITE3_TEXT 3 - -/* -** CAPI3REF: Results Values From A Query -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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 <tokenizer-name> 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.c ***********************/ -#ifndef SQLITE_CORE - #include "sqlite3ext.h" - SQLITE_EXTENSION_INIT1 -#endif - - -/* TODO(shess) MAN, this thing needs some refactoring. At minimum, it -** would be nice to order the file better, perhaps something along the -** lines of: -** -** - utility functions -** - table setup functions -** - table update functions -** - table query functions -** -** Put the query functions last because they're likely to reference -** typedefs or functions from the table update section. -*/ - -#if 0 -# define FTSTRACE(A) printf A; fflush(stdout) -#else -# define FTSTRACE(A) -#endif - -/* -** Default span for NEAR operators. -*/ -#define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10 - -/* It is not safe to call isspace(), tolower(), or isalnum() on -** hi-bit-set characters. This is the same solution used in the -** tokenizer. -*/ -/* TODO(shess) The snippet-generation code should be using the -** tokenizer-generated tokens rather than doing its own local -** tokenization. -*/ -/* TODO(shess) Is __isascii() a portable version of (c&0x80)==0? */ -static int safe_isspace(char c){ - return (c&0x80)==0 ? isspace(c) : 0; -} -static int safe_tolower(char c){ - return (c&0x80)==0 ? tolower(c) : c; -} -static int safe_isalnum(char c){ - return (c&0x80)==0 ? isalnum(c) : 0; -} - -typedef enum DocListType { - DL_DOCIDS, /* docids only */ - DL_POSITIONS, /* docids + positions */ - DL_POSITIONS_OFFSETS /* docids + positions + offsets */ -} DocListType; - -/* -** By default, only positions and not offsets are stored in the doclists. -** To change this so that offsets are stored too, compile with -** -** -DDL_DEFAULT=DL_POSITIONS_OFFSETS -** -** If DL_DEFAULT is set to DL_DOCIDS, your table can only be inserted -** into (no deletes or updates). -*/ -#ifndef DL_DEFAULT -# define DL_DEFAULT DL_POSITIONS -#endif - -enum { - POS_END = 0, /* end of this position list */ - POS_COLUMN, /* followed by new column number */ - POS_BASE -}; - -/* MERGE_COUNT controls how often we merge segments (see comment at -** top of file). -*/ -#define MERGE_COUNT 16 - -/* utility functions */ - -/* CLEAR() and SCRAMBLE() abstract memset() on a pointer to a single -** record to prevent errors of the form: -** -** my_function(SomeType *b){ -** memset(b, '\0', sizeof(b)); // sizeof(b)!=sizeof(*b) -** } -*/ -/* TODO(shess) Obvious candidates for a header file. */ -#define CLEAR(b) memset(b, '\0', sizeof(*(b))) - -#ifndef NDEBUG -# define SCRAMBLE(b) memset(b, 0x55, sizeof(*(b))) -#else # define SCRAMBLE(b) #endif /* We may need up to VARINT_MAX bytes to store an encoded 64-bit integer. */ #define VARINT_MAX 10 @@ -80370,10 +75326,11 @@ ** data currently stored (nData) and buffer capacity (nCapacity). ** ** dataBufferInit - create a buffer with given initial capacity. ** dataBufferReset - forget buffer's data, retaining capacity. ** dataBufferDestroy - free buffer's data. +** dataBufferSwap - swap contents of two buffers. ** dataBufferExpand - expand capacity without adding data. ** dataBufferAppend - append data. ** dataBufferAppend2 - append two pieces of data at once. ** dataBufferReplace - replace buffer's data. */ @@ -80393,10 +75350,15 @@ pBuffer->nData = 0; } static void dataBufferDestroy(DataBuffer *pBuffer){ if( pBuffer->pData!=NULL ) sqlite3_free(pBuffer->pData); SCRAMBLE(pBuffer); +} +static void dataBufferSwap(DataBuffer *pBuffer1, DataBuffer *pBuffer2){ + DataBuffer tmp = *pBuffer1; + *pBuffer1 = *pBuffer2; + *pBuffer2 = tmp; } static void dataBufferExpand(DataBuffer *pBuffer, int nAddCapacity){ assert( nAddCapacity>0 ); /* TODO(shess) Consider expanding more aggressively. Note that the ** underlying malloc implementation may take care of such things for @@ -80609,11 +75571,11 @@ SCRAMBLE(pReader); } #ifndef NDEBUG /* Verify that the doclist can be validly decoded. Also returns the -** last docid found because it's convenient in other assertions for +** last docid found because it is convenient in other assertions for ** DLWriter. */ static void docListValidate(DocListType iType, const char *pData, int nData, sqlite_int64 *pLastDocid){ sqlite_int64 iPrevDocid = 0; @@ -80972,11 +75934,11 @@ } DLCollector; /* TODO(shess) This could also be done by calling plwTerminate() and ** dataBufferAppend(). I tried that, expecting nominal performance ** differences, but it seemed to pretty reliably be worth 1% to code -** it this way. I suspect it's the incremental malloc overhead (some +** it this way. I suspect it is the incremental malloc overhead (some ** percentage of the plwTerminate() calls will cause a realloc), so ** this might be worth revisiting if the DataBuffer implementation ** changes. */ static void dlcAddDoclist(DLCollector *pCollector, DataBuffer *b){ @@ -81647,11 +76609,11 @@ str[n] = '\0'; return str; } /* Duplicate a string; the caller must free() the returned string. - * (We don't use strdup() since it's not part of the standard C library and + * (We don't use strdup() since it is not part of the standard C library and * may not be available everywhere.) */ static char *string_dup(const char *s){ return string_dup_n(s, strlen(s)); } @@ -81730,11 +76692,11 @@ ** If the QueryTerm.nNear variable is non-zero, then the token is followed ** by a NEAR operator with span set to (nNear-1). For example, the ** following query: ** ** The QueryTerm.iPhrase variable stores the index of the token within -** it's phrase, indexed starting at 1, or 1 if the token is not part +** its phrase, indexed starting at 1, or 1 if the token is not part ** of any phrase. ** ** For example, the data structure used to represent the following query: ** ** ... MATCH 'sqlite NEAR/5 google NEAR/2 "search engine"' @@ -85488,50 +80450,147 @@ } leafWriterDestroy(&writer); return rc; } +/* Accumulate the union of *acc and *pData into *acc. */ +static void docListAccumulateUnion(DataBuffer *acc, + const char *pData, int nData) { + DataBuffer tmp = *acc; + dataBufferInit(acc, tmp.nData+nData); + docListUnion(tmp.pData, tmp.nData, pData, nData, acc); + dataBufferDestroy(&tmp); +} + +/* TODO(shess) It might be interesting to explore different merge +** strategies, here. For instance, since this is a sorted merge, we +** could easily merge many doclists in parallel. With some +** comprehension of the storage format, we could merge all of the +** doclists within a leaf node directly from the leaf node's storage. +** It may be worthwhile to merge smaller doclists before larger +** doclists, since they can be traversed more quickly - but the +** results may have less overlap, making them more expensive in a +** different way. +*/ + /* Scan pReader for pTerm/nTerm, and merge the term's doclist over ** *out (any doclists with duplicate docids overwrite those in *out). ** Internal function for loadSegmentLeaf(). */ static int loadSegmentLeavesInt(fulltext_vtab *v, LeavesReader *pReader, const char *pTerm, int nTerm, int isPrefix, DataBuffer *out){ + /* doclist data is accumulated into pBuffers similar to how one does + ** increment in binary arithmetic. If index 0 is empty, the data is + ** stored there. If there is data there, it is merged and the + ** results carried into position 1, with further merge-and-carry + ** until an empty position is found. + */ + DataBuffer *pBuffers = NULL; + int nBuffers = 0, nMaxBuffers = 0, rc; + assert( nTerm>0 ); - /* Process while the prefix matches. */ - while( !leavesReaderAtEnd(pReader) ){ + for(rc=SQLITE_OK; rc==SQLITE_OK && !leavesReaderAtEnd(pReader); + rc=leavesReaderStep(v, pReader)){ /* TODO(shess) Really want leavesReaderTermCmp(), but that name is ** already taken to compare the terms of two LeavesReaders. Think ** on a better name. [Meanwhile, break encapsulation rather than ** use a confusing name.] */ - int rc; int c = leafReaderTermCmp(&pReader->leafReader, pTerm, nTerm, isPrefix); + if( c>0 ) break; /* Past any possible matches. */ if( c==0 ){ const char *pData = leavesReaderData(pReader); - int nData = leavesReaderDataBytes(pReader); - if( out->nData==0 ){ - dataBufferReplace(out, pData, nData); + int iBuffer, nData = leavesReaderDataBytes(pReader); + + /* Find the first empty buffer. */ + for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){ + if( 0==pBuffers[iBuffer].nData ) break; + } + + /* Out of buffers, add an empty one. */ + if( iBuffer==nBuffers ){ + if( nBuffers==nMaxBuffers ){ + DataBuffer *p; + nMaxBuffers += 20; + + /* Manual realloc so we can handle NULL appropriately. */ + p = sqlite3_malloc(nMaxBuffers*sizeof(*pBuffers)); + if( p==NULL ){ + rc = SQLITE_NOMEM; + break; + } + + if( nBuffers>0 ){ + assert(pBuffers!=NULL); + memcpy(p, pBuffers, nBuffers*sizeof(*pBuffers)); + sqlite3_free(pBuffers); + } + pBuffers = p; + } + dataBufferInit(&(pBuffers[nBuffers]), 0); + nBuffers++; + } + + /* At this point, must have an empty at iBuffer. */ + assert(iBuffer<nBuffers && pBuffers[iBuffer].nData==0); + + /* If empty was first buffer, no need for merge logic. */ + if( iBuffer==0 ){ + dataBufferReplace(&(pBuffers[0]), pData, nData); }else{ - DataBuffer result; - dataBufferInit(&result, out->nData+nData); - docListUnion(out->pData, out->nData, pData, nData, &result); - dataBufferDestroy(out); - *out = result; - /* TODO(shess) Rather than destroy out, we could retain it for - ** later reuse. + /* pAcc is the empty buffer the merged data will end up in. */ + DataBuffer *pAcc = &(pBuffers[iBuffer]); + DataBuffer *p = &(pBuffers[0]); + + /* Handle position 0 specially to avoid need to prime pAcc + ** with pData/nData. */ + dataBufferSwap(p, pAcc); + docListAccumulateUnion(pAcc, pData, nData); + + /* Accumulate remaining doclists into pAcc. */ + for(++p; p<pAcc; ++p){ + docListAccumulateUnion(pAcc, p->pData, p->nData); + + /* dataBufferReset() could allow a large doclist to blow up + ** our memory requirements. + */ + if( p->nCapacity<1024 ){ + dataBufferReset(p); + }else{ + dataBufferDestroy(p); + dataBufferInit(p, 0); + } + } + } + } + } + + /* Union all the doclists together into *out. */ + /* TODO(shess) What if *out is big? Sigh. */ + if( rc==SQLITE_OK && nBuffers>0 ){ + int iBuffer; + for(iBuffer=0; iBuffer<nBuffers; ++iBuffer){ + if( pBuffers[iBuffer].nData>0 ){ + if( out->nData==0 ){ + dataBufferSwap(out, &(pBuffers[iBuffer])); + }else{ + docListAccumulateUnion(out, pBuffers[iBuffer].pData, + pBuffers[iBuffer].nData); + } } } - if( c>0 ) break; /* Past any possible matches. */ - - rc = leavesReaderStep(v, pReader); - if( rc!=SQLITE_OK ) return rc; - } - return SQLITE_OK; + } + + while( nBuffers-- ){ + dataBufferDestroy(&(pBuffers[nBuffers])); + } + if( pBuffers!=NULL ) sqlite3_free(pBuffers); + + return rc; } /* Call loadSegmentLeavesInt() with pData/nData as input. */ static int loadSegmentLeaf(fulltext_vtab *v, const char *pData, int nData, const char *pTerm, int nTerm, int isPrefix, @@ -85578,11 +80637,11 @@ ** the last interior-node term). */ /* TODO(shess) The calling code may already know that the end child is ** not worth calculating, because the end may be in a later sibling ** node. Consider whether breaking symmetry is worthwhile. I suspect -** it's not worthwhile. +** it is not worthwhile. */ static void getChildrenContaining(const char *pData, int nData, const char *pTerm, int nTerm, int isPrefix, sqlite_int64 *piStartChild, sqlite_int64 *piEndChild){ @@ -85921,11 +80980,11 @@ } v->iPrevDocid = iDocid; return SQLITE_OK; } -/* This function implements the xUpdate callback; it's the top-level entry +/* This function implements the xUpdate callback; it is the top-level entry * point for inserting, deleting or updating a row in a full-text table. */ static int fulltextUpdate(sqlite3_vtab *pVtab, int nArg, sqlite3_value **ppArg, sqlite_int64 *pRowid){ fulltext_vtab *v = (fulltext_vtab *) pVtab; int rc; @@ -86153,23 +81212,23 @@ ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed ** to by the argument to point a the "simple" tokenizer implementation. ** Function ...PorterTokenizerModule() sets *pModule to point to the ** porter tokenizer/stemmer implementation. */ -void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); -void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule); -void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule); - -int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *); +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); + +SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, fts3Hash *, const char *); /* ** Initialise the fts3 extension. If this extension is built as part ** of the sqlite library, then this function is called directly by ** SQLite. If fts3 is built as a dynamically loadable extension, this ** function is called by the sqlite3_extension_init() entry point. */ -int sqlite3Fts3Init(sqlite3 *db){ +SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){ int rc = SQLITE_OK; fts3Hash *pHash = 0; const sqlite3_tokenizer_module *pSimple = 0; const sqlite3_tokenizer_module *pPorter = 0; const sqlite3_tokenizer_module *pIcu = 0; @@ -86220,11 +81279,11 @@ } return rc; } #if !SQLITE_CORE -int sqlite3_extension_init( +SQLITE_API int sqlite3_extension_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi) @@ -86262,3659 +81321,10 @@ ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ #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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh 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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 -** -** 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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 */ static void *fts3HashMalloc(int n){ @@ -89936,11 +81346,11 @@ ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass ** determines what kind of key the hash table will use. "copyKey" is ** true if the hash table should make its own private copy of keys and ** false if it should just use the supplied pointer. */ -void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){ +SQLITE_PRIVATE void sqlite3Fts3HashInit(fts3Hash *pNew, int keyClass, int copyKey){ assert( pNew!=0 ); assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY ); pNew->keyClass = keyClass; pNew->copyKey = copyKey; pNew->first = 0; @@ -89951,11 +81361,11 @@ /* Remove all entries from a hash table. Reclaim all memory. ** Call this routine to delete a hash table or to reset a hash table ** to the empty state. */ -void sqlite3Fts3HashClear(fts3Hash *pH){ +SQLITE_PRIVATE void sqlite3Fts3HashClear(fts3Hash *pH){ fts3HashElem *elem; /* For looping over all elements of the table */ assert( pH!=0 ); elem = pH->first; pH->first = 0; @@ -90160,11 +81570,11 @@ /* Attempt to locate an element of the hash table pH with a key ** that matches pKey,nKey. Return the data for this element if it is ** found, or NULL if there is no match. */ -void *sqlite3Fts3HashFind(const fts3Hash *pH, const void *pKey, int nKey){ +SQLITE_PRIVATE 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 */ if( pH==0 || pH->ht==0 ) return 0; @@ -90189,11 +81599,11 @@ ** the new data is returned and the hash table is unchanged. ** ** If the "data" parameter to this function is NULL, then the ** element corresponding to "key" is removed from the hash table. */ -void *sqlite3Fts3HashInsert( +SQLITE_PRIVATE void *sqlite3Fts3HashInsert( fts3Hash *pH, /* The hash table to insert into */ const void *pKey, /* The key */ int nKey, /* Number of bytes in the key */ void *data /* The data */ ){ @@ -90283,3693 +81693,10 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -/************** 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh 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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 -** -** 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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 <tokenizer-name> 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 */ typedef struct porter_tokenizer { @@ -94567,11 +82294,11 @@ /* ** Allocate a new porter tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ -void sqlite3Fts3PorterTokenizerModule( +SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &porterTokenizerModule; } @@ -94604,7700 +82331,16 @@ ** * The FTS3 module is being built into the core of ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined). */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -/************** 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: sqlite3ext.h,v 1.17 2007/08/31 16:11:36 drh 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh Exp $ -*/ -#ifndef _SQLITE3_H_ -#define _SQLITE3_H_ - -/* -** Make sure we can call this stuff from C++. -*/ -#if 0 -extern "C" { +#ifndef SQLITE_CORE + SQLITE_EXTENSION_INIT1 #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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 -** -** 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh 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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 -** -** 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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 <tokenizer-name> 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: ** ** SELECT <function-name>(<key-name>); ** SELECT <function-name>(<key-name>, <pointer>); @@ -102358,11 +82401,10 @@ sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT); } #ifdef SQLITE_TEST -#include <tcl.h> /* ** Implementation of a special SQL scalar function for testing tokenizers ** designed to be used in concert with the Tcl testing framework. This ** function must be called with two arguments: @@ -102522,11 +82564,11 @@ } return sqlite3_finalize(pStmt); } -void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule); /* ** Implementation of the scalar function fts3_tokenizer_internal_test(). ** This function is used for testing only, it is not included in the ** build unless SQLITE_TEST is defined. @@ -102591,11 +82633,11 @@ ** provide read/write access to the contents of *pHash. ** ** The third argument to this function, zName, is used as the name ** of both the scalar and, if created, the virtual table. */ -int sqlite3Fts3InitHashTable( +SQLITE_PRIVATE int sqlite3Fts3InitHashTable( sqlite3 *db, fts3Hash *pHash, const char *zName ){ int rc = SQLITE_OK; @@ -102658,3693 +82700,10 @@ */ #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) -/************** 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh 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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 -** -** 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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 <tokenizer-name> 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; char delim[128]; /* flag ASCII delimiters */ } simple_tokenizer; @@ -106530,3955 +82889,14 @@ /* ** Allocate a new simple tokenizer. Return a pointer to the new ** tokenizer in *ppModule */ -void sqlite3Fts3SimpleTokenizerModule( +SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule( sqlite3_tokenizer_module const**ppModule ){ *ppModule = &simpleTokenizerModule; } #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */ /************** End of fts3_tokenizer1.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: fts3_icu.c,v 1.2 2007/10/24 21:52:37 shess 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 -** -** 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: sqlite.h.in,v 1.271 2007/11/21 15:24:01 drh 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 -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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. -** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.2" -#define SQLITE_VERSION_NUMBER 3005002 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The 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 -** -** This routine returns TRUE (nonzero) if SQLite was compiled with -** all of its mutexes enabled and is thus threadsafe. It returns -** zero if the particular build is for single-threaded operation -** only. -** -** 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. -** -** This is an experimental API and may go away or change in future -** releases. -*/ -int sqlite3_threadsafe(void); - -/* -** CAPI3REF: Database Connection Handle -** -** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. -*/ -#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 -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()], [sqlite3_open16()], or -** [sqlite3_open_v2()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. -** -** Passing this routine a database connection that has already been -** closed results in undefined behavior. 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 -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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]. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory using [sqlite3_free()]. -** If errmsg==NULL, then no error message is ever written. -** -** 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. -** -*/ -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 -** KEYWORDS: SQLITE_OK -** -** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** 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 /* NOT USED. 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 -** -** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at 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 users 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We 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. -** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** -** 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 -** -** Combination of the following 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 -** -** The xDeviceCapabilities method of the [sqlite3_io_methods] -** object returns an integer which is a vector of the following -** bit values expressing I/O characteristics of the mass storage -** device that holds the file that the [sqlite3_io_methods] -** refers to. -** -** 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(). -*/ -#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 -** -** 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. -*/ -#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 -** -** When SQLite invokes the xSync() method of an [sqlite3_io_methods] -** object it uses a combination of the following integer values as -** the second argument. -** -** 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 means -** to use normal fsync() semantics. 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 -** -** 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 -** -** 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 -** <ul> -** <li> [SQLITE_LOCK_NONE], -** <li> [SQLITE_LOCK_SHARED], -** <li> [SQLITE_LOCK_RESERVED], -** <li> [SQLITE_LOCK_PENDING], or -** <li> [SQLITE_LOCK_EXCLUSIVE]. -** </ul> -** 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: -** -** <ul> -** <li> [SQLITE_IOCAP_ATOMIC] -** <li> [SQLITE_IOCAP_ATOMIC512] -** <li> [SQLITE_IOCAP_ATOMIC1K] -** <li> [SQLITE_IOCAP_ATOMIC2K] -** <li> [SQLITE_IOCAP_ATOMIC4K] -** <li> [SQLITE_IOCAP_ATOMIC8K] -** <li> [SQLITE_IOCAP_ATOMIC16K] -** <li> [SQLITE_IOCAP_ATOMIC32K] -** <li> [SQLITE_IOCAP_ATOMIC64K] -** <li> [SQLITE_IOCAP_SAFE_APPEND] -** <li> [SQLITE_IOCAP_SEQUENTIAL] -** </ul> -** -** 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 -** -** These integer constants are opcodes for the xFileControl method -** of the [sqlite3_io_methods] object and to the [sqlite3_file_control()] -** interface. -** -** 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 -** is used during testing and only needs to be supported when SQLITE_TEST -** is defined. -*/ -#define SQLITE_FCNTL_LOCKSTATE 1 - -/* -** CAPI3REF: Mutex Handle -** -** 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 -** 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 -** -** 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. -** -** 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. So the [sqlite3_file] can store a pointer to the -** filename if it needs to remember the filename for some reason. -** -** The flags argument to xOpen() is a copy of the flags argument -** to [sqlite3_open_v2()]. If [sqlite3_open()] or [sqlite3_open16()] -** is used, then flags is [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. -** If xOpen() opens a file read-only then it sets *pOutFlags to -** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be -** set. -** -** SQLite will also add one of the following flags to the xOpen() -** call, depending on the object being opened: -** -** <ul> -** <li> [SQLITE_OPEN_MAIN_DB] -** <li> [SQLITE_OPEN_MAIN_JOURNAL] -** <li> [SQLITE_OPEN_TEMP_DB] -** <li> [SQLITE_OPEN_TEMP_JOURNAL] -** <li> [SQLITE_OPEN_TRANSIENT_DB] -** <li> [SQLITE_OPEN_SUBJOURNAL] -** <li> [SQLITE_OPEN_MASTER_JOURNAL] -** </ul> -** -** 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. -** -** SQLite might also add one of the following flags to the xOpen -** method: -** -** <ul> -** <li> [SQLITE_OPEN_DELETEONCLOSE] -** <li> [SQLITE_OPEN_EXCLUSIVE] -** </ul> -** -** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be -** deleted when it is closed. This will always be set for TEMP -** databases and journals and for subjournals. 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. -** -** Space to hold the [sqlite3_file] structure passed as the third -** argument to xOpen is allocated by caller (the SQLite core). -** szOsFile bytes are allocated for this object. The xOpen method -** fills in the allocated space. -** -** 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. The file can be a -** directory. -** -** SQLite will always allocate at least mxPathname+1 byte for -** the output buffers for xGetTempname and xFullPathname. The exact -** size of the output buffer is also passed as a parameter to both -** methods. 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 endevour 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 -** -** These integer constants can be used as the third parameter to -** the xAccess method of an [sqlite3_vfs] object. They determine -** the kind of what kind of permissions the xAccess method is -** looking for. With SQLITE_ACCESS_EXISTS, the xAccess method -** simply checks to see if the file exists. With SQLITE_ACCESS_READWRITE, -** the xAccess method checks to see if the file is both readable -** and writable. 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 -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. 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 -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column 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 given in the first -** argument. 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. -** -** 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, -** and INSERT OR ABORT make no changes to the return value of this -** routine when their insertion fails. 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. -** -** 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 -** -** This function returns the number of database rows that were changed -** (or inserted or deleted) by the most recent SQL statement. 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 -** to find the total number of changes including changes caused by triggers. -** -** 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 trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use -** "DELETE FROM table WHERE 1" instead. -** -** 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 -*** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. 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()]). -** -** 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 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. -** -** 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_total_changes(sqlite3*); - -/* -** CAPI3REF: Interrupt A Long-Running Query -** -** This function causes any pending database operation to abort and -** return at its earliest opportunity. 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 -** is closed or might close before sqlite3_interrupt() returns. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. -*/ -void sqlite3_interrupt(sqlite3*); - -/* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. -** -** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. -*/ -int sqlite3_complete(const char *sql); -int sqlite3_complete16(const void *sql); - -/* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** 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. -** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [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 this routine. The second argument to -** the handler is the number of times that the busy handler has -** been invoked for this locking event. 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 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 return [SQLITE_BUSY] instead. -** 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. -** -** The default busy callback is NULL. -** -** 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 -** 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 -** 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 -** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> -** CorruptionFollowingBusyError</a> wiki page for a discussion of why -** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. -** -** There can only be a single busy handler defined for each database -** connection. Setting a new busy handler clears any previous one. -** Note that calling [sqlite3_busy_timeout()] will also set or clear -** the busy handler. -** -** 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. The busy handler is invoked -** in the thread that was running when the SQLITE_BUSY was hit. -*/ -int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); - -/* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a -** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. 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 -** turns off all busy handlers. -** -** 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <blockquote><pre> -** Name | Age -** ----------------------- -** Alice | 43 -** Bob | 28 -** Cindy | 21 -** </pre></blockquote> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <blockquote><pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre></blockquote> -** -** 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 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. -** -** 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 -** -** These routines are workalikes of the "printf()" family of functions -** from the standard C library. -** -** 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 -** 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 -** 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 -** 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() -** returns a pointer to its buffer instead of the number of -** characters actually written into the buffer. 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 -** parameter "n" is the total size of the buffer, including space for -** the zero terminator. 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. -** -** 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 '\'' -** character it escapes that character and allows it to be inserted into -** the string. -** -** For example, so some string variable contains text as follows: -** -** <blockquote><pre> -** char *zText = "It's a happy day!"; -** </pre></blockquote> -** -** One can use this text in an SQL statement as follows: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** Because the %q format string is used, the '\'' character in zText -** is escaped and the SQL generated is as follows: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It''s a happy day!') -** </pre></blockquote> -** -** This is correct. Had we used %s instead of %q, the generated SQL -** would have looked like this: -** -** <blockquote><pre> -** INSERT INTO table1 VALUES('It's a happy day!'); -** </pre></blockquote> -** -** 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. 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. So, for example, one could say: -** -** <blockquote><pre> -** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); -** sqlite3_exec(db, zSQL, 0, 0, 0); -** sqlite3_free(zSQL); -** </pre></blockquote> -** -** 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 -** addition that after the string has been read and copied into -** the result, [sqlite3_free()] is called on the input string. -*/ -char *sqlite3_mprintf(const char*,...); -char *sqlite3_vmprintf(const char*, va_list); -char *sqlite3_snprintf(int,char*,const char*, ...); - -/* -** CAPI3REF: Memory Allocation Subsystem -** -** The SQLite core uses these three routines for all of its own -** internal memory allocation needs. (See the exception below.) -** -** The default implementation -** of the memory allocation subsystem uses the malloc(), realloc() -** and free() provided by the standard C library. However, if -** SQLite is compiled with the following C preprocessor macro -** -** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> -** -** where <i>NNN</i> is an integer, then SQLite create a static -** array of at least <i>NNN</i> bytes in size and use that array -** for all of its dynamic memory allocation needs. -** -** 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. -** -** <b>Exception:</b> 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 -** -** 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 below. -** -** The first of these two routines returns the amount of memory -** currently outstanding (malloced but not freed). The second -** returns the largest instantaneous amount of outstanding -** memory. The highwater mark is reset if the argument is -** true. -** -** The value returned may or may not include allocation -** overhead, depending on which built-in memory allocator -** implementation is used. -*/ -sqlite3_int64 sqlite3_memory_used(void); -sqlite3_int64 sqlite3_memory_highwater(int resetFlag); - -/* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. -** 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 -** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. -** -** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. -** -** 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. -** -** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. -** -** Note that the authorizer callback is invoked only during -** [sqlite3_prepare()] or its variants. Authorization is not -** performed during statement evaluation in [sqlite3_step()]. -*/ -int sqlite3_set_authorizer( - sqlite3*, - int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), - void *pUserData -); - -/* -** CAPI3REF: Authorizer Return Codes -** -** 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 -** -** The [sqlite3_set_authorizer()] interface registers a callback function -** that is invoked to authorizer certain SQL statement actions. 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. -** -** These action code values signify what kind of operation is to be -** authorized. 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 -** 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 -** -** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. -** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. -** -** 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 -** -** 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 -** interface is to keep a GUI updated during a large query. -** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. 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 -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for [sqlite3_open()] and [sqlite3_open_v2()] and UTF-16 encoded -** in the native byte order for [sqlite3_open16()]. -** An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 -** 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 if [sqlite3_open16()] is used. -** -** 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 -** provides two additional parameters for additional control over the -** new database connection. The flags parameter can be one of: -** -** <ol> -** <li> [SQLITE_OPEN_READONLY] -** <li> [SQLITE_OPEN_READWRITE] -** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] -** </ol> -** -** The first value opens the database read-only. If the database does -** not previously exist, an error is returned. The second option opens -** the database for reading and writing if possible, or reading only if -** if the file is write protected. In either case the database must already -** exist or an error is returned. The third option opens the database -** for reading and writing and creates it if it does not already exist. -** The third options is behavior that is always used for [sqlite3_open()] -** and [sqlite3_open16()]. -** -** If the filename is ":memory:", then an private -** in-memory database is created for the connection. This in-memory -** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary -** on-disk database will be created. 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. -** -** <b>Note to windows users:</b> 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 -** -** 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'. If a prior API call failed but the -** most recent API call succeeded, the return value from sqlite3_errcode() -** is undefined. -** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language -** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. 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. Interfaces that are -** not associated with a specific database connection (examples: -** [sqlite3_mprintf()] or [sqlite3_enable_shared_cache()] do not change -** the return code. -** -** 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 -** -** Instance of this object represent single SQL statements. This -** 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: -** -** <ol> -** <li> Create the object using [sqlite3_prepare_v2()] or a related -** function. -** <li> Bind values to host parameters using -** [sqlite3_bind_blob | sqlite3_bind_* interfaces]. -** <li> Run the SQL by calling [sqlite3_step()] one or more times. -** <li> Reset the statement using [sqlite3_reset()] then go back -** to step 2. Do this zero or more times. -** <li> Destroy the object using [sqlite3_finalize()]. -** </ol> -** -** Refer to documentation on individual methods above for additional -** information. -*/ -typedef struct sqlite3_stmt sqlite3_stmt; - -/* -** CAPI3REF: Compiling An SQL Statement -** -** To execute an SQL query, it must first be compiled into a byte-code -** program using one of these routines. -** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** 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 -** 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. -** -** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *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. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. -** -** 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 -** behave a differently in two ways: -** -** <ol> -** <li> -** 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 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. -** </li> -** -** <li> -** When an error occurs, -** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. -** 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. -** </li> -** </ol> -*/ -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 */ -); - -/* -** Retrieve the original SQL statement associated with a compiled statement -** in UTF-8 encoding. -** -** 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 nul-terminated string containing a copy of -** the original SQL statement. The pointer is valid until the statement -** is deleted using sqlite3_finalize(). -** -** If the statement was compiled using either of the legacy interfaces -** sqlite3_prepare() or sqlite3_prepare16(), this function returns NULL. -** -****** EXPERIMENTAL - subject to change without notice ************** -*/ -const char *sqlite3_sql(sqlite3_stmt *pStmt); - -/* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. -*/ -typedef struct Mem sqlite3_value; - -/* -** CAPI3REF: SQL Function Context Object -** -** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. -*/ -typedef struct sqlite3_context sqlite3_context; - -/* -** CAPI3REF: Binding Values To Prepared Statements -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: -** -** <ul> -** <li> ? -** <li> ?NNN -** <li> :AAA -** <li> @AAA -** <li> $VVV -** </ul> -** -** 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. -** 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 always is a pointer -** to the [sqlite3_stmt] object returned from [sqlite3_prepare_v2()] or -** its variants. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. -** The NNN value must be between 1 and the compile-time -** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. -** -** The third argument is the value to bind to the parameter. -** -** 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. The number -** of bytes does not include the zero-terminator at the end of strings. -** If the fourth parameter is negative, the length of the string is -** number of bytes up to the first zero terminator. -** -** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that -** is filled with zeros. A zeroblob uses a fixed amount of memory -** (just an integer to hold it size) while it is being processed. -** Zeroblobs are intended to serve as place-holders for BLOBs whose -** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. A negative -** value for the zeroblob results in a zero-length BLOB. -** -** The sqlite3_bind_*() routines must be called after -** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and -** before [sqlite3_step()]. -** Bindings are not cleared by the [sqlite3_reset()] routine. -** Unbound parameters are interpreted as NULL. -** -** 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] 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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. -** -** The prepared statement must not be [sqlite3_finalize | finalized] -** prior to this routine returnning. Otherwise the results are undefined -** and probably undesirable. -*/ -int sqlite3_bind_parameter_count(sqlite3_stmt*); - -/* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** 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. -** Parameters of the form "?" or "?NNN" have no name. -** -** The first bound 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 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 -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. -*/ -int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); - -/* -** CAPI3REF: Reset All Bindings On A Prepared Statement -** -** Contrary to the intuition of many, [sqlite3_reset()] does not -** reset the [sqlite3_bind_blob | bindings] on a -** [sqlite3_stmt | prepared statement]. Use this routine to -** reset all host parameters to NULL. -*/ -int sqlite3_clear_bindings(sqlite3_stmt*); - -/* -** CAPI3REF: Number Of Columns In A Result Set -** -** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. 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 -** -** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. 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 -** [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 -** (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 -** -** 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 UTF8 or UTF16 string. 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 [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 -** database, table, and column. -** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. -** 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. 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 UTF-16 -** encoded strings, the other functions return UTF-8. -** -** These APIs are only available if the library was compiled with the -** SQLITE_ENABLE_COLUMN_METADATA preprocessor symbol defined. -** -** 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL 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 -** expression or subquery) then the declared type of the table -** column is returned. 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. 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 -** -** 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. -** -** <b>Goofy Interface Alert:</b> -** 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: -** -** Return the number of values in the current row of the result set. -** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 -** -** Every value in SQLite has one of five fundamental datatypes: -** -** <ul> -** <li> 64-bit signed integer -** <li> 64-bit IEEE floating point number -** <li> string -** <li> BLOB -** <li> NULL -** </ul> -** -** 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 -** -** 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: -** -** <blockquote> -** <table border="1"> -** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion -** -** <tr><td> NULL <td> INTEGER <td> Result is 0 -** <tr><td> NULL <td> FLOAT <td> Result is 0.0 -** <tr><td> NULL <td> TEXT <td> Result is NULL pointer -** <tr><td> NULL <td> BLOB <td> Result is NULL pointer -** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float -** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer -** <tr><td> INTEGER <td> BLOB <td> Same as for INTEGER->TEXT -** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer -** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float -** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT -** <tr><td> TEXT <td> INTEGER <td> Use atoi() -** <tr><td> TEXT <td> FLOAT <td> Use atof() -** <tr><td> TEXT <td> BLOB <td> No change -** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi() -** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof() -** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed -** </table> -** </blockquote> -** -** 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: -** -** <ul> -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** -** <li><p> 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.</p></li> -** </ul> -** -** 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: -** -** <ul> -** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li> -** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li> -** </ul> -** -** 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 <b>not</b> 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 -** -** 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 -** -** The sqlite3_reset() function is called to reset a -** [sqlite3_stmt | compiled SQL statement] object. -** back to it's 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 -** -** 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 -** -** 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 -** -** 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 order -** words if the value is original a string that looks like a number) -** then it 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 -** -** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation -** of the aggregate can use the returned buffer to accumulate data. -** -** The buffer allocated is freed automatically by SQLite whan 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. -** -** 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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. -** -** This routine must be called from the same thread in which -** the SQL function is running. -*/ -void *sqlite3_user_data(sqlite3_context*); - -/* -** CAPI3REF: Function Auxiliary Data -** -** 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. -** -** The sqlite3_get_auxdata() interface returns a pointer to the meta-data -** associated with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. -** -** 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); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior -** -** 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 -** -** 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. -** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. -** -** These routines must be called from within the same thread as -** the SQL function associated with the [sqlite3_context] pointer. -*/ -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 -** -** These functions are used to add new collation sequences to the -** [sqlite3*] handle specified as the first argument. -** -** 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 -** the name is passed as the second function argument. -** -** 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 -** 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. -** -** 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 -** sequence (so that SQLite cannot call it anymore). Each time the user -** 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. -** -** The remaining arguments to the user-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. The user 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). -** -** The sqlite3_create_collation_v2() works like sqlite3_create_collation() -** excapt that it takes an extra argument which is a destructor for -** the collation. 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 [sqlite3*] database handle is closed using [sqlite3_close()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. -*/ -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 -** -** 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. -** -** 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. 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. -** -** 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 -** handle. 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. -** -** 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 -** -** This function causes the current thread to suspend execution -** 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 -** requested from the operating system is returned. -** -** SQLite implements this interface by calling the xSleep() -** method of the default [sqlite3_vfs] object. -*/ -int sqlite3_sleep(int); - -/* -** CAPI3REF: Name Of The Folder Holding Temporary Files -** -** 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 -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. -** -** 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. The only way to -** find out if SQLite automatically rolled back the transaction after -** an error is to use this function. -** -** If another thread changes the autocommit status of the database -** connection while this routine is running, then the return value -** is undefined. -*/ -int sqlite3_get_autocommit(sqlite3*); - -/* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This 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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. 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. -** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** 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 -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. -** -** 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 -** -** Register 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. -** -** 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. -** -** 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. -*/ -void *sqlite3_update_hook( - sqlite3*, - void(*)(void *,int ,char const *,char const *,sqlite3_int64), - void* -); - -/* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** -** This routine enables or disables the sharing of the database cache -** and schema data structures between connections to the same database. -** Sharing is enabled if the argument is true and disabled if the argument -** is false. -** -** Beginning in SQLite version 3.5.0, cache sharing is enabled and disabled -** for an entire process. In prior versions of SQLite, sharing was -** enabled or disabled for each thread separately. -** -** 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. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the [sqlite3_create_module()] API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default. 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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -*/ -int sqlite3_release_memory(int); - -/* -** CAPI3REF: Impose A Limit On Heap Size -** -** Place 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 specified limit, [sqlite3_release_memory()] is -** invoked one or more times to free up some space before the allocation -** is made. -** -** 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. -** -** 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. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. 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 -** 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 -** -** 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. -** -** <pre> -** 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 -** </pre> -** -** -** 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: -** -** <pre> -** data type: "INTEGER" -** collation sequence: "BINARY" -** not null: 0 -** primary key: 1 -** auto increment: 0 -** </pre> -** -** 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 -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory -** by calling [sqlite3_free()]. -** -** 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 -** -** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. -*/ -int sqlite3_enable_load_extension(sqlite3 *db, int onoff); - -/* -** CAPI3REF: Make Arrangements To Automatically Load An Extension -** -** Register an extension entry point that is automatically invoked -** whenever a new database connection is opened using -** [sqlite3_open()], [sqlite3_open16()], or [sqlite3_open_v2()]. -** -** 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. -** -** Duplicate extensions are detected so calling this routine multiple -** times with the same extension is harmless. -** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). 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. -** -** Automatic extensions apply across all threads. -** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] -** calls. -** -** This call disabled automatic extensions in all threads. -** -** 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 -** -** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: -** -** <pre> -** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** 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. -** -** On success, [SQLITE_OK] is returned and the new -** [sqlite3_blob | 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-handle error code and message -** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. -*/ -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 -** -** Close an open [sqlite3_blob | blob handle]. -*/ -int sqlite3_blob_close(sqlite3_blob *); - -/* -** CAPI3REF: Return The Size Of An Open BLOB -** -** 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 -** -** This function is used to read data from an open -** [sqlite3_blob | blob-handle] into a caller supplied buffer. -** n bytes of data are copied into buffer -** z from the open blob, starting at offset iOffset. -** -** 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 -** -** This function is used to write data into an open -** [sqlite3_blob | blob-handle] from a user supplied buffer. -** n bytes of data are copied from the buffer -** pointed to by z into the open blob, starting at offset iOffset. -** -** 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. -** -** 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 -** -** 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. -** -** The sqlite3_vfs_find() interface returns a pointer to a VFS given its -** name. Names are case sensitive. If there is no match, a NULL -** pointer is returned. If zVfsName is NULL then the default -** VFS is returned. -** -** 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 -** 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 -** 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 -** -** 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: -** -** <ul> -** <li> SQLITE_MUTEX_OS2 -** <li> SQLITE_MUTEX_PTHREAD -** <li> SQLITE_MUTEX_W32 -** <li> SQLITE_MUTEX_NOOP -** </ul> -** -** 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. -** -** The sqlite3_mutex_alloc() routine allocates a new -** mutex and returns a pointer to it. If it returns NULL -** that means that a mutex could not be allocated. SQLite -** will unwind its stack and return an error. The argument -** to sqlite3_mutex_alloc() is one of these integer constants: -** -** <ul> -** <li> SQLITE_MUTEX_FAST -** <li> SQLITE_MUTEX_RECURSIVE -** <li> SQLITE_MUTEX_STATIC_MASTER -** <li> SQLITE_MUTEX_STATIC_MEM -** <li> SQLITE_MUTEX_STATIC_MEM2 -** <li> SQLITE_MUTEX_STATIC_PRNG -** <li> SQLITE_MUTEX_STATIC_LRU -** </ul> -** -** 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. -** The mutex implementation does not need to make a distinction -** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does -** not want to. But SQLite will only request a recursive mutex in -** cases where it really needs one. 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. -** -** The other allowed parameters to sqlite3_mutex_alloc() each return -** a pointer to a static preexisting mutex. 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. -** -** 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. But for the static -** mutex types, the same mutex is returned on every call that has -** the same type number. -** -** The sqlite3_mutex_free() routine deallocates a previously -** allocated dynamic mutex. SQLite is careful to deallocate every -** dynamic mutex that it allocates. The dynamic mutexes must not be in -** use when they are deallocated. Attempting to deallocate a static -** mutex results in undefined behavior. SQLite never deallocates -** a static mutex. -** -** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt -** to enter a mutex. If another thread is already within the mutex, -** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return -** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK -** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can -** be entered multiple times by the same thread. In such cases the, -** mutex must be exited an equal number of times before another thread -** can enter. If the same thread tries to enter any other kind of mutex -** more than once, the behavior is undefined. SQLite will never exhibit -** such behavior in its own use of mutexes. -** -** Some systems (ex: windows95) do not the operation implemented by -** sqlite3_mutex_try(). On those systems, sqlite3_mutex_try() will -** always return SQLITE_BUSY. The SQLite core only ever uses -** sqlite3_mutex_try() as an optimization so this is acceptable behavior. -** -** The sqlite3_mutex_leave() routine exits a mutex that was -** previously entered by the same thread. The behavior -** is undefined if the mutex is not currently entered by the -** calling thread or is not currently allocated. SQLite will -** never do either. -** -** 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 -** -** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines -** are intended for use inside assert() statements. The SQLite core -** never uses these routines except inside an assert() and applications -** are advised to follow the lead of the core. The core only -** provides implementations for these routines when it is compiled -** with the SQLITE_DEBUG flag. External mutex implementations -** are only required to provide these routines if SQLITE_DEBUG is -** defined and if NDEBUG is not defined. -** -** These routines should return true if the mutex in their argument -** is held or not held, respectively, by the calling thread. -** -** 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. -** -** If the argument to sqlite3_mutex_held() is a NULL pointer then -** the routine should return 1. 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. 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 -** -** The [sqlite3_mutex_alloc()] interface takes a single argument -** which is one of these integer constants. -*/ -#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 -** -** 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. The -** name of the database is the name assigned to the database by the -** <a href="lang_attach.html">ATTACH</a> SQL command that opened the -** database. To control the main database file, use the name "main" -** or a NULL pointer. The third and fourth parameters to this routine -** are passed directly through to the second and third parameters of -** the xFileControl method. The return value of the xFileControl -** method becomes the return value of this routine. -** -** If the second parameter (zDbName) does not match the name of any -** open database file, then SQLITE_ERROR is returned. This error -** code is not remembered and will not be recalled by [sqlite3_errcode()] -** or [sqlite3_errmsg()]. The underlying xFileControl method might -** also return SQLITE_ERROR. There is no way to distinguish between -** an incorrect zDbName and an SQLITE_ERROR return from the underlying -** xFileControl method. -** -** 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 <tokenizer-name> 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 <unicode/ubrk.h> -#include <unicode/ucol.h> -#include <unicode/ustring.h> -#include <unicode/utf16.h> - -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 */ -){ - IcuTokenizer *p; - int n = 0; - - if( argc>0 ){ - n = strlen(argv[0])+1; - } - p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n); - if( !p ){ - return SQLITE_NOMEM; - } - memset(p, 0, sizeof(IcuTokenizer)); - - if( n ){ - p->zLocale = (char *)&p[1]; - memcpy(p->zLocale, argv[0], n); - } - - *ppTokenizer = (sqlite3_tokenizer *)p; - - return SQLITE_OK; -} - -/* -** Destroy a tokenizer -*/ -static int icuDestroy(sqlite3_tokenizer *pTokenizer){ - IcuTokenizer *p = (IcuTokenizer *)pTokenizer; - sqlite3_free(p); - return SQLITE_OK; -} - -/* -** Prepare to begin tokenizing a particular string. The input -** string to be tokenized is pInput[0..nBytes-1]. A cursor -** used to incrementally tokenize this string is returned in -** *ppCursor. -*/ -static int icuOpen( - sqlite3_tokenizer *pTokenizer, /* The tokenizer */ - const char *zInput, /* Input string */ - int nInput, /* Length of zInput in bytes */ - sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ -){ - IcuTokenizer *p = (IcuTokenizer *)pTokenizer; - IcuCursor *pCsr; - - const int32_t opt = U_FOLD_CASE_DEFAULT; - UErrorCode status = U_ZERO_ERROR; - int nChar; - - UChar32 c; - int iInput = 0; - int iOut = 0; - - *ppCursor = 0; - - if( -1 == nInput ) nInput = strlen(nInput); - nChar = nInput+1; - pCsr = (IcuCursor *)sqlite3_malloc( - sizeof(IcuCursor) + /* IcuCursor */ - nChar * sizeof(UChar) + /* IcuCursor.aChar[] */ - (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */ - ); - if( !pCsr ){ - return SQLITE_NOMEM; - } - memset(pCsr, 0, sizeof(IcuCursor)); - pCsr->aChar = (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( iInput<nInput ){ - U8_NEXT(zInput, iInput, nInput, c); - }else{ - c = 0; - } - } - - pCsr->pIter = 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; -} - -/* -** 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; -} - -/* -** 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( iStart<iEnd ){ - int iWhite = iStart; - U8_NEXT(pCsr->aChar, 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 ********************************************/
Modified src/sqlite3.h from [535f235f65] to [180fe7f3de].
@@ -28,11 +28,11 @@ ** 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: sqlite.h.in,v 1.218 2007/07/19 12:41:40 drh Exp $ +** @(#) $Id: sqlite.h.in,v 1.283 2008/01/31 17:21:22 drh Exp $ */ #ifndef _SQLITE3_H_ #define _SQLITE3_H_ #include <stdarg.h> /* Needed for the definition of va_list */ @@ -39,10 +39,18 @@ /* ** Make sure we can call this stuff from C++. */ #ifdef __cplusplus 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. @@ -53,81 +61,134 @@ #ifdef SQLITE_VERSION_NUMBER # undef SQLITE_VERSION_NUMBER #endif /* -** CAPI3REF: Compile-Time Library Version Numbers -** -** The version of the SQLite library is contained in the sqlite3.h -** header file in a #define named SQLITE_VERSION. The SQLITE_VERSION -** macro resolves to a string constant. -** -** The format of the version string is "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". -** 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 +** 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. +** +** The "version" of SQLite is a strong 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 ** there are major feature enhancements that are forwards compatible -** but not backwards compatible. The Z value is incremented with +** but not backwards compatible. The Z value is release number +** and is incremented with ** each release but resets back to 0 when Y is incremented. ** -** The SQLITE_VERSION_NUMBER is an integer with the value -** (X*1000000 + Y*1000 + Z). 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.4.1" -#define SQLITE_VERSION_NUMBER 3004001 - -/* -** CAPI3REF: Run-Time Library Version Numbers -** -** These routines return values equivalent to the header constants -** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER]. The values returned -** by this routines should only be different from the header values -** if you compile your program using an sqlite3.h header from a -** different version of SQLite that the version of the library you -** link against. -** -** The sqlite3_version[] string constant contains the text of the -** [SQLITE_VERSION] string. The sqlite3_libversion() function returns -** a poiner to the sqlite3_version[] string constant. The function -** is provided for DLL users who can only access functions and not +** +** INVARIANTS: +** +** {F10011} The SQLITE_VERSION #define in the sqlite3.h header file +** evaluates to a string literal that is the SQLite version +** with which the header file is associated. +** +** {F10014} The SQLITE_VERSION_NUMBER #define resolves 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.5.5" +#define SQLITE_VERSION_NUMBER 3005005 + +/* +** 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 +** [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 ** constants within the DLL. -*/ -extern const char sqlite3_version[]; +** +** INVARIANTS: +** +** {F10021} The [sqlite3_libversion_number()] interface returns an integer +** equal to [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. +*/ +SQLITE_EXTERN const char sqlite3_version[]; const char *sqlite3_libversion(void); int sqlite3_libversion_number(void); /* -** CAPI3REF: Database Connection Handle +** 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 os false, +** the mutexes are omitted. Without the mutexes, it is not safe +** to use SQLite from more than one thread. +** +** There is a measurable performance penalty for enabling mutexes. +** 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. +** +** INVARIANTS: +** +** {F10101} The [sqlite3_threadsafe()] function returns nonzero if +** SQLite was compiled with its mutexes enabled or zero +** if SQLite was compiled with mutexes disabled. +*/ +int sqlite3_threadsafe(void); + +/* +** CAPI3REF: Database Connection Handle {F12000} +** KEYWORDS: {database connection} ** ** 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] interface is its constructor -** 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 +** 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 -** -** Some compilers do not support the "long long" datatype. So we have -** to do compiler-specific typedefs for 64-bit signed and unsigned integers. -** -** Many SQLite interface functions require a 64-bit integer arguments. -** Those interfaces are declared using this typedef. +** CAPI3REF: 64-Bit Integer Types {F10200} +** KEYWORDS: sqlite_int64 sqlite_uint64 +** +** Because there is no cross-platform way to specify 64-bit integer types +** SQLite includes typedefs for 64-bit signed and unsigned integers. +** +** 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] types specify a +** 64-bit signed integer. +** +** {F10202} The [sqlite_uint64] and [sqlite3_uint64] types specify +** a 64-bit unsigned integer. */ #ifdef SQLITE_INT64_TYPE typedef SQLITE_INT64_TYPE sqlite_int64; typedef unsigned SQLITE_INT64_TYPE sqlite_uint64; #elif defined(_MSC_VER) || defined(__BORLANDC__) @@ -135,30 +196,59 @@ 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 sqlite_int64 +# define double sqlite3_int64 #endif /* -** CAPI3REF: Closing A Database Connection -** -** Call this function with a pointer to a structure that was previously -** returned from [sqlite3_open()] and the corresponding database will by -** closed. -** -** All SQL statements prepared using [sqlite3_prepare_v2()] or -** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()] -** before this routine is called. Otherwise, SQLITE_BUSY is returned and the -** database connection remains open. +** CAPI3REF: Closing A Database Connection {F12010} +** +** This routine is the destructor for the [sqlite3] object. +** +** Applications should [sqlite3_finalize | finalize] all +** [prepared statements] and +** [sqlite3_blob_close | close] all [sqlite3_blob | BLOBs] +** associated with the [sqlite3] object prior +** to attempting to close the [sqlite3] object. +** +** <todo>What happens to pending transactions? Are they +** rolled back, or abandoned?</todo> +** +** INVARIANTS: +** +** {F12011} The [sqlite3_close()] interface destroys an [sqlite3] object +** allocated by a prior call to [sqlite3_open()], +** [sqlite3_open16()], or [sqlite3_open_v2()]. +** +** {F12012} The [sqlite3_close()] function releases all memory used by the +** connection and closes all open files. +** +** {F12013} If the database connection contains +** [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. +** +** LIMITATIONS: +** +** {U12015} The parameter to [sqlite3_close()] must be an [sqlite3] object +** pointer previously obtained from [sqlite3_open()] or the +** equivalent, or NULL. +** +** {U12016} The parameter to [sqlite3_close()] must not have been previously +** closed. */ int sqlite3_close(sqlite3 *); /* ** The type for a callback function. @@ -166,52 +256,102 @@ ** compatibility and is not documented. */ typedef int (*sqlite3_callback)(void*,int,char**, char**); /* -** CAPI3REF: One-Step Query Execution Interface -** -** This interface is used to do a one-time evaluatation of zero -** or more SQL statements. UTF-8 text of the SQL statements to -** be evaluted is passed in as the second parameter. The statements -** are prepared one by one using [sqlite3_prepare()], evaluated -** using [sqlite3_step()], then destroyed using [sqlite3_finalize()]. -** -** If one or more of the SQL statements are queries, then -** the callback function specified by the 3rd parameter is -** invoked once for each row of the query result. This callback -** should normally return 0. 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. -** -** The 4th parameter to this interface is an arbitrary pointer that is -** passed through to the callback function as its first parameter. -** -** The 2nd parameter to the callback function is the number of -** columns in the query result. The 3rd parameter to the callback -** is an array of strings holding the values for each column -** as extracted using [sqlite3_column_text()]. -** The 4th parameter to the callback is an array of strings -** obtained using [sqlite3_column_name()] and holding -** the names of each column. -** -** 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. -** -** If an error occurs while parsing or evaluating the SQL (but -** not while executing the callback) then an appropriate error -** message is written into memory obtained from [sqlite3_malloc()] and -** *errmsg is made to point to that message. The calling function -** is responsible for freeing the memory that holds the error -** message. Use [sqlite3_free()] for this. If errmsg==NULL, -** then no error message is ever written. -** -** 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. -** +** CAPI3REF: One-Step Query Execution Interface {F12100} +** +** The sqlite3_exec() interface is a convenient way of running +** one or more SQL statements without a lot of C code. The +** 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. +** +** The sqlite3_exec() interface is implemented in terms of +** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. +** The sqlite3_exec() routine does nothing that cannot be done +** by [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()]. +** The sqlite3_exec() is just a convenient wrapper. +** +** INVARIANTS: +** +** {F12101} The [sqlite3_exec()] interface evaluates zero or more UTF-8 +** encoded, semicolon-separated, SQL statements in the +** zero-terminated string of its 2nd parameter within the +** context of the [sqlite3] object given in the 1st parameter. +** +** {F12104} The return value of [sqlite3_exec()] is SQLITE_OK if all +** SQL statements run successfully. +** +** {F12105} The return value of [sqlite3_exec()] is 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 is +** invoked once for each row of result. +** +** {F12110} If the callback returns a non-zero value then [sqlite3_exec()] +** will aborted the SQL statement it is currently evaluating, +** skip all subsequent SQL statements, and return [SQLITE_ABORT]. +** <todo>What happens to *errmsg here? Does the result code for +** sqlite3_errcode() get set?</todo> +** +** {F12113} The [sqlite3_exec()] routine will pass its 4th parameter through +** as the 1st parameter of the callback. +** +** {F12116} The [sqlite3_exec()] routine sets the 2nd parameter of its +** callback to be the number of columns in the current row of +** result. +** +** {F12119} The [sqlite3_exec()] routine sets 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 sets 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()] never invokes a callback. All query +** results are silently discarded. +** +** {F12128} If an error occurs while parsing or evaluating any of the SQL +** statements handed to [sqlite3_exec()] then [sqlite3_exec()] will +** return an [error code] other than [SQLITE_OK]. +** +** {F12131} If an error occurs while parsing or evaluating any of the SQL +** handed to [sqlite3_exec()] and if the 5th parameter (errmsg) +** to [sqlite3_exec()] is not NULL, then an error message is +** allocated using the equivalent of [sqlite3_mprintf()] and +** *errmsg is made to point to that message. +** +** {F12134} The [sqlite3_exec()] routine does not change the value of +** *errmsg if errmsg is NULL or if there are no errors. +** +** {F12137} The [sqlite3_exec()] function sets the error code and message +** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** +** LIMITATIONS: +** +** {U12141} The first parameter to [sqlite3_exec()] must be an valid and open +** [database connection]. +** +** {U12142} The database connection must not be closed while +** [sqlite3_exec()] is running. +** +** {U12143} The calling function is should use [sqlite3_free()] to free +** the memory that *errmsg is left pointing at once the error +** message is no longer needed. +** +** {U12145} The SQL statement text in the 2nd parameter to [sqlite3_exec()] +** must remain unchanged while [sqlite3_exec()] is running. */ int sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluted */ int (*callback)(void*,int,char**,char**), /* Callback function */ @@ -218,28 +358,22 @@ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); /* -** CAPI3REF: Result Codes -** KEYWORDS: SQLITE_OK +** CAPI3REF: Result Codes {F10210} +** KEYWORDS: SQLITE_OK {error code} {error codes} ** ** Many SQLite functions return an integer result code from the set shown -** above in order to indicates success or failure. -** -** The result codes above are the only ones returned by SQLite in its -** default configuration. However, the [sqlite3_extended_result_codes()] -** API can be used to set a database connectoin to return more detailed -** result codes. -** -** See also: [SQLITE_IOERR_READ | extended result codes] -** +** here in order to indicates success or failure. +** +** 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 /* NOT USED. Internal logic error in SQLite */ +#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 */ @@ -252,11 +386,11 @@ #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 contraint violation */ +#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 */ @@ -265,35 +399,44 @@ #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 +** CAPI3REF: Extended Result Codes {F10220} +** KEYWORDS: {extended error code} {extended error codes} +** KEYWORDS: {extended result codes} ** ** In its default configuration, SQLite API routines return one of 26 integer -** result codes described at result-codes. However, experience has shown that +** [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 users might like. In an effort to +** 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) for -** each database -** connection using the [sqlite3_extended_result_codes()] API. -** -** Some of the available extended result codes are listed above. -** We expect the number of extended result codes will be expand +** about errors. The extended result codes are enabled or disabled +** for each database connection 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. ** -** The symbolic name for an extended result code always contains a related -** primary result code as a prefix. Primary result codes contain a single -** "_" character. Extended result codes contain two or more "_" characters. -** The numeric value of an extended result code can be converted to its -** corresponding primary result code by masking off the lower 8 bytes. -** ** 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 always contains +** a related primary result code as a prefix. +** +** {F10224} Primary result code names contain a single "_" character. +** +** {F10225} Extended result code names contain two or more "_" characters. +** +** {F10226} The numeric value of an extended result code contains the +** numeric value of its corresponding primary result code it +** 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)) @@ -302,169 +445,676 @@ #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)) - -/* -** CAPI3REF: Enable Or Disable Extended Result Codes -** -** This routine enables or disables the -** [SQLITE_IOERR_READ | extended result codes] feature. -** By default, SQLite API routines return one of only 26 integer -** [SQLITE_OK | result codes]. 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. -** -** The second argument is a boolean value that turns extended result -** codes on and off. Extended result codes are off by default for -** backwards compatibility with older versions of SQLite. +#define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) + +/* +** CAPI3REF: Flags For File Open Operations {F10230} +** +** These bit values are intended for use in then +** 3rd parameter to the [sqlite3_open_v2()] interface and +** in the 4th parameter 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} +** +** 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. +** +** 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(). +*/ +#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} +** +** SQLite uses one of these integer values as the second +** argument to calls it makes to the xLock() and xUnlock() methods +** of an [sqlite3_io_methods] object. +*/ +#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} +** +** 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 +** sync operation only needs to flush data to mass storage. Inode +** information need not be flushed. The SQLITE_SYNC_NORMAL means +** to use normal fsync() semantics. 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 +** <ul> +** <li> [SQLITE_LOCK_NONE], +** <li> [SQLITE_LOCK_SHARED], +** <li> [SQLITE_LOCK_RESERVED], +** <li> [SQLITE_LOCK_PENDING], or +** <li> [SQLITE_LOCK_EXCLUSIVE]. +** </ul> +** 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: +** +** <ul> +** <li> [SQLITE_IOCAP_ATOMIC] +** <li> [SQLITE_IOCAP_ATOMIC512] +** <li> [SQLITE_IOCAP_ATOMIC1K] +** <li> [SQLITE_IOCAP_ATOMIC2K] +** <li> [SQLITE_IOCAP_ATOMIC4K] +** <li> [SQLITE_IOCAP_ATOMIC8K] +** <li> [SQLITE_IOCAP_ATOMIC16K] +** <li> [SQLITE_IOCAP_ATOMIC32K] +** <li> [SQLITE_IOCAP_ATOMIC64K] +** <li> [SQLITE_IOCAP_SAFE_APPEND] +** <li> [SQLITE_IOCAP_SEQUENTIAL] +** </ul> +** +** 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. +** +** 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 +** 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. The SQLite core never looks +** at the internal representation of an [sqlite3_mutex]. 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: +** +** <ul> +** <li> [SQLITE_OPEN_MAIN_DB] +** <li> [SQLITE_OPEN_MAIN_JOURNAL] +** <li> [SQLITE_OPEN_TEMP_DB] +** <li> [SQLITE_OPEN_TEMP_JOURNAL] +** <li> [SQLITE_OPEN_TRANSIENT_DB] +** <li> [SQLITE_OPEN_SUBJOURNAL] +** <li> [SQLITE_OPEN_MASTER_JOURNAL] +** </ul> {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. +** +** SQLite might also add one of the following flags to the xOpen +** method: +** +** <ul> +** <li> [SQLITE_OPEN_DELETEONCLOSE] +** <li> [SQLITE_OPEN_EXCLUSIVE] +** </ul> +** +** {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} +** +** The sqlite3_extended_result_codes() routine enables or disables the +** [SQLITE_IOERR_READ | extended result codes] feature of SQLite. +** The extended result codes are disabled by default for historical +** compatibility. +** +** INVARIANTS: +** +** {F12201} Each new [database connection] has the +** [extended result codes] feature +** disabled by default. +** +** {F12202} The [sqlite3_extended_result_codes(D,F)] interface will enable +** [extended result codes] for the +** [database connection] D if the F parameter +** is true, or disable them if F is false. */ int sqlite3_extended_result_codes(sqlite3*, int onoff); /* -** CAPI3REF: Last Insert Rowid -** -** Each entry in an SQLite table has a unique 64-bit signed integer key -** called the "rowid". The rowid is always available as an undeclared -** column named ROWID, OID, or _ROWID_. If the table has a column of -** type INTEGER PRIMARY KEY then that column is another an alias for the -** rowid. -** -** This routine returns the rowid of the most recent INSERT into -** the database from the database connection given in the first -** argument. If no inserts have ever occurred on this database -** connection, zero is returned. +** 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 +** as an undeclared column named ROWID, OID, or _ROWID_ as long as those +** names are not also used by explicitly declared columns. If +** the table has a column of type INTEGER PRIMARY KEY then that column +** 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 +** shown in the first argument. 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. -*/ -sqlite_int64 sqlite3_last_insert_rowid(sqlite3*); - -/* -** CAPI3REF: Count The Number Of Rows Modified +** +** 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, +** and INSERT OR ABORT make no changes to the return value of this +** routine when their insertion fails. 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. +** +** 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 done +** on the same database connection and within the same +** trigger context, or zero if there have +** been no qualifying inserts on that connection. +** +** {F12223} The [sqlite3_last_insert_rowid()] function returns +** same value when called from the same trigger context +** immediately before and after a ROLLBACK. +** +** LIMITATIONS: +** +** {U12232} If separate thread does 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. +*/ +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 -** (or inserted or deleted) by the most recent SQL statement. Only +** or inserted or deleted by the most recently completed SQL statement +** on the 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 +** triggers are not counted. Use the [sqlite3_total_changes()] function ** to find the total number of changes including changes caused by triggers. ** -** Within the body of a trigger, the sqlite3_changes() interface can be -** called to find the number of +** A "row changes" 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. +** +** So 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 ** changes in the most recently completed INSERT, UPDATE, or DELETE -** statement within the body of the trigger. -** -** All changes are counted, even if they were later undone by a -** ROLLBACK or ABORT. Except, changes associated with creating and -** dropping tables are not counted. -** -** 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. -** -** 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. To get an accurate count of the number of rows deleted, use +** statement within the body of the same trigger. +** However, the number returned does not include in changes +** caused by subtriggers since they 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. +** To get an accurate count of the number of rows deleted, use ** "DELETE FROM table WHERE 1" instead. +** +** INVARIANTS: +** +** {F12241} The [sqlite3_changes()] function returns the number of +** row changes caused by the most recent INSERT, UPDATE, +** or DELETE statement on the same database connection and +** within the same trigger context, or zero if there have +** not been any qualifying row changes. +** +** LIMITATIONS: +** +** {U12252} If a separate thread makes changes on the same database connection +** while [sqlite3_changes()] is running then the value returned +** is unpredictable and unmeaningful. */ int sqlite3_changes(sqlite3*); /* -** CAPI3REF: Total Number Of Rows Modified +** CAPI3REF: Total Number Of Rows Modified {F12260} *** -** This function returns the number of database rows that have been -** modified by INSERT, UPDATE or DELETE statements since the database handle -** was opened. This includes UPDATE, INSERT and DELETE statements executed -** as part of trigger programs. All changes are counted as soon as the -** statement that makes them is completed (when the statement handle is -** passed to [sqlite3_reset()] or [sqlite_finalise()]). -** -** 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 +** This function returns the number of row changes caused +** by INSERT, UPDATE or DELETE statements since the database handle +** was opened. The count includes all changes from all trigger +** contexts. But 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()]). +** +** 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. +** +** LIMITATIONS: +** +** {U12264} If a separate thread makes changes on the same database connection +** while [sqlite3_total_changes()] is running then the value +** returned is unpredictable and unmeaningful. */ int sqlite3_total_changes(sqlite3*); /* -** CAPI3REF: Interrupt A Long-Running Query +** 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 +** return at its earliest opportunity. 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. -** -** The SQL operation that is interrupted will return [SQLITE_INTERRUPT]. -** If an interrupted operation was an update that is inside an -** explicit transaction, then the entire transaction will be rolled -** back automatically. +** thread that is currently running the database operation. 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. +** 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 +** 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: +** +** {U12279} If the database connection closes while [sqlite3_interrupt()] +** is running then bad things will likely happen. */ void sqlite3_interrupt(sqlite3*); /* -** CAPI3REF: Determine If An SQL Statement Is Complete -** -** These functions return true if the given input string comprises -** one or more complete SQL statements. For the sqlite3_complete() call, -** the parameter must be a nul-terminated UTF-8 string. For -** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string -** is required. +** CAPI3REF: Determine If An SQL Statement Is Complete {F10510} ** ** These routines are useful for command-line input to determine if the -** currently entered text forms one or more complete SQL statements or -** if additional input is needed before sending the statements into -** SQLite for parsing. The algorithm is simple. If the -** last token other than spaces and comments is a semicolon, then return -** true. Actually, the algorithm is a little more complicated than that -** in order to deal with triggers, but the basic idea is the same: the -** statement is not complete unless it ends in a semicolon. +** 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 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. +** +** These routines do not parse the SQL and +** so will not detect syntactically incorrect SQL. +** +** INVARIANTS: +** +** {F10511} The sqlite3_complete() and sqlite3_complete16() functions +** return true (non-zero) 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. +** +** LIMITATIONS: +** +** {U10512} The input to sqlite3_complete() must be a zero-terminated +** UTF-8 string. +** +** {U10513} The input to sqlite3_complete16() must be a zero-terminated +** UTF-16 string in native byte order. */ int sqlite3_complete(const char *sql); int sqlite3_complete16(const void *sql); /* -** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors -** -** This routine identifies a callback function that might be invoked -** whenever an attempt is made to open a database table +** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors {F12310} +** +** 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. ** If the busy callback is NULL, then [SQLITE_BUSY] -** (or sometimes [SQLITE_IOERR_BLOCKED]) +** 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 this routine. The second argument to ** the handler is the number of times that the busy handler has -** been invoked for this locking event. If the +** been invoked for this locking event. 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 is made to open the -** database for reading and the cycle repeats. +** 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 return [SQLITE_BUSY] instead. +** a deadlock, it will go ahead and return [SQLITE_BUSY] or +** [SQLITE_IOERR_BLOCKED] instead of invoking the +** busy handler. ** 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 @@ -474,45 +1124,66 @@ ** will induce the first process to release its read lock and allow ** the second process to proceed. ** ** The default busy callback is NULL. ** -** The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED] when -** SQLite is in the middle of a large transaction where all the +** 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 ** 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 ** 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 +** forces an automatic rollback of the changes. See the ** <a href="http://www.sqlite.org/cvstrac/wiki?p=CorruptionFollowingBusyError"> ** CorruptionFollowingBusyError</a> wiki page for a discussion of why ** this is important. -** -** Sqlite is re-entrant, so the busy handler may start a new query. -** (It is not clear why anyone would every want to do this, but it -** is allowed, in theory.) 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. ** ** There can only be a single busy handler defined for each database ** connection. Setting a new busy handler clears any previous one. ** Note that calling [sqlite3_busy_timeout()] will also set or clear ** the busy handler. +** +** INVARIANTS: +** +** {F12311} The [sqlite3_busy_handler()] function replaces the busy handler +** callback in the database connection identified by the 1st +** parameter with a new busy handler identified by the 2nd and 3rd +** parameters. +** +** {F12312} The default busy handler for new database connections is NULL. +** +** {F12314} When two or more database connection share a common cache, +** the busy handler for the database connection currently using +** the cache is invoked when the cache encounters a lock. +** +** {F12316} If a busy handler callback returns zero, then the SQLite +** interface that provoked the locking event will return +** [SQLITE_BUSY]. +** +** {F12318} SQLite will invokes the busy handler with two argument 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: +** +** {U12319} A busy handler should not call close the database connection +** or prepared statement that invoked the busy handler. */ int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); /* -** CAPI3REF: Set A Busy Timeout -** -** This routine sets a busy handler that sleeps for a while when a +** CAPI3REF: Set A Busy Timeout {F12340} +** +** This routine sets a [sqlite3_busy_handler | busy handler] +** that sleeps for a while when a ** table is locked. The handler will sleep multiple times until -** at least "ms" milliseconds of sleeping have been done. After +** 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 ** turns off all busy handlers. @@ -519,87 +1190,149 @@ ** ** 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 overrides 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 is 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 is set that repeatedly calls +** the xSleep() method in the 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 -** -** This next routine is a convenience wrapper around [sqlite3_exec()]. -** 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. -** -** As an example, suppose the query result where this table: -** -** <pre> +** CAPI3REF: Convenience Routines For Running Queries {F12370} +** +** Definition: A <b>result table</b> is memory data structure created by the +** [sqlite3_get_table()] interface. A result table records the +** complete query results from one or more queries. +** +** 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 are give a NULL pointer. All other values are in +** their UTF-8 zero-terminated string representation as returned by +** [sqlite3_column_text()]. +** +** A result table might consists 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: +** +** <blockquote><pre> ** Name | Age ** ----------------------- ** Alice | 43 ** Bob | 28 ** Cindy | 21 -** </pre> -** -** If the 3rd argument were &azResult then after the function returns -** azResult will contain the following data: -** -** <pre> -** azResult[0] = "Name"; -** azResult[1] = "Age"; -** azResult[2] = "Alice"; -** azResult[3] = "43"; -** azResult[4] = "Bob"; -** azResult[5] = "28"; -** azResult[6] = "Cindy"; -** azResult[7] = "21"; -** </pre> -** -** 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). +** </pre></blockquote> +** +** 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: +** +** <blockquote><pre> +** azResult[0] = "Name"; +** azResult[1] = "Age"; +** azResult[2] = "Alice"; +** azResult[3] = "43"; +** azResult[4] = "Bob"; +** azResult[5] = "28"; +** azResult[6] = "Cindy"; +** azResult[7] = "21"; +** </pre></blockquote> +** +** 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. ** ** After the calling function has finished using the result, it should -** pass the result data pointer to sqlite3_free_table() in order to +** pass the pointer to the result table 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. -** -** The return value of this routine is the same as from [sqlite3_exec()]. +** [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. +** +** 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 frees the result table under construction, aborts the +** query in process, skips any subsequent queries, sets the +** *resultp output pointer to NULL and returns [SQLITE_NOMEM]. +** +** {F12373} If the ncolumn parameter to [sqlite3_get_table()] is not NULL +** then [sqlite3_get_table()] write the number of columns in the +** result set of the query into *ncolumn if the query is +** successful (if the function returns SQLITE_OK). +** +** {F12374} If the nrow parameter to [sqlite3_get_table()] is not NULL +** then [sqlite3_get_table()] write the number of rows in the +** result set of the query into *nrow if the query is +** successful (if the function returns SQLITE_OK). +** +** {F12376} The [sqlite3_get_table()] function sets its *ncolumn value +** to the number of columns in the result set of the query in the +** sql parameter, or to zero if the query in sql has an empty +** result set. */ 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 */ + sqlite3*, /* An open database */ + const char *sql, /* SQL to be evaluated */ + char ***pResult, /* Results of the query */ + 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 +** CAPI3REF: Formatted String Printing Functions {F17400} ** ** These routines are workalikes of the "printf()" family of functions ** from the standard C library. ** ** The sqlite3_mprintf() and sqlite3_vmprintf() routines write their -** results into memory obtained from [sqlite_malloc()]. +** results into memory obtained from [sqlite3_malloc()]. ** The strings returned by these two routines should be -** released by [sqlite3_free()]. Both routines return a +** released by [sqlite3_free()]. 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 ** 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. 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() ** returns a pointer to its buffer instead of the number of ** characters actually written into the buffer. We admit that @@ -614,11 +1347,11 @@ ** 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" and "%Q" options. +** is are "%q", "%Q", and "%z" options. ** ** 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 '\'' ** character it escapes that character and allows it to be inserted into @@ -657,70 +1390,245 @@ ** literal. ** ** 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. So, for example, one could say: +** quotes) in place of the %Q option. {END} So, for example, one could say: ** ** <blockquote><pre> ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText); ** sqlite3_exec(db, zSQL, 0, 0, 0); ** sqlite3_free(zSQL); ** </pre></blockquote> ** ** 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 +** 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 writes 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); char *sqlite3_snprintf(int,char*,const char*, ...); /* -** CAPI3REF: Memory Allocation Functions -** -** SQLite uses its own memory allocator. On some installations, this -** memory allocator is identical to the standard malloc()/realloc()/free() -** and can be used interchangable. On others, the implementations are -** different. For maximum portability, it is best not to mix calls -** to the standard malloc/realloc/free with the sqlite versions. +** 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 +** does not include operating-system specific VFS implementation. The +** windows VFS uses native malloc and free for some operations. +** +** 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 +** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns +** a NULL pointer. +** +** 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 +** a no-op if is called with a NULL pointer. Passing a NULL pointer +** to sqlite3_free() is harmless. 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 +** 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 +** 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() +** 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 +** 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 +** 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 +** 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 +** is not freed. +** +** 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 following C preprocessor macro +** +** <blockquote> SQLITE_MEMORY_SIZE=<i>NNN</i> </blockquote> +** +** where <i>NNN</i> is an integer, then SQLite create a static +** array of at least <i>NNN</i> 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]. +** +** INVARIANTS: +** +** {F17303} The [sqlite3_malloc(N)] interface returns either a pointer to +** 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 +** where K is the lessor 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: +** +** {U17350} The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()] +** must be either NULL or else a pointer obtained from a prior +** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that has +** not been released. +** +** {U17351} 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); void sqlite3_free(void*); /* -** CAPI3REF: Compile-Time Authorization Callbacks -*** -** This routine registers a authorizer callback with the SQLite library. +** CAPI3REF: Memory Allocator Statistics {F17370} +** +** SQLite provides these two interfaces for reporting on the status +** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()] +** the memory allocation subsystem included within the SQLite. +** +** 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 highwater 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 highwater 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 highwater mark +** prior to the reset. +*/ +sqlite3_int64 sqlite3_memory_used(void); +sqlite3_int64 sqlite3_memory_highwater(int resetFlag); + +/* +** CAPI3REF: Compile-Time Authorization Callbacks {F12500} +** +** This routine registers a authorizer callback with a particular +** database connection, supplied in the first argument. ** 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 ** 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. -** -** Depending on the action, the [SQLITE_IGNORE] and [SQLITE_DENY] return -** codes might mean something different or they might mean the same -** thing. If the action is, for example, to perform a delete opertion, -** then [SQLITE_IGNORE] and [SQLITE_DENY] both cause the statement compilation -** to fail with an error. But if the action is to read a specific column -** from a specific table, then [SQLITE_DENY] will cause the entire -** statement to fail but [SQLITE_IGNORE] will cause a NULL value to be -** read instead of the actual column value. +** rejected with an error. 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 will fail with an error message. +** +** When the callback returns [SQLITE_OK], that means the operation +** requested is ok. 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 is constructed to insert 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. ** ** 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 available action codes are -** [SQLITE_COPY | documented separately]. The third through sixth -** parameters to the callback are strings that contain additional -** details about the action to be authorized. +** 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. ** ** 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 @@ -731,25 +1639,77 @@ ** user-entered SQL is being prepared that disallows everything ** except SELECT statements. ** ** 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. A NULL authorizer means that no authorization -** callback is invoked. The default authorizer is NULL. +** previous call. Disable the authorizer by installing a NULL callback. +** The authorizer is disabled by default. ** ** 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 coded 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 the +** any previously installed authorizer. +** +** {F12521} A NULL authorizer means that no authorization +** callback is invoked. +** +** {F12522} The default authorizer is NULL. */ int sqlite3_set_authorizer( sqlite3*, int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), void *pUserData ); /* -** CAPI3REF: Authorizer Return Codes +** 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 @@ -757,27 +1717,49 @@ */ #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 +** CAPI3REF: Authorizer Action Codes {F12550} ** ** The [sqlite3_set_authorizer()] interface registers a callback function ** that is invoked to authorizer certain SQL statement actions. 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. ** ** These action code values signify what kind of operation is to be -** authorized. The 3rd and 4th parameters to the authorization callback -** function will be parameters or NULL depending on which of these +** authorized. 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 ** 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. +** +** 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 function] +** 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 */ #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */ #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */ @@ -810,130 +1792,333 @@ #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 +** CAPI3REF: Tracing And Profiling Functions {F12280} ** ** 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 the first [sqlite3_step()] for the evaluation of an SQL statement. +** +** 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 triggersubprogram is entered. The callbacks for triggers +** contain a UTF-8 SQL comment that identifies the trigger. +** ** The callback function registered by sqlite3_profile() is invoked -** as each SQL statement finishes and includes -** information on how long that statement ran. +** 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. ** ** The sqlite3_profile() API is currently considered experimental and -** is subject to change. +** 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 UTF8 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. */ void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); void *sqlite3_profile(sqlite3*, - void(*xProfile)(void*,const char*,sqlite_uint64), void*); - -/* -** CAPI3REF: Query Progress Callbacks -** -** 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 + void(*xProfile)(void*,const char*,sqlite3_uint64), void*); + +/* +** CAPI3REF: Query Progress Callbacks {F12910} +** +** 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 ** interface is to keep a GUI updated during a large query. ** -** The progress callback is invoked once for every N virtual machine opcodes, -** where N is the second argument to this function. The progress callback -** itself is identified by the third argument to this function. The fourth -** argument to this function is a void pointer passed to the progress callback -** function each time it is invoked. -** -** 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. -** -** 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. -** To remove the progress callback altogether, pass NULL as the third -** argument to this function. -** -** If the progress callback returns a result other than 0, then the current -** query is immediately terminated and any database changes rolled back. -** The containing [sqlite3_exec()], [sqlite3_step()], or -** [sqlite3_get_table()] call returns SQLITE_INTERRUPT. This feature -** can be used, for example, to implement the "Cancel" button on a -** progress dialog box in a GUI. +** If the progress callback returns non-zero, the opertion 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. <todo>What if N is less than 1?</todo> +** +** {F12913} The progress callback itself is identified by the third +** argument to [sqlite3_progress_handler()]. +** +** {F12914} The fourth argument [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. {END} +** +** {F12916} Every call to [sqlite3_progress_handler()] +** overwrites any previously registere progress handler. +** +** {F12917} If the progress handler callback is NULL then no progress +** handler is invoked. +** +** {F12918} If the progress callback returns a result other than 0, then +** the behavior is a if [sqlite3_interrupt()] had been called. */ void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); /* -** CAPI3REF: Opening A New Database Connection -** -** Open the sqlite database file "filename". The "filename" is UTF-8 -** encoded for sqlite3_open() and UTF-16 encoded in the native byte order -** for sqlite3_open16(). An [sqlite3*] handle is returned in *ppDb, even -** if an error occurs. If the database is opened (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 +** 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()]. +** An [sqlite3*] handle is usually returned in *ppDb, even +** if an error occurs. The only exception is 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 ** an English language description of the error. ** -** If the database file does not exist, then a new database will be created -** as needed. The default encoding for the database will be UTF-8 if -** sqlite3_open() is called and UTF-16 if sqlite3_open16 is used. -** -** 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. -** -** Note to windows users: The encoding used for the filename argument -** of sqlite3_open() 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(). +** 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 [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 acccepts two additional parameters for additional control +** over the new database connection. The flags parameter can be +** one of: +** +** <ol> +** <li> [SQLITE_OPEN_READONLY] +** <li> [SQLITE_OPEN_READWRITE] +** <li> [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE] +** </ol> +** +** The first value opens the database read-only. +** If the database does not previously exist, an error is returned. +** The second option opens +** the database for reading and writing if possible, or reading only if +** if the file is write protected. In either case the database +** must already exist or an error is returned. The third option +** opens the database for reading and writing and creates it if it does +** not already exist. +** The third options is behavior that is always used for [sqlite3_open()] +** and [sqlite3_open16()]. +** +** If the filename is ":memory:", then an private +** in-memory database is created for the connection. This in-memory +** database will vanish when the database connection is closed. 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 filename is an empty string, then a private temporary +** on-disk database will be created. 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. +** +** <b>Note to windows users:</b> 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. +** <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required +** in sqlite3_open_v2()?</todo> +** +** {F12719} If the filename is an empty string, then a private, ephermeral +** on-disk database will be created. +** <todo>Is SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE required +** in sqlite3_open_v2()?</todo> +** +** {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 is V is a NULL pointer. */ 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 */ ); - -/* -** CAPI3REF: Error Codes And Messages +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} ** ** 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'. If a prior API call failed but the +** with [sqlite3] handle 'db'. If a prior API call failed but the ** most recent API call succeeded, the return value from sqlite3_errcode() ** is undefined. ** -** The sqlite3_errmsg() and sqlite3_errmsg16() return English-langauge +** The sqlite3_errmsg() and sqlite3_errmsg16() return English-language ** text that describes the error, as either UTF8 or UTF16 respectively. -** Memory to hold the error message string is managed internally. The -** string may be overwritten or deallocated by subsequent calls to SQLite -** interface functions. -** -** Calls to many sqlite3_* functions set the error code and string returned -** by [sqlite3_errcode()], [sqlite3_errmsg()], and [sqlite3_errmsg16()] -** (overwriting the previous values). Note that calls to [sqlite3_errcode()], -** [sqlite3_errmsg()], and [sqlite3_errmsg16()] themselves do not affect the -** results of future invocations. Calls to API routines that do not return -** an error code (examples: [sqlite3_data_count()] or [sqlite3_mprintf()]) do -** not change the error code returned by this routine. -** -** 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()]. +** Memory to hold the error message string is managed internally. +** The application does not need to worry with freeing the result. +** However, the error string might be overwritten or deallocated b +** subsequent calls to other SQLite interface functions. +** +** INVARIANTS: +** +** {F12801} The [sqlite3_errcode(D)] interface returns the numeric +** [SQLITE_OK | result code] or +** [SQLITE_IOERR_READ | extended result code] +** for the most recent failed interface call associated +** with [sqlite3] handle D. +** +** {U12802} If a prior API call failed but the most recent API call +** succeeded, the return value from [sqlite3_errcode()], +** [sqlite3_errmsg()], and [sqlite3_errmsg16()] are undefined. +** +** {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 UTF8 or UTF16 respectively. +** +** {U12804} The strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()] +** are only valid until the next SQLite interface call. +** +** {F12807} Calls to [sqlite3_errcode()], [sqlite3_errmsg()], and +** [sqlite3_errmsg16()] themselves do not affect the +** results of future invocations of these routines. +** +** {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()]. */ int sqlite3_errcode(sqlite3 *db); const char *sqlite3_errmsg(sqlite3*); const void *sqlite3_errmsg16(sqlite3*); /* -** CAPI3REF: SQL Statement Object -** -** Instance of this object represent single SQL statements. This -** is variously known as a "prepared statement" or a +** CAPI3REF: SQL Statement Object {F13000} +** KEYWORDS: {prepared statement} {prepared statements} +** +** 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: ** ** <ol> @@ -951,76 +2136,110 @@ ** information. */ typedef struct sqlite3_stmt sqlite3_stmt; /* -** CAPI3REF: Compiling An SQL Statement +** 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. ** -** The first argument "db" is an [sqlite3 | SQLite database handle] -** obtained from a prior call to [sqlite3_open()] or [sqlite3_open16()]. +** The first argument "db" is an [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 ** 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. +** 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 +** 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' character or -** until the nByte-th byte, whichever comes first. -** -** *pzTail is made to point to the first byte past the end of the first -** SQL statement in zSql. This routine only compiles the first statement -** in zSql, so *pzTail is left pointing to what remains uncompiled. -** -** *ppStmt is left pointing to a compiled -** [sqlite3_stmt | SQL statement structure] that can be +** 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 compiles the first +** statement in zSql, so *pzTail is left pointing to what remains +** uncompiled. +** +** *ppStmt is left pointing to a compiled [prepared statement] that can be ** executed using [sqlite3_step()]. Or if there is an error, *ppStmt may be -** set to NULL. If the input text contained no SQL (if the input is and -** empty string or a comment) then *ppStmt is set to NULL. The calling -** procedure is responsible for deleting the compiled SQL statement +** set to NULL. 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 -** [SQLITE_ERROR | error code] is returned. +** [error code] is returned. ** ** 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 +** original SQL text. {END} This causes the [sqlite3_step()] interface to ** behave a differently in two ways: ** ** <ol> ** <li> ** 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 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. +** statement and try to run it again. 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. {END} ** </li> ** ** <li> ** When an error occurs, ** [sqlite3_step()] will return one of the detailed -** [SQLITE_ERROR | result codes] or -** [SQLITE_IOERR_READ | extended result codes] such as directly. +** [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. ** </li> ** </ol> +** +** 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, then 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 nBytes bytes +** 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. +** <todo>What does *pzTail point to if there is one statement?</todo> +** +** {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. */ int sqlite3_prepare( sqlite3 *db, /* Database handle */ const char *zSql, /* SQL statement, UTF-8 encoded */ int nByte, /* Maximum length of zSql in bytes. */ @@ -1048,88 +2267,116 @@ sqlite3_stmt **ppStmt, /* OUT: Statement handle */ const void **pzTail /* OUT: Pointer to unused portion of zSql */ ); /* -** CAPI3REF: Dynamically Typed Value Object -** -** SQLite uses dynamic typing for the values it stores. Values can -** be integers, floating point values, strings, BLOBs, or NULL. When -** passing around values internally, each value is represented as -** an instance of the sqlite3_value object. +** CAPIREF: Retrieving Statement SQL {F13100} +** +** This intereface can be used to retrieve a saved copy of the original +** SQL text used to create a [prepared statement]. +** +** INVARIANTS: +** +** {F13101} If the [prepared statement] passed as +** the an argument to [sqlite3_sql()] was compiled +** compiled using either [sqlite3_prepare_v2()] or +** [sqlite3_prepare16_v2()], +** then [sqlite3_sql()] function 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 an argument to [sqlite3_sql()] was compiled +** compiled using either [sqlite3_prepare()] or +** [sqlite3_prepare16()], +** then [sqlite3_sql()] function 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)]. +*/ +const char *sqlite3_sql(sqlite3_stmt *pStmt); + +/* +** CAPI3REF: Dynamically Typed Value Object {F15000} +** +** SQLite uses the sqlite3_value object to represent all values +** that are or can be stored in a database table. +** SQLite uses dynamic typing for the values it stores. +** 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 +** CAPI3REF: SQL Function Context Object {F16001} ** ** The context in which an SQL function executes is stored in an -** sqlite3_context object. A pointer to such an object is the -** first parameter to user-defined SQL functions. +** sqlite3_context object. 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 -** -** In the SQL strings input to [sqlite3_prepare_v2()] and its variants, -** one or more literals can be replace by a parameter in one of these -** forms: +** CAPI3REF: Binding Values To Prepared Statements {F13500} +** +** In the SQL strings input to [sqlite3_prepare_v2()] and its +** variants, literals may be replace by a parameter in one +** of these forms: ** ** <ul> ** <li> ? ** <li> ?NNN -** <li> :AAA -** <li> @AAA +** <li> :VVV +** <li> @VVV ** <li> $VVV ** </ul> ** ** 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. -** The values of these parameters (also called "host parameter names") +** VVV alpha-numeric parameter name. +** The values of these parameters (also called "host parameter names" +** or "SQL parameters") ** can be set using the sqlite3_bind_*() routines defined here. ** -** 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. The second -** argument is the index of the parameter to be set. The first parameter has -** an index of 1. When the same named 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_name()] API if desired. The index for "?NNN" -** parametes is the value of NNN. +** 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. The second +** argument is the index of the parameter to be set. The +** first parameter has an index of 1. When the same named +** 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_name()] API if desired. The index +** for "?NNN" parameters is the value of NNN. ** The NNN value must be between 1 and the compile-time ** parameter SQLITE_MAX_VARIABLE_NUMBER (default value: 999). -** See <a href="limits.html">limits.html</a> for additional information. ** ** The third argument is the value to bind to the parameter. ** ** 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. The number +** in the parameter. To be clear: the value is the number of <u>bytes</u> +** in the value, not the number of characters. The number ** of bytes does not include the zero-terminator at the end of strings. ** If the fourth parameter is negative, the length of the string is ** number of bytes up to the first zero terminator. ** ** 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. 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 SQLite makes its -** own private copy of the data immediately, before the sqlite3_bind_*() -** routine returns. -** -** The sqlite3_bind_zeroblob() routine binds a BLOB of length n that +** string after SQLite has finished with it. If the fifth argument is +** the special value [SQLITE_STATIC], then SQLite 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 +** SQLite makes its own private copy of the data immediately, before +** the sqlite3_bind_*() routine returns. +** +** The sqlite3_bind_zeroblob() routine binds a BLOB of length N that ** is filled with zeros. A zeroblob uses a fixed amount of memory ** (just an integer to hold it size) while it is being processed. ** Zeroblobs are intended to serve as place-holders for BLOBs whose ** content is later written using -** [sqlite3_blob_open | increment BLOB I/O] routines. +** [sqlite3_blob_open | increment BLOB I/O] routines. A negative +** value for the zeroblob results in a zero-length BLOB. ** ** The sqlite3_bind_*() routines must be called after ** [sqlite3_prepare_v2()] (and its variants) or [sqlite3_reset()] and ** before [sqlite3_step()]. ** Bindings are not cleared by the [sqlite3_reset()] routine. @@ -1136,159 +2383,395 @@ ** Unbound parameters are interpreted as NULL. ** ** 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] is returned if these routines are called on a virtual -** machine that is the wrong state or which has already been finalized. +** [SQLITE_MISUSE] might be 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 [sqlite3_prepare | 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 occurances of the same +** parameter, or one more than the largest index over all +** parameters to the left if this is the first occurrance +** of this parameter, or 1 if this is the leftmost parameter. +** +** {F13521} The [sqlite3_prepare | SQL statement compiler] fail with +** an [SQLITE_RANGE] error if the index of an SQL parameter +** is less than 1 or greater than SQLITE_MAX_VARIABLE_NUMBER. +** +** {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 V value 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 +** V value after it has finished using the V value. +** +** {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. */ 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, sqlite_int64); +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 -** -** Return the largest host parameter index in the precompiled statement given -** as the argument. When the host parameters are of the forms like ":AAA" -** or "?", then they are assigned sequential increasing numbers beginning -** with one, so the value returned is the number of parameters. 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. 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. +** CAPI3REF: Number Of SQL 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 +** place-holders for values that are [sqlite3_bind_blob | bound] +** to the parameters at a later time. +** +** This routine actually returns the index of the largest 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. */ int sqlite3_bind_parameter_count(sqlite3_stmt*); /* -** CAPI3REF: Name Of A Host Parameter -** -** This routine returns a pointer to the name of the n-th parameter in a -** [sqlite3_stmt | prepared statement]. -** Host parameters of the form ":AAA" or "@AAA" or "$VVV" have a name +** 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 ":AAA" or "@AAA" or "$AAA" 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. ** Parameters of the form "?" or "?NNN" have no name. ** -** The first bound 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 the -** UTF-8 encoding even if the named parameter was originally specified -** as UTF-16 in [sqlite3_prepare16()] or [sqlite3_prepare16_v2()]. +** 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 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 +** [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 "?" or +** a numbered parameter "?NNN". */ const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); /* -** CAPI3REF: Index Of A Parameter With A Given Name -** -** This routine returns the index of a host parameter with the given name. -** The name must match exactly. If no parameter with the given name is -** found, return 0. Parameter names must be UTF8. +** 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 [prepared statement] +** S whose name matches the UTF-8 string N, or 0 if there is +** no match. */ int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); /* -** CAPI3REF: Reset All Bindings On A Prepared Statement +** 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 -** [sqlite3_stmt | prepared statement]. Use this routine to +** [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 [prepared statement] S +** back to NULL. */ int sqlite3_clear_bindings(sqlite3_stmt*); /* -** CAPI3REF: Number Of Columns In A Result Set +** CAPI3REF: Number Of Columns In A Result Set {F13710} ** ** Return the number of columns in the result set returned by the -** [sqlite3_stmt | compiled SQL statement]. This routine returns 0 +** [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. */ int sqlite3_column_count(sqlite3_stmt *pStmt); /* -** CAPI3REF: Column Names In A Result Set +** 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 UTF8 string and sqlite3_column_name16() -** returns a pointer to a UTF16 string. The first parameter is the -** [sqlite_stmt | prepared statement] that implements the SELECT statement. +** interface returns a pointer to a zero-terminated UTF8 string +** and sqlite3_column_name16() returns a pointer to a zero-terminated +** UTF16 string. The first parameter is the +** [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 -** [sqlite_stmt | prepared statement] is destroyed by [sqlite3_finalize()] +** [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 +** (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 left-most column) for the +** result set of [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 left-most column) for the +** result set of [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 memory to hold there 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 returns 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 indentifier +** 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); /* -** CAPI3REF: Source Of Data In A Query Result +** 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 UTF8 or UTF16 string. 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 [sqlite3_stmt | prepared statement] is destroyed using +** the [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 ** database, table, and column. ** -** The first argument to the following calls is a -** [sqlite3_stmt | compiled SQL statement]. +** The first argument to the following calls is a [prepared statement]. ** 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. Otherwise, they return the +** 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. ** -** As with all other SQLite APIs, those postfixed with "16" return UTF-16 -** encoded strings, the other functions return UTF-8. +** 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. +** +** 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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 [prepared statement] S +** is extracted, or NULL if the 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: +** +** {U13751} If two or more threads call one or more +** [sqlite3_column_database_name|column metadata interfaces] +** 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); 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 -** -** The first parameter is a [sqlite3_stmt | compiled SQL statement]. +** 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 +** 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. 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. For example, in -** the database schema: +** 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: ** @@ -1302,18 +2785,40 @@ ** 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); +** +** INVARIANTS: +** +** {F13761} A successful call to [sqlite3_column_decltype(S,N)] +** returns a zero-terminated UTF-8 string containing the +** 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 [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 void *sqlite3_column_decltype16(sqlite3_stmt*,int); /* -** CAPI3REF: Evaluate An SQL Statement -** -** After an [sqlite3_stmt | SQL statement] has been prepared with a call +** CAPI3REF: Evaluate An SQL Statement {F13200} +** +** After an [prepared 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. ** @@ -1352,15 +2857,15 @@ ** 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 -** [sqlite_stmt | prepared statement]. In the "v2" interface, +** [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 [sqlite_stmt | prepared statement] that has +** Perhaps it was called on a [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. ** @@ -1368,46 +2873,81 @@ ** 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. +** [error 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 +** more specific [error codes] are returned directly ** by sqlite3_step(). The use of the "v2" interface is recommended. +** +** INVARIANTS: +** +** {F13202} If [prepared statement] S is ready to be +** run, then [sqlite3_step(S)] advances that prepared statement +** until to completion or until it is ready to return another +** row of the result set or an interrupt or 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 appropraite error code that is not one of +** [SQLITE_OK], [SQLITE_ROW], or [SQLITE_DONE]. +** +** {F15310} If an [sqlite3_interrupt|interrupt] or 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: +** CAPI3REF: Number of columns in a result set {F13770} ** ** Return the number of values in the current row of the result set. ** -** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine -** will return the same value as the [sqlite3_column_count()] function. -** 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 [sqlite_stmt | prepared statement] for the first time, -** this routine returns zero. +** 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. */ int sqlite3_data_count(sqlite3_stmt *pStmt); /* -** CAPI3REF: Fundamental Datatypes -** -** Every value in SQLite has one of five fundamental datatypes: +** CAPI3REF: Fundamental Datatypes {F10265} +** KEYWORDS: SQLITE_TEXT +** +** {F10266}Every value in SQLite has one of five fundamental datatypes: ** ** <ul> ** <li> 64-bit signed integer ** <li> 64-bit IEEE floating point number ** <li> string ** <li> BLOB ** <li> NULL -** </ul> +** </ul> {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 @@ -1424,23 +2964,35 @@ # define SQLITE_TEXT 3 #endif #define SQLITE3_TEXT 3 /* -** CAPI3REF: Results Values From A Query -** -** These routines return information about the information -** in a single column of the current result row of a query. In every +** 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 -** evaluate (the [sqlite_stmt*] that was returned from +** [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 left-most column has an index of 0. +** 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 @@ -1459,12 +3011,17 @@ ** 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 empty 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. +** but leaves the result in UTF-16 in native byte order 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 @@ -1471,12 +3028,11 @@ ** automatically. The following table details the conversions that ** are applied: ** ** <blockquote> ** <table border="1"> -** <tr><th> Internal <th> Requested <th> -** <tr><th> Type <th> Type <th> Conversion +** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion ** ** <tr><td> NULL <td> INTEGER <td> Result is 0 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0 ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer @@ -1540,64 +3096,159 @@ ** 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 <b>not</b> 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]. +** +** INVARIANTS: +** +** {F13803} The [sqlite3_column_blob(S,N)] interface converts the +** Nth column in the current row of the result set for +** [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 +** [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 +** [prepared statement] S into a 32-bit signed integer and +** returns a copy of that integer. +** +** {F13818} The [sqlite3_column_int64(S,N)] interface converts the +** Nth column in the current row of the result set for +** [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 +** [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 +** [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 +** [prepared statement] S. +** +** {F13830} The [sqlite3_column_value(S,N)] interface returns a +** pointer to the [sqlite3_value] object that for the +** Nth column in the current row of the result set for +** [prepared statement] S. */ 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); -sqlite_int64 sqlite3_column_int64(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 +** 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 +** [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 -** [SQLITE_ERROR | error code] or [SQLITE_IOERR_READ | extended error code] +** [error code] or [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 +** [prepared statement]. 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]. +** [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. */ int sqlite3_finalize(sqlite3_stmt *pStmt); /* -** CAPI3REF: Reset A Prepared Statement Object +** CAPI3REF: Reset A Prepared Statement Object {F13330} ** ** The sqlite3_reset() function is called to reset a -** [sqlite_stmt | compiled SQL statement] object. -** back to it's initial state, ready to be re-executed. +** [prepared 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 +** [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 +** [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 [prepared statement] S. */ int sqlite3_reset(sqlite3_stmt *pStmt); /* -** CAPI3REF: Create Or Redefine SQL Functions -** -** The following two functions are used to add SQL functions or aggregates +** CAPI3REF: Create Or Redefine SQL Functions {F16100} +** KEYWORDS: {function creation routines} +** +** 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 ** 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 +** The first argument is the [database connection] 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. ** @@ -1615,21 +3266,21 @@ ** 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 sqlite_create_function() or sqlite3_create_function16() multiple +** 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 -** [sqlite_user_data()]. +** [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 @@ -1641,34 +3292,44 @@ ** 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. +** +** 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 a +** zero-terminated UTF-8. +** +** {F16106} */ int sqlite3_create_function( - sqlite3 *, + sqlite3 *db, const char *zFunctionName, int nArg, int eTextRep, - void*, + void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); int sqlite3_create_function16( - sqlite3*, + sqlite3 *db, const void *zFunctionName, int nArg, int eTextRep, - void*, + void *pApp, void (*xFunc)(sqlite3_context*,int,sqlite3_value**), void (*xStep)(sqlite3_context*,int,sqlite3_value**), void (*xFinal)(sqlite3_context*) ); /* -** CAPI3REF: Text Encodings +** CAPI3REF: Text Encodings {F10267} ** ** These constant define integer codes that represent the various ** text encodings supported by SQLite. */ #define SQLITE_UTF8 1 @@ -1689,14 +3350,15 @@ */ int sqlite3_aggregate_count(sqlite3_context*); int sqlite3_expired(sqlite3_stmt*); int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*); int sqlite3_global_recover(void); - - -/* -** CAPI3REF: Obtaining SQL Function Parameter Values +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. ** @@ -1719,66 +3381,83 @@ ** 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 order -** words if the value is original a string that looks like a number) -** then it is done. Otherwise no conversion occurs. The +** 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()], [sqlite_value_text()], +** [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*); -sqlite_int64 sqlite3_value_int64(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 +** CAPI3REF: Obtain Aggregate Function Context {F16210} ** ** The implementation of aggregate SQL functions use this routine to allocate -** a structure for storing their state. The first time this routine -** is called for a particular aggregate, a new structure of size nBytes -** is allocated, zeroed, and returned. On subsequent calls (for the -** same aggregate instance) the same buffer is returned. The implementation +** 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 buffer allocated is freed automatically by SQLite whan the aggregate -** query concludes. +** {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 -** -** The pUserData parameter to the [sqlite3_create_function()] -** and [sqlite3_create_function16()] routines -** used to register user functions is available to -** the implementation of the function using this call. +** 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 +** 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 @@ -1787,32 +3466,42 @@ ** 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 with the Nth argument value to the current SQL function -** call, where N is the second parameter. If no meta-data has been set for -** that value, then a NULL pointer is returned. -** -** The sqlite3_set_auxdata() is used to associate meta-data with an SQL -** function argument. The third parameter is a pointer to the meta-data -** to be associated with the Nth user function argument value. The fourth -** parameter specifies a destructor that will be called on the meta- -** data pointer to release it when it is no longer required. If the -** destructor is NULL, it is not invoked. +** 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. -*/ -void *sqlite3_get_auxdata(sqlite3_context*, int); -void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); - - -/* -** CAPI3REF: Constants Defining Special Destructor Behavior +** +** 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 @@ -1826,11 +3515,11 @@ 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 +** 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. @@ -1840,75 +3529,160 @@ ** to bind values to host parameters in prepared statements. ** Refer to the ** [sqlite3_bind_blob | sqlite3_bind_* documentation] for ** additional information. ** -** The sqlite3_result_error() and sqlite3_result_error16() functions -** cause the implemented SQL function to throw an exception. The -** parameter to sqlite3_result_error() or sqlite3_result_error16() -** is the text of an error message. -** -** The sqlite3_result_toobig() cause the function implementation -** to throw and error indicating that a string or BLOB is to long -** to represent. +** {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*, sqlite_int64); +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 -** +** 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(). 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. ** -** The third argument must be one of the constants [SQLITE_UTF8], +** {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. -** +** 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. If it is NULL, this is the same as deleting the collation -** sequence (so that SQLite cannot call it anymore). Each time the user +** 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. ** -** The remaining arguments to the user-supplied routine are two strings, -** each represented by a [length, data] pair and encoded in the encoding +** {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. The user routine should return negative, zero or positive if +** 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. The destructor is called when the collation is +** 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 +** 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()]. -** -** The sqlite3_create_collation_v2() interface is experimental and -** subject to change in future releases. The other collation creation -** functions are stable. */ int sqlite3_create_collation( sqlite3*, const char *zName, int eTextRep, @@ -1930,30 +3704,33 @@ void*, int(*xCompare)(void*,int,const void*,int,const void*) ); /* -** CAPI3REF: Collation Needed Callbacks -** +** 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. If sqlite3_collation_needed16() is used, the names -** are passed as UTF-16 in machine native byte order. A call to either +** 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 -** handle. 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()]. */ @@ -1992,218 +3769,249 @@ sqlite3 *db, /* Database to be rekeyed */ const void *pKey, int nKey /* The new key */ ); /* -** CAPI3REF: Suspend Execution For A Short Time -** -** This function causes the current thread to suspend execution -** a number of milliseconds specified in its parameter. -** -** If the operating system does not support sleep requests with +** 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. The number of milliseconds of sleep actually +** 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 +** 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. ** -** Once [sqlite3_open()] has been called, changing this variable will -** invalidate the current temporary database, if any. Generally speaking, -** it is not safe to invoke this routine after [sqlite3_open()] has -** been called. -*/ -extern char *sqlite3_temp_directory; - -/* -** CAPI3REF: Test To See If The Databse Is In Auto-Commit Mode -** -** Test to see whether or not the database connection is in autocommit -** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on -** by default. Autocommit is disabled by a BEGIN statement and reenabled -** by the next COMMIT or ROLLBACK. +** 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} +** +** 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 reenabled by a [COMMIT] or [ROLLBACK]. +** +** 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. The only way to +** find out if SQLite automatically rolled back the transaction after +** an error is to use this function. +** +** INVARIANTS: +** +** {F12931} The [sqlite3_get_autocommit()] interface 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 successful [BEGIN] statement. +** +** {F12934} Autocommit mode is enabled by a successful [COMMIT] or [ROLLBACK] +** statement. +** +** +** LIMITATIONS: +*** +** {U12936} If another thread changes the autocommit status of the database +** connection while this routine is running, then the return value +** is undefined. */ int sqlite3_get_autocommit(sqlite3*); /* -** CAPI3REF: Find The Database Handle Associated With A Prepared Statement -** -** Return the [sqlite3*] database handle to which a -** [sqlite3_stmt | prepared statement] belongs. -** This is the same database handle that was +** CAPI3REF: Find The Database Handle Of A Prepared Statement {F13120} +** +** {F13121} The sqlite3_db_handle interface +** returns the [sqlite3*] database handle to which a +** [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 -** -** These routines -** register callback functions to be invoked whenever a transaction -** is committed or rolled back. The pArg argument is passed through -** to the callback. If the callback on a commit hook function +** 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. ** -** If another function was previously registered, its pArg value is returned. -** Otherwise NULL is returned. -** -** Registering a NULL function disables the callback. -** -** For the purposes of this API, a transaction is said to have been +** {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. The -** callback is not invoked if a transaction is automatically rolled -** back because the database connection is closed. +** 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. +** <todo> Check on this </todo> {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 -** -** Register a callback function with the database connection identified by the +** 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. -** Any callback set by a previous call to this function for the same +** {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 +** {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. The final callback parameter is -** the rowid of the row. In the case of an update, this is the rowid after +** 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. +** {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 *,sqlite_int64), + void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); /* -** CAPI3REF: Enable Or Disable Shared Pager Cache -** +** 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. ** -** Cache sharing is enabled and disabled on a thread-by-thread basis. -** Each call to this routine enables or disables cache sharing only for -** connections created in the same thread in which this routine is called. -** There is no mechanism for sharing cache between database connections -** running in different threads. -** -** Sharing must be disabled prior to shutting down a thread or else -** the thread will leak memory. Call this routine with an argument of -** 0 to turn off sharing. Or use the sqlite3_thread_cleanup() API. -** -** This routine must not be called when any database connections -** are active in the current thread. Enabling or disabling shared -** cache while there are active database connections will result -** in memory corruption. -** -** When the shared cache is enabled, the -** following routines must always be called from the same thread: -** [sqlite3_open()], [sqlite3_prepare_v2()], [sqlite3_step()], -** [sqlite3_reset()], [sqlite3_finalize()], and [sqlite3_close()]. -** This is due to the fact that the shared cache makes use of -** thread-specific storage so that it will be available for sharing -** with other connections. -** -** Virtual tables cannot be used with a shared cache. When shared -** cache is enabled, the sqlite3_create_module() API used to register -** virtual tables will always return an error. -** -** This routine returns [SQLITE_OK] if shared cache was -** enabled or disabled successfully. An [SQLITE_ERROR | error code] -** is returned otherwise. -** -** Shared cache is disabled by default for backward compatibility. +** {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 [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 -** -** Attempt to free N bytes of heap memory by deallocating non-essential -** memory allocations held by the database library (example: memory -** used to cache database pages to improve performance). -** -** This function is not a part of standard builds. It is only created -** if SQLite is compiled with the SQLITE_ENABLE_MEMORY_MANAGEMENT macro. +** 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 -** -** Place a "soft" limit on the amount of heap memory that may be allocated by -** SQLite within the current thread. If an internal allocation is requested -** that would exceed the specified limit, [sqlite3_release_memory()] is invoked -** one or more times to free up some space before the allocation is made. -** -** 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. -** -** Prior to shutting down a thread sqlite3_soft_heap_limit() must be set to -** zero (the default) or else the thread will leak memory. Alternatively, use -** the [sqlite3_thread_cleanup()] API. -** +** 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 exhaused. -** The default value for the soft heap limit is zero. -** -** SQLite makes a best effort to honor the soft heap limit. But if it -** is unable to reduce memory usage below the soft limit, execution will -** continue without error or notification. This is why the limit is +** [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. ** -** This function is only available if the library was compiled with the -** SQLITE_ENABLE_MEMORY_MANAGEMENT option set. -** memory-management has been enabled. +** 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: Clean Up Thread Local Storage -** -** This routine makes sure that all thread-local storage has been -** deallocated for the current thread. -** -** This routine is not technically necessary. All thread-local storage -** will be automatically deallocated once memory-management and -** shared-cache are disabled and the soft heap limit has been set -** to zero. This routine is provided as a convenience for users who -** want to make absolutely sure they have not forgotten something -** prior to killing off a thread. -*/ -void sqlite3_thread_cleanup(void); - -/* -** CAPI3REF: Extract Metadata About A Column Of A Table +** 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. @@ -2271,26 +4079,33 @@ 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 colums is auto-increment */ + int *pAutoinc /* OUTPUT: True if column is auto-increment */ ); /* -** CAPI3REF: Load An Extension -** -** Attempt to load an SQLite extension library contained in the file -** zFile. The entry point is zProc. zProc may be 0 in which case the -** name of the entry point defaults to "sqlite3_extension_init". -** -** Return [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong. -** -** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with -** error message text. The calling function should free this memory +** 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 */ @@ -2298,59 +4113,62 @@ 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 +** 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. It is off by default. See ticket #1863. -** -** Call this routine with onoff==1 to turn extension loading on -** and call it with onoff==0 to turn it back off again. +** 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 -** -** Register an extension entry point that is automatically invoked +** 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()] or [sqlite3_open16()]. +** [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. ** -** Duplicate extensions are detected so calling this routine multiple +** {F12642} Duplicate extensions are detected so calling this routine multiple ** times with the same extension is harmless. ** -** This routine stores a pointer to the extension in an array -** that is obtained from malloc(). If you run a memory leak +** {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_automatic_extension_reset()] prior +** array, then invoke [sqlite3_reset_auto_extension()] prior ** to shutdown to free the memory. ** -** 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 -** -** Disable all previously registered automatic extensions. This -** routine undoes the effect of all prior [sqlite3_automatic_extension()] +** 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_auto_extension()] ** calls. ** -** This call disabled 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); @@ -2396,12 +4214,12 @@ 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*, sqlite_int64 *pRowid); - int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite_int64 *); + 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, @@ -2421,18 +4239,19 @@ ** The aConstraint[] array records WHERE clause constraints of the ** form: ** ** column OP expr ** -** Where OP is =, <, <=, >, or >=. The particular operator is stored +** 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 simplificatinos to the WHERE clause in an attempt to +** 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[]. @@ -2457,28 +4276,28 @@ ** 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 */ - const int nConstraint; /* Number of entries in aConstraint */ - const struct sqlite3_index_constraint { + 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 */ - } *const aConstraint; /* Table of WHERE clause constraints */ - const int nOrderBy; /* Number of terms in the ORDER BY clause */ - const struct sqlite3_index_orderby { + } *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. */ - } *const aOrderBy; /* The ORDER BY clause */ + } *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 */ - } *const aConstraintUsage; + } *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 */ @@ -2517,11 +4336,11 @@ ); /* ** Every module implementation uses a subclass of the following structure ** to describe a particular instance of the module. Each subclass will -** be taylored to the specific needs of the module implementation. The +** 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 @@ -2583,112 +4402,391 @@ ** 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 stablizes, we will declare the +** 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 +** 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 [sqltie3_blob_size()] interface returns the size of the +** 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 -** -** Open a handle to the blob located in row iRow,, column zColumn, -** table zTable in database zDb. i.e. the same blob that would -** be selected by: +** 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: ** ** <pre> ** SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; -** </pre> -** -** If the flags parameter is non-zero, the blob is opened for +** </pre> {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. -** -** On success, [SQLITE_OK] is returned and the new +** access. {END} +** +** {F17813} On success, [SQLITE_OK] is returned and the new ** [sqlite3_blob | blob handle] is written to *ppBlob. -** Otherwise an error code is returned and +** {F17814} Otherwise an error code is returned and ** any value written to *ppBlob should not be used by the caller. -** This function sets the database-handle error code and message +** {F17815} This function sets the database-handle error code and message ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()]. +** <todo>We should go through and mark all interfaces that behave this +** way with a similar statement</todo> */ int sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, - sqlite_int64 iRow, + sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); /* -** CAPI3REF: Close A BLOB Handle +** 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 -** -** Return the size in bytes of the blob accessible via the open +** 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 +** 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. -** n bytes of data are copied into buffer +** {F17851} n bytes of data are copied into buffer ** z from the open blob, starting at offset iOffset. ** -** On success, SQLITE_OK is returned. Otherwise, an -** [SQLITE_ERROR | SQLite error code] or an -** [SQLITE_IOERR_READ | extended error code] is returned. +** {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 +** [error code] or an [extended error code] is returned. */ int sqlite3_blob_read(sqlite3_blob *, void *z, int n, int iOffset); /* -** CAPI3REF: Write Data Into A BLOB Incrementally +** 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. -** n bytes of data are copied from the 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 [sqlite3_blob | blob-handle] passed as the first argument +** {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. -** -** On success, SQLITE_OK is returned. Otherwise, an -** [SQLITE_ERROR | SQLite error code] or an -** [SQLITE_IOERR_READ | extended error code] is returned. +** {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 +** [error code] or an [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: +** +** <ul> +** <li> SQLITE_MUTEX_OS2 +** <li> SQLITE_MUTEX_PTHREAD +** <li> SQLITE_MUTEX_W32 +** <li> SQLITE_MUTEX_NOOP +** </ul> +** +** 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: +** +** <ul> +** <li> SQLITE_MUTEX_FAST +** <li> SQLITE_MUTEX_RECURSIVE +** <li> SQLITE_MUTEX_STATIC_MASTER +** <li> SQLITE_MUTEX_STATIC_MEM +** <li> SQLITE_MUTEX_STATIC_MEM2 +** <li> SQLITE_MUTEX_STATIC_PRNG +** <li> SQLITE_MUTEX_STATIC_LRU +** </ul> {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 +** <a href="lang_attach.html">ATTACH</a> 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*); + +/* +** 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 a 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 meansing 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_FAULT_CONFIG 1 +#define SQLITE_TESTCTRL_FAULT_FAILURES 2 +#define SQLITE_TESTCTRL_FAULT_BENIGN_FAILURES 3 +#define SQLITE_TESTCTRL_FAULT_PENDING 4 + + + + /* ** Undo the hack that converts floating point types to integer for ** builds on processors without floating point support. */
Modified src/xfer.c from [fe8089aded] to [f7995ea18a].
@@ -284,17 +284,17 @@ } /* ** Send a gimme message for every phantom. */ -static void request_phantoms(Xfer *pXfer){ +static void request_phantoms(Xfer *pXfer, int maxReq){ Stmt q; db_prepare(&q, "SELECT uuid FROM phantom JOIN blob USING(rid)" " WHERE NOT EXISTS(SELECT 1 FROM shun WHERE uuid=blob.uuid)" ); - while( db_step(&q)==SQLITE_ROW ){ + while( db_step(&q)==SQLITE_ROW && maxReq-- > 0 ){ const char *zUuid = db_column_text(&q, 0); blob_appendf(pXfer->pOut, "gimme %s\n", zUuid); pXfer->nGimmeSent++; } db_finalize(&q); @@ -464,11 +464,11 @@ blobarray_zero(xfer.aToken, count(xfer.aToken)); cgi_set_content_type(g.zContentType); blob_zero(&xfer.err); xfer.pIn = &g.cgiIn; xfer.pOut = cgi_output_blob(); - xfer.mxSend = db_get_int("max-download", 1000000); + xfer.mxSend = db_get_int("max-download", 5000000); db_begin_transaction(); db_multi_exec( "CREATE TEMP TABLE onremote(rid INTEGER PRIMARY KEY);" ); @@ -645,11 +645,11 @@ @ error bad\scommand:\s%F(blob_str(&xfer.line)) } blobarray_reset(xfer.aToken, xfer.nToken); } if( isPush ){ - request_phantoms(&xfer); + request_phantoms(&xfer, 500); } if( isPull ){ create_cluster(); send_unclustered(&xfer); } @@ -703,11 +703,13 @@ const char *zSCode = db_get("server-code", "x"); const char *zPCode = db_get("project-code", 0); int nMsg = 0; /* Number of messages sent or received */ int nCycle = 0; /* Number of round trips to the server */ int nFileSend = 0; - const char *zCookie; /* Server cookie */ + int nFileRecv; /* Number of files received */ + int mxPhantomReq = 200; /* Max number of phantoms to request per comm */ + const char *zCookie; /* Server cookie */ Blob send; /* Text we are sending to the server */ Blob recv; /* Reply we got back from the server */ Xfer xfer; /* Transfer data */ memset(&xfer, 0, sizeof(xfer)); @@ -759,11 +761,11 @@ /* Generate gimme messages for phantoms and leaf messages ** for all leaves. */ if( pullFlag || cloneFlag ){ - request_phantoms(&xfer); + request_phantoms(&xfer, mxPhantomReq); } if( pushFlag ){ send_unsent(&xfer); nMsg += send_unclustered(&xfer); } @@ -930,14 +932,15 @@ go = 0; /* If we received one or more files on the previous exchange but ** there are still phantoms, then go another round. */ - if( (xfer.nFileRcvd+xfer.nDeltaRcvd+xfer.nDanglingFile>0 || newPhantom) - && db_exists("SELECT 1 FROM phantom") - ){ + nFileRecv = xfer.nFileRcvd + xfer.nDeltaRcvd + xfer.nDanglingFile; + if( (nFileRecv>0 || newPhantom) && db_exists("SELECT 1 FROM phantom") ){ go = 1; + mxPhantomReq = nFileRecv*2; + if( mxPhantomReq<200 ) mxPhantomReq = 200; } nMsg = 0; xfer.nFileRcvd = 0; xfer.nDeltaRcvd = 0; xfer.nDanglingFile = 0;