GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.sqlite.org (truncated) — C/C++ Interface For SQLite Version 3 C-language Interface Specification for SQLiteThis page is intended to be a precise and detailed specification. For a tutorial introduction, see instead: This same content is also available split out into some smaller pages.Experimental And Deprecated InterfacesSQLite interfaces can be subdivided into three categories:
Stable interfaces will be maintained indefinitely in a backwards compatible way. An application that uses only stable interfaces should always be able to relink against a newer version of SQLite without any changes. Experimental interfaces are subject to change. Applications that use experimental interfaces may need to be modified when upgrading to a newer SQLite release, though this is rare. When new interfaces are added to SQLite, they generally begin as experimental interfaces. After an interface has been in use for a while and the developers are confident that the design of the interface is sound and worthy of long-term support, the interface is marked as stable. Deprecated interfaces have been superseded by better methods of accomplishing the same thing and should be avoided in new applications. Deprecated interfaces continue to be supported for the sake of backwards compatibility. At some point in the future, it is possible that deprecated interfaces may be removed. Key points:
List Of Objects:
List Of Constants:Also available: list of error codes
List Of Functions:Note: Functions marked with "(exp)"
are experimental and functions whose names are
Flags for sqlite3_serialize#define SQLITE_SERIALIZE_NOCOPY 0x001 /* Do no memory allocations */ Zero or more of the following constants can be OR-ed together for the F argument to sqlite3_serialize(D,S,P,F). SQLITE_SERIALIZE_NOCOPY means that sqlite3_serialize() will return a pointer to contiguous in-memory database that it is currently using, without making a copy of the database. If SQLite is not currently using a contiguous in-memory database, then this option causes sqlite3_serialize() to return a NULL pointer. SQLite will only be using a contiguous in-memory database if it has been initialized by a prior call to sqlite3_deserialize(). Flags for sqlite3_setlk_timeout()#define SQLITE_SETLK_BLOCK_ON_CONNECT 0x01 Maximum xShmLock index#define SQLITE_SHM_NLOCK 8 The xShmLock method on sqlite3_io_methods may use values between 0 and this upper bound as its "offset" argument. The SQLite core will never attempt to acquire or release a lock outside of this range Loadable Extension Thunktypedef struct sqlite3_api_routines sqlite3_api_routines; A pointer to the opaque sqlite3_api_routines structure is passed as the third parameter to entry points of loadable extensions. This structure must be typedefed in order to work around compiler warnings on some platforms. Online Backup Objecttypedef struct sqlite3_backup sqlite3_backup; The sqlite3_backup object records state information about an ongoing online backup operation. The sqlite3_backup object is created by a call to sqlite3_backup_init() and is destroyed by a call to sqlite3_backup_finish(). See Also: Using the SQLite Online Backup API SQL Function Context Objecttypedef struct sqlite3_context sqlite3_context; The context in which an SQL function executes is stored in an sqlite3_context object. A pointer to an sqlite3_context object is always the first parameter to application-defined SQL functions. The application-defined SQL function implementation will pass this pointer through into calls to sqlite3_result(), sqlite3_aggregate_context(), sqlite3_user_data(), sqlite3_context_db_handle(), sqlite3_get_auxdata(), and/or sqlite3_set_auxdata(). 26 Methods using this object:
Name Of The Folder Holding Database FilesSQLITE_EXTERN char *sqlite3_data_directory; If this global variable is made to point to a string which is the name of a folder (a.k.a. directory), then all database files specified with a relative pathname and created or accessed by SQLite when using a built-in windows VFS will be assumed to be relative to that directory. If this variable is a NULL pointer, then SQLite assumes that all database files specified with a relative pathname are relative to the current directory for the process. Only the windows VFS makes use of this global variable; it is ignored by the unix VFS. Changing the value of this variable while a database connection is open can result in a corrupt database. It is not safe to read or modify this variable in more than one thread at a time. It is not safe to read or modify this variable if a database connection is being used at the same time in a separate thread. It is intended that this variable be set once as part of process initialization and before any SQLite interface routines have been called and that this variable remain unchanged thereafter. The data_store_directory pragma may modify this variable and cause it to point to memory obtained from sqlite3_malloc. Furthermore, the data_store_directory pragma always assumes that any string that this variable points to is held in memory obtained from sqlite3_malloc and the pragma may attempt to free that memory using sqlite3_free. Hence, if this variable is modified directly, either it should be made NULL or made to point to memory obtained from sqlite3_malloc or else the use of the data_store_directory pragma should be avoided. 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. File Nametypedef const char *sqlite3_filename; Type sqlite3_filename is used by SQLite to pass filenames to the xOpen method of a VFS. It may be cast to (const char*) and treated as a normal, nul-terminated, UTF-8 buffer containing the filename, but may also be passed to special APIs such as:
Virtual Table Indexing Information
The sqlite3_index_info structure and its substructures is used as part of the virtual table interface to pass information into and receive the reply from the xBestIndex method of a virtual table 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 using one of the SQLITE_INDEX_CONSTRAINT_ values. 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 that are relevant 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 colUsed field indicates which columns of the virtual table may be required by the current scan. Virtual table columns are numbered from zero in the order in which they appear within the CREATE TABLE statement passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62), the corresponding bit is set within the colUsed mask if the column may be required by SQLite. If the table has at least 64 columns and any column to the right of the first 63 is required, then bit 63 of colUsed is also set. In other words, column iCol may be required if the expression (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to non-zero. 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 might not be checked again by the byte code. The aConstraintUsage[].omit flag is an optimization hint. When the omit flag is left in its default setting of false, the constraint will always be checked separately in byte code. If the omit flag is changed to true, then the constraint may or may not be checked in byte code. In other words, when the omit flag is true there is no guarantee that the constraint will not be checked again using byte code. The idxNum and idxStr values are recorded and passed into the xFilter method. sqlite3_free() is used to free idxStr if and only if needToFreeIdxStr is true. The orderByConsumed means that output from xFilter/xNext 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 a particular strategy. A cost of N indicates that the cost of the strategy is similar to a linear scan of an SQLite table with N rows. A cost of log(N) indicates that the expense of the operation is similar to that of a binary search on a unique indexed field of an SQLite table with N rows. The estimatedRows value is an estimate of the number of rows that will be returned by the strategy. The xBestIndex method may optionally populate the idxFlags field with a mask of SQLITE_INDEX_SCAN_* flags. One such flag is SQLITE_INDEX_SCAN_HEX, which if set causes the EXPLAIN QUERY PLAN output to show the idxNum as hex instead of as decimal. Another flag is SQLITE_INDEX_SCAN_UNIQUE, which if set indicates that the query plan will return at most one row. Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then SQLite also assumes that if a call to the xUpdate() method is made as part of the same statement to delete or update a virtual table row and the implementation returns SQLITE_CONSTRAINT, then there is no need to rollback any database changes. In other words, if the xUpdate() returns SQLITE_CONSTRAINT, the database contents must be exactly as they were before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by the xUpdate method are automatically rolled back by SQLite. IMPORTANT: The estimatedRows field was added to the sqlite3_index_info structure for SQLite version 3.8.2 (2013-12-06). If a virtual table extension is used with an SQLite version earlier than 3.8.2, the results of attempting to read or write the estimatedRows field are undefined (but are likely to include crashing the application). The estimatedRows field should therefore only be used if sqlite3_libversion_number() returns a value greater than or equal to 3008002. Similarly, the idxFlags field was added for version 3.9.0 (2015-10-14). It may therefore only be used if sqlite3_libversion_number() returns a value greater than or equal to 3009000. 3 Methods using this object: sqlite3_vtab_collation(), sqlite3_vtab_distinct(), sqlite3_vtab_rhs_value() OS Interface File Virtual Methods Object
Every file opened by the sqlite3_vfs.xOpen method populates an sqlite3_file object (or, more commonly, a subclass of the sqlite3_file object) with a pointer to an instance of this object. This object defines the methods used to perform various operations against the open file represented by the sqlite3_file object. If the sqlite3_vfs.xOpen method sets the sqlite3_file.pMethods element to a non-NULL pointer, then the sqlite3_io_methods.xClose method may be invoked even if the sqlite3_vfs.xOpen reported that it failed. The only way to prevent a call to xClose following a failed sqlite3_vfs.xOpen is for the sqlite3_vfs.xOpen to set the sqlite3_file.pMethods element to NULL. The flags argument to xSync may be one of SQLITE_SYNC_NORMAL or SQLITE_SYNC_FULL. The first choice is the normal fsync(). The second choice is a Mac OS X style fullsync. The SQLITE_SYNC_DATAONLY flag may be ORed in to indicate that only the data of the file and not its inode needs to be synced. The integer values to xLock() and xUnlock() are one of
The xFileControl() method is a generic interface that allows custom VFS implementations to directly control an open file using the sqlite3_file_control() interface. The second "op" argument is an integer opcode. The third argument is a generic pointer intended to point to a structure that may contain arguments or space in which to write return values. Potential uses for xFileControl() might be functions to enable blocking locks with timeouts, to change the locking strategy (for example to use dot-file locks), to inquire about the status of a lock, or to break stale locks. The SQLite core reserves all opcodes less than 100 for its own use. A list of opcodes less than 100 is available. Applications that define a custom xFileControl method should use opcodes greater than 100 to avoid conflicts. VFS implementations should return SQLITE_NOTFOUND for file control opcodes that they do not recognize. 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:
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(). If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill in the unread portions of the buffer with zeros. A VFS that fails to zero-fill short reads might seem to work. However, failure to zero-fill short reads will eventually lead to database corruption. Memory Allocation Routines
An instance of this object defines the interface between SQLite and low-level memory allocation routines. This object is used in only one place in the SQLite interface. A pointer to an instance of this object is the argument to sqlite3_config() when the configuration option is SQLITE_CONFIG_MALLOC or SQLITE_CONFIG_GETMALLOC. By creating an instance of this object and passing it to sqlite3_config(SQLITE_CONFIG_MALLOC) during configuration, an application can specify an alternative memory allocation subsystem for SQLite to use for all of its dynamic memory needs. Note that SQLite comes with several built-in memory allocators that are perfectly adequate for the overwhelming majority of applications and that this object is only useful to a tiny minority of applications with specialized memory allocation requirements. This object is also used during testing of SQLite in order to specify an alternative memory allocator that simulates memory out-of-memory conditions in order to verify that SQLite recovers gracefully from such conditions. The xMalloc, xRealloc, and xFree methods must work like the malloc(), realloc() and free() functions from the standard C library. SQLite guarantees that the second argument to xRealloc is always a value returned by a prior call to xRoundup. xSize should return the allocated size of a memory allocation previously obtained from xMalloc or xRealloc. The allocated size is always at least as big as the requested size but may be larger. The xRoundup method returns what would be the allocated size of a memory allocation given a particular requested size. Most memory allocators round up memory allocations at least to the next multiple of 8. Some allocators round up to a larger multiple or to a power of 2. Every memory allocation request coming in through sqlite3_malloc() or sqlite3_realloc() first calls xRoundup. If xRoundup returns 0, that causes the corresponding memory allocation to fail. The xInit method initializes the memory allocator. For example, it might allocate any required mutexes or initialize internal data structures. The xShutdown method is invoked (indirectly) by sqlite3_shutdown() and should deallocate any resources acquired by xInit. The pAppData pointer is used as the only parameter to xInit and xShutdown. SQLite holds the SQLITE_MUTEX_STATIC_MAIN mutex when it invokes the xInit method, so the xInit method need not be threadsafe. The xShutdown method is only called from sqlite3_shutdown() so it does not need to be threadsafe either. For all other methods, SQLite holds the SQLITE_MUTEX_STATIC_MEM mutex as long as the SQLITE_CONFIG_MEMSTATUS configuration option is turned on (which it is by default) and so the methods are automatically serialized. However, if SQLITE_CONFIG_MEMSTATUS is disabled, then the other methods must be threadsafe or else make their own arrangements for serialization. SQLite will never invoke xInit() more than once without an intervening call to xShutdown(). Mutex Handletypedef struct sqlite3_mutex sqlite3_mutex; 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(). Mutex Methods Object
An instance of this structure defines the low-level routines used to allocate and use mutexes. Usually, the default mutex implementations provided by SQLite are sufficient, however the application has the option of substituting a custom implementation for specialized deployments or systems for which SQLite does not provide a suitable implementation. In this case, the application creates and populates an instance of this structure to pass to sqlite3_config() along with the SQLITE_CONFIG_MUTEX option. Additionally, an instance of this structure can be used as an output variable when querying the system for the current mutex implementation, using the SQLITE_CONFIG_GETMUTEX option. The xMutexInit method defined by this structure is invoked as part of system initialization by the sqlite3_initialize() function. The xMutexInit routine is called by SQLite exactly once for each effective call to sqlite3_initialize(). The xMutexEnd method defined by this structure is invoked as part of system shutdown by the sqlite3_shutdown() function. The implementation of this method is expected to release all outstanding resources obtained by the mutex methods implementation, especially those obtained by the xMutexInit method. The xMutexEnd() interface is invoked exactly once for each call to sqlite3_shutdown(). The remaining seven methods defined by this structure (xMutexAlloc, xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and xMutexNotheld) implement the following interfaces (respectively):
The only difference is that the public sqlite3_XXX functions enumerated above silently ignore any invocations that pass a NULL pointer instead of a valid mutex handle. The implementations of the methods defined by this structure are not required to handle this case. The results of passing a NULL pointer instead of a valid mutex handle are undefined (i.e. it is acceptable to provide an implementation that segfaults if it is passed a NULL pointer). The xMutexInit() method must be threadsafe. It must be harmless to invoke xMutexInit() multiple times within the same process and without intervening calls to xMutexEnd(). Second and subsequent calls to xMutexInit() must be no-ops. xMutexInit() must not use SQLite memory allocation (sqlite3_malloc() and its associates). Similarly, xMutexAlloc() must not use SQLite memory allocation for a static mutex. However xMutexAlloc() may use SQLite memory allocation for a fast or recursive mutex. SQLite will invoke the xMutexEnd() method when sqlite3_shutdown() is called, but only if the prior call to xMutexInit returned SQLITE_OK. If xMutexInit fails in any way, it is expected to clean up after itself prior to returning. Custom Page Cache Objecttypedef struct sqlite3_pcache sqlite3_pcache; The sqlite3_pcache type is opaque. It is implemented by the pluggable module. The SQLite core has no knowledge of its size or internal structure and never deals with the sqlite3_pcache object except by holding and passing pointers to the object. See sqlite3_pcache_methods2 for additional information. Custom Page Cache Object
The sqlite3_pcache_page object represents a single page in the page cache. The page cache will allocate instances of this object. Various methods of the page cache use pointers to instances of this object as parameters or as their return value. See sqlite3_pcache_methods2 for additional information. Name Of The Folder Holding Temporary FilesSQLITE_EXTERN char *sqlite3_temp_directory; If this global variable is made to point to a string which is the name of a folder (a.k.a. directory), then all temporary files created by SQLite when using a built-in VFS will be placed in that directory. If this variable is a NULL pointer, then SQLite performs a search for an appropriate temporary file directory. Applications are strongly discouraged from using this global variable. It is required to set a temporary folder on Windows Runtime (WinRT). But for all other platforms, it is highly recommended that applications neither read nor write this variable. This global variable is a relic that exists for backwards compatibility of legacy applications and should be avoided in new projects. It is not safe to read or modify this variable in more than one thread at a time. It is not safe to read or modify this variable if a database connection is being used at the same time in a separate thread. It is intended that this variable be set once as part of process initialization and before any SQLite interface routines have been called and that this variable remain unchanged thereafter. The temp_store_directory pragma may modify this variable and cause it to point to memory obtained from sqlite3_malloc. Furthermore, the temp_store_directory pragma always assumes that any string that this variable points to is held in memory obtained from sqlite3_malloc and the pragma may attempt to free that memory using sqlite3_free. Hence, if this variable is modified directly, either it should be made NULL or made to point to memory obtained from sqlite3_malloc or else the use of the temp_store_directory pragma should be avoided. Except when requested by the temp_store_directory pragma, SQLite does not free the memory that sqlite3_temp_directory points to. If the application wants that memory to be freed, it must do so itself, taking care to only do so after all database connection objects have been destroyed. Note to Windows Runtime users: The temporary directory must be set prior to calling sqlite3_open or sqlite3_open_v2. Otherwise, various features that require the use of temporary files may fail. Here is an example of how to do this using C++ with the Windows Runtime:
OS Interface Object
An instance of the sqlite3_vfs 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". See the VFS documentation for further information. The VFS interface is sometimes extended by adding new methods onto the end. Each time such an extension occurs, the iVersion field is incremented. The iVersion value started out as 1 in SQLite version 3.5.0 on 2007-09-04, then increased to 2 with SQLite version 3.7.0 on 2010-07-21, and then increased to 3 with SQLite version 3.7.6 on 2011-04-12. Additional fields may be appended to the sqlite3_vfs object and the iVersion value may increase again in future versions of SQLite. Note that due to an oversight, the structure of the sqlite3_vfs object changed in the transition from SQLite version 3.5.9 to version 3.6.0 on 2008-07-16 and yet the iVersion field was not increased. The szOsFile field is the size of the subclassed sqlite3_file structure used by this VFS. mxPathname is the maximum length of a pathname in this VFS. Registered sqlite3_vfs objects are kept on a linked list formed by the pNext pointer. The sqlite3_vfs_register() and sqlite3_vfs_unregister() interfaces manage this list in a thread-safe way. The sqlite3_vfs_find() interface searches the list. Neither the application code nor the VFS implementation should use the pNext pointer. The pNext field is the only field 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 guarantees that the zFilename parameter to xOpen is either a NULL pointer or string obtained from xFullPathname() with an optional suffix added. If a suffix is added to the zFilename parameter, it will consist of a single "-" character followed by no more than 11 alphanumeric and/or "-" characters. SQLite further guarantees that the string will be valid and unchanged until xClose() is called. Because of the previous sentence, the sqlite3_file can safely store a pointer to the filename if it needs to remember the filename for some reason. If the zFilename parameter to xOpen is a NULL pointer then xOpen must invent its own temporary name for the file. Whenever the xFilename parameter is NULL it will also be the case that the flags parameter will include SQLITE_OPEN_DELETEONCLOSE. 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. 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:
The file I/O implementation can use the object type flags to change the way it deals with files. For example, an application that does not care about crash recovery or rollback might make the open of a journal file a no-op. Writes to this journal would also be no-ops, and any attempt to read the journal would return SQLITE_IOERR. Or the implementation might recognize that a database file will be doing page-aligned sector reads and writes in a random order and set up its I/O subsystem accordingly. SQLite might also add one of the following flags to the xOpen method: The SQLITE_OPEN_DELETEONCLOSE flag means the file should be deleted when it is closed. The SQLITE_OPEN_DELETEONCLOSE will be set for TEMP databases and their journals, transient databases, and subjournals. The SQLITE_OPEN_EXCLUSIVE flag is always used in conjunction with the SQLITE_OPEN_CREATE flag, which are both directly analogous to the O_EXCL and O_CREAT flags of the POSIX open() API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the SQLITE_OPEN_CREATE, is used to indicate that file should always be created, and that it is an error if it already exists. It is not used to indicate the file should be opened for exclusive access. At least szOsFile bytes of memory are allocated by SQLite to hold the sqlite3_file structure passed as the third argument to xOpen. The xOpen method does not have to allocate the structure; it should just fill it in. Note that the xOpen method must set the sqlite3_file.pMethods to either a valid sqlite3_io_methods object or to NULL. xOpen must do this even if the open fails. SQLite expects that the sqlite3_file.pMethods element will be valid after xOpen returns regardless of the success or failure of the xOpen call. The flags argument to xAccess() may be SQLITE_ACCESS_EXISTS to test for the existence of a file, or SQLITE_ACCESS_READWRITE to test whether a file is readable and writable, or SQLITE_ACCESS_READ to test whether a file is at least readable. The SQLITE_ACCESS_READ flag is never actually used and is not implemented in the built-in VFSes of SQLite. The file is named by the second argument and can be a directory. The xAccess method returns SQLITE_OK on success or some non-zero error code if there is an I/O error or if the name of the file given in the second argument is illegal. If SQLITE_OK is returned, then non-zero or zero is written into *pResOut to indicate whether or not the file is accessible. SQLite will always allocate at least mxPathname+1 bytes for the output buffer 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. Since this is handled as a fatal error by SQLite, vfs implementations should endeavor to prevent this by setting mxPathname to a sufficiently large value. The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64() interfaces are not strictly a part of the filesystem, but they are included in the VFS structure for completeness. The xRandomness() function attempts to return nBytes bytes of good-quality randomness into zOut. The return value is the actual number of bytes of randomness obtained. The xSleep() method causes the calling thread to sleep for at least the number of microseconds given. The xCurrentTime() method returns a Julian Day Number for the current date and time as a floating point value. The xCurrentTimeInt64() method returns, as an integer, the Julian Day Number multiplied by 86400000 (the number of milliseconds in a 24-hour day). SQLite will use the xCurrentTimeInt64() method to get the current date and time if that method is available (if iVersion is 2 or greater and the function pointer is not NULL) and will fall back to xCurrentTime() if xCurrentTimeInt64() is unavailable. The xSetSystemCall(), xGetSystemCall(), and xNextSystemCall() interfaces are not used by the SQLite core. These optional interfaces are provided by some VFSes to facilitate testing of the VFS code. By overriding system calls with functions under its control, a test program can simulate faults and error conditions that would otherwise be difficult or impossible to induce. The set of system calls that can be overridden varies from one VFS to another, and from one version of the same VFS to the next. Applications that use these interfaces must be prepared for any or all of these interfaces to be NULL or for their behavior to change from one release to the next. Applications must not attempt to access any of these methods if the iVersion of the VFS is less than 3. Virtual Table Instance Object
Every virtual table module implementation uses a subclass of this object to describe a particular instance of the virtual table. 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. Obtain Aggregate Function Contextvoid *sqlite3_aggregate_context(sqlite3_context*, int nBytes); Implementations of aggregate SQL functions use this routine to allocate memory for storing their state. The first time the sqlite3_aggregate_context(C,N) routine is called for a particular aggregate function, SQLite allocates N bytes of memory, zeroes out that memory, and returns a pointer to the new memory. On second and subsequent calls to sqlite3_aggregate_context() for the same aggregate function instance, the same buffer is returned. Sqlite3_aggregate_context() is normally called once for each invocation of the xStep callback and then one last time when the xFinal callback is invoked. When no rows match an aggregate query, the xStep() callback of the aggregate function implementation is never called and xFinal() is called exactly once. In those cases, sqlite3_aggregate_context() might be called for the first time from within xFinal(). The sqlite3_aggregate_context(C,N) routine returns a NULL pointer when first called if N is less than or equal to zero or if a memory allocation error occurs. The amount of space allocated by sqlite3_aggregate_context(C,N) is determined by the N parameter on the first successful call. Changing the value of N in any subsequent call to sqlite3_aggregate_context() within the same aggregate function instance will not resize the memory allocation. Within the xFinal callback, it is customary to set N=0 in calls to sqlite3_aggregate_context(C,N) so that no pointless memory allocations occur. SQLite automatically frees the memory allocated by sqlite3_aggregate_context() when the aggregate query concludes. The first parameter must be a copy of the SQL function context that is the first parameter to the xStep or xFinal callback routine that implements the aggregate function. This routine must be called from the same thread in which the aggregate SQL function is running. Automatically Load Statically Linked Extensionsint sqlite3_auto_extension(void(*xEntryPoint)(void)); This interface causes the xEntryPoint() function to be invoked for each new database connection that is created. The idea here is that xEntryPoint() is the entry point for a statically linked SQLite extension that is to be automatically loaded into all new database connections. Even though the function prototype shows that xEntryPoint() takes no arguments and returns void, SQLite invokes xEntryPoint() with three arguments and expects an integer result as if the signature of the entry point were as follows: int xEntryPoint( sqlite3 *db, char **pzErrMsg, const struct sqlite3_api_routines *pThunk ); If the xEntryPoint routine encounters an error, it should make *pzErrMsg point to an appropriate error message (obtained from sqlite3_mprintf()) and return an appropriate error code. SQLite ensures that *pzErrMsg is NULL before calling the xEntryPoint(). SQLite will invoke sqlite3_free() on *pzErrMsg after xEntryPoint() returns. If any xEntryPoint() returns an error, the sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2() call that provoked the xEntryPoint() will fail. Calling sqlite3_auto_extension(X) with an entry point X that is already on the list of automatic extensions is a harmless no-op. No entry point will be called more than once for each database connection that is opened. See also: sqlite3_reset_auto_extension() and sqlite3_cancel_auto_extension() Autovacuum Compaction Amount Callbackint sqlite3_autovacuum_pages( sqlite3 *db, unsigned int(*)(void*,const char*,unsigned int,unsigned int,unsigned int), void*, void(*)(void*) ); The sqlite3_autovacuum_pages(D,C,P,X) interface registers a callback function C that is invoked prior to each autovacuum of the database file. The callback is passed a copy of the generic data pointer (P), the schema-name of the attached database that is being autovacuumed, the size of the database file in pages, the number of free pages, and the number of bytes per page, respectively. The callback should return the number of free pages that should be removed by the autovacuum. If the callback returns zero, then no autovacuum happens. If the value returned is greater than or equal to the number of free pages, then a complete autovacuum happens. If there are multiple ATTACH-ed database files that are being modified as part of a transaction commit, then the autovacuum pages callback is invoked separately for each file. The callback is not reentrant. The callback function should not attempt to invoke any other SQLite interface. If it does, bad things may happen, including segmentation faults and corrupt database files. The callback function should be a simple function that does some arithmetic on its input parameters and returns a result. The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional destructor for the P parameter. If X is not NULL, then X(P) is invoked whenever the database connection closes or when the callback is overwritten by another invocation of sqlite3_autovacuum_pages(). There is only one autovacuum pages callback per database connection. Each call to the sqlite3_autovacuum_pages() interface overrides all previous invocations for that database connection. If the callback argument (C) to sqlite3_autovacuum_pages(D,C,P,X) is a NULL pointer, then the autovacuum steps callback is canceled. The return value from sqlite3_autovacuum_pages() is normally SQLITE_OK, but might be some other error code if something goes wrong. The current implementation will only return SQLITE_OK or SQLITE_MISUSE, but other return codes might be added in future releases. If no autovacuum pages callback is specified (the usual case) or a NULL pointer is provided for the callback, then the default behavior is to vacuum all free pages. So, in other words, the default behavior is the same as if the callback function were something like this:
Number Of SQL Parametersint sqlite3_bind_parameter_count(sqlite3_stmt*); This routine can be used to find the number of SQL parameters in a prepared statement. SQL parameters are tokens of the form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as placeholders for values that are bound to the parameters at a later time. This routine actually returns the index of the largest (rightmost) parameter. For all forms except ?NNN, this will correspond to the number of unique parameters. If parameters of the ?NNN form are used, there may be gaps in the list. See also: sqlite3_bind(), sqlite3_bind_parameter_name(), and sqlite3_bind_parameter_index(). Index Of A Parameter With A Given Nameint sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName); 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(). 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() or sqlite3_prepare16_v3(). See also: sqlite3_bind(), sqlite3_bind_parameter_count(), and sqlite3_bind_parameter_name(). Name Of A Host Parameterconst char *sqlite3_bind_parameter_name(sqlite3_stmt*, int); The sqlite3_bind_parameter_name(P,N) interface returns the name of the N-th SQL parameter in the prepared statement P. SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" respectively. In other words, the initial ":" or "$" or "@" or "?" is included as part of the name. Parameters of the form "?" without a following integer have no name and are referred to as "nameless" or "anonymous parameters". The first host parameter has an index of 1, not 0. If the value N is out of range or if the N-th parameter is nameless, then NULL is returned. The returned string is always in UTF-8 encoding even if the named parameter was originally specified as UTF-16 in sqlite3_prepare16(), sqlite3_prepare16_v2(), or sqlite3_prepare16_v3(). See also: sqlite3_bind(), sqlite3_bind_parameter_count(), and sqlite3_bind_parameter_index(). Return The Size Of An Open BLOBint sqlite3_blob_bytes(sqlite3_blob *); Returns the size in bytes of the BLOB accessible via the successfully opened BLOB handle in its only argument. The incremental blob I/O routines can only read or overwrite existing blob content; they cannot change the size of a blob. This routine only works on a BLOB handle which has been created by a prior successful call to sqlite3_blob_open() and which has not been closed by sqlite3_blob_close(). Passing any other pointer in to this routine results in undefined and probably undesirable behavior. Close A BLOB Handleint sqlite3_blob_close(sqlite3_blob *); This function closes an open BLOB handle. The BLOB handle is closed unconditionally. Even if this routine returns an error code, the handle is still closed. If the blob handle being closed was opened for read-write access, and if the database is in auto-commit mode and there are no other open read-write blob handles or active write statements, the current transaction is committed. If an error occurs while committing the transaction, an error code is returned and the transaction rolled back. Calling this function with an argument that is not a NULL pointer or an open blob handle results in undefined behavior. Calling this routine with a null pointer (such as would be returned by a failed call to sqlite3_blob_open()) is a harmless no-op. Otherwise, if this function is passed a valid open blob handle, the values returned by the sqlite3_errcode() and sqlite3_errmsg() functions are set before returning. Open A BLOB For Incremental I/Oint sqlite3_blob_open( sqlite3*, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob ); This interfaces opens a handle to the BLOB located in row iRow, column zColumn, table zTable in database zDb; in other words, the same BLOB that would be selected by: SELECT zColumn FROM zDb.zTable WHERE rowid = iRow; Parameter zDb is not the filename that contains the database, but rather the symbolic name of the database. For attached databases, this is the name that appears after the AS keyword in the ATTACH statement. For the main database file, the database name is "main". For TEMP tables, the database name is "temp". If the flags parameter is non-zero, then the BLOB is opened for read and write access. If the flags parameter is zero, the BLOB is opened for read-only access. On success, SQLITE_OK is returned and the new BLOB handle is stored in *ppBlob. Otherwise an error code is returned and, unless the error code is SQLITE_MISUSE, *ppBlob is set to NULL. This means that, provided the API is not misused, it is always safe to call sqlite3_blob_close() on *ppBlob after this function returns. This function fails with SQLITE_ERROR if any of the following are true:
Unless it returns SQLITE_MISUSE, this function sets the database connection error code and message accessible via sqlite3_errcode() and sqlite3_errmsg() and related functions. A BLOB referenced by sqlite3_blob_open() may be read using the sqlite3_blob_read() interface and modified by using sqlite3_blob_write(). The BLOB handle can be moved to a different row of the same table using the sqlite3_blob_reopen() interface. However, the column, table, or database of a BLOB handle cannot be changed after the BLOB handle is opened. If the row that a BLOB handle points to is modified by an UPDATE, DELETE, or by ON CONFLICT side-effects then the BLOB handle is marked as "expired". This is true if any column of the row is changed, even a column other than the one the BLOB handle is open on. Calls to sqlite3_blob_read() and sqlite3_blob_write() for an expired BLOB handle fail with a return code of SQLITE_ABORT. Changes written into a BLOB prior to the BLOB expiring are not rolled back by the expiration of the BLOB. Such changes will eventually commit if the transaction continues to completion. Use the sqlite3_blob_bytes() interface to determine the size of the opened blob. The size of a blob may not be changed by this interface. Use the UPDATE SQL command to change the size of a blob. The sqlite3_bind_zeroblob() and sqlite3_result_zeroblob() interfaces and the built-in zeroblob SQL function may be used to create a zero-filled blob to read or write using the incremental-blob interface. To avoid a resource leak, every open BLOB handle should eventually be released by a call to sqlite3_blob_close(). See also: sqlite3_blob_close(), sqlite3_blob_reopen(), sqlite3_blob_read(), sqlite3_blob_bytes(), sqlite3_blob_write(). Read Data From A BLOB Incrementallyint sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset); This function is used to read data from an open BLOB handle into a caller-supplied buffer. N bytes of data are copied into buffer Z from the open BLOB, starting at offset iOffset. If offset iOffset is less than N bytes from the end of the BLOB, SQLITE_ERROR is returned and no data is read. If N or iOffset is less than zero, SQLITE_ERROR is returned and no data is read. The size of the blob (and hence the maximum value of N+iOffset) can be determined using the sqlite3_blob_bytes() interface. An attempt to read from an expired BLOB handle fails with an error code of SQLITE_ABORT. On success, sqlite3_blob_read() returns SQLITE_OK. Otherwise, an error code or an extended error code is returned. This routine only works on a BLOB handle which has been created by a prior successful call to sqlite3_blob_open() and which has not been closed by sqlite3_blob_close(). Passing any other pointer in to this routine results in undefined and probably undesirable behavior. See also: sqlite3_blob_write(). Move a BLOB Handle to a New Rowint sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64); This function is used to move an existing BLOB handle so that it points to a different row of the same database table. The new row is identified by the rowid value passed as the second argument. Only the row can be changed. The database, table and column on which the blob handle is open remain the same. Moving an existing BLOB handle to a new row is faster than closing the existing handle and opening a new one. The new row must meet the same criteria as for sqlite3_blob_open() - it must exist and there must be either a blob or text value stored in the nominated column. If the new row is not present in the table, or if it does not contain a blob or text value, or if another error occurs, an SQLite error code is returned and the blob handle is considered aborted. All subsequent calls to sqlite3_blob_read(), sqlite3_blob_write() or sqlite3_blob_reopen() on an aborted blob handle immediately return SQLITE_ABORT. Calling sqlite3_blob_bytes() on an aborted blob handle always returns zero. This function sets the database handle error code and message. Write Data Into A BLOB Incrementallyint sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset); This function is used to write data into an open BLOB handle from a caller-supplied buffer. N bytes of data are copied from the buffer Z into the open BLOB, starting at offset iOffset. On success, sqlite3_blob_write() returns SQLITE_OK. Otherwise, an error code or an extended error code is returned. Unless SQLITE_MISUSE is returned, this function sets the database connection error code and message accessible via sqlite3_errcode() and sqlite3_errmsg() and related functions. If the BLOB handle passed as the first argument was not opened for writing (the flags parameter to sqlite3_blob_open() was zero), this function returns SQLITE_READONLY. 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. The size of the BLOB (and hence the maximum value of N+iOffset) can be determined using the sqlite3_blob_bytes() interface. If N or iOffset are less than zero SQLITE_ERROR is returned and no data is written. An attempt to write to an expired BLOB handle fails with an error code of SQLITE_ABORT. Writes to the BLOB that occurred before the BLOB handle expired are not rolled back by the expiration of the handle, though of course those changes might have been overwritten by the statement that expired the BLOB handle or by other independent statements. This routine only works on a BLOB handle which has been created by a prior successful call to sqlite3_blob_open() and which has not been closed by sqlite3_blob_close(). Passing any other pointer in to this routine results in undefined and probably undesirable behavior. See also: sqlite3_blob_read(). Set A Busy Timeoutint sqlite3_busy_timeout(sqlite3*, int ms); This routine sets a busy handler that sleeps for a specified amount of time when a table is locked. The handler will sleep multiple times until at least "ms" milliseconds of sleeping have accumulated. After at least "ms" milliseconds of sleeping, the handler returns 0 which causes sqlite3_step() to return SQLITE_BUSY. 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 at any given moment. If another busy handler was defined (using sqlite3_busy_handler()) prior to calling this routine, that other busy handler is cleared. See also: PRAGMA busy_timeout Cancel Automatic Extension Loadingint sqlite3_cancel_auto_extension(void(*xEntryPoint)(void)); The sqlite3_cancel_auto_extension(X) interface unregisters the initialization routine X that was registered using a prior call to sqlite3_auto_extension(X). The sqlite3_cancel_auto_extension(X) routine returns 1 if initialization routine X was successfully unregistered and it returns 0 if X was not on the list of initialization routines. Reset All Bindings On A Prepared Statementint sqlite3_clear_bindings(sqlite3_stmt*); Contrary to the intuition of many, sqlite3_reset() does not reset the bindings on a prepared statement. Use this routine to reset all host parameters to NULL. Number Of Columns In A Result Setint sqlite3_column_count(sqlite3_stmt *pStmt); Return the number of columns in the result set returned by the prepared statement. If this routine returns 0, that means the prepared statement returns no data (for example an UPDATE). However, just because this routine returns a positive number does not mean that one or more rows of data will be returned. A SELECT statement will always have a positive sqlite3_column_count() but depending on the WHERE clause constraints and the table content, it might return no rows. See also: sqlite3_data_count() Configuring The SQLite Libraryint sqlite3_config(int, ...); The sqlite3_config() interface is used to make global configuration changes to SQLite in order to tune SQLite to the specific needs of the application. The default configuration is recommended for most applications and so this routine is usually not necessary. It is provided to support rare applications with unusual needs. The sqlite3_config() interface is not threadsafe. The application must ensure that no other SQLite interfaces are invoked by other threads while sqlite3_config() is running. The first argument to sqlite3_config() is an integer configuration option that determines what property of SQLite is to be configured. Subsequent arguments vary depending on the configuration option in the first argument. For most configuration options, the sqlite3_config() interface may only be invoked prior to library initialization using sqlite3_initialize() or after shutdown by sqlite3_shutdown(). The exceptional configuration options that may be invoked at any time are called "anytime configuration options". If sqlite3_config() is called after sqlite3_initialize() and before sqlite3_shutdown() with a first argument that is not an anytime configuration option, then the sqlite3_config() call will return SQLITE_MISUSE. Note, however, that sqlite3_config() can be called as part of the implementation of an application-defined sqlite3_os_init(). When a configuration option is set, sqlite3_config() returns SQLITE_OK. If the option is unknown or SQLite is unable to set the option then this routine returns a non-zero error code. Database Connection For Functionssqlite3 *sqlite3_context_db_handle(sqlite3_context*); The sqlite3_context_db_handle() interface returns a copy of the pointer to the database connection (the 1st parameter) of the sqlite3_create_function() and sqlite3_create_function16() routines that originally registered the application defined function. Number of columns in a result setint sqlite3_data_count(sqlite3_stmt *pStmt); The sqlite3_data_count(P) interface returns the number of columns in the current row of the result set of prepared statement P. If prepared statement P does not have results ready to return (via calls to the sqlite3_column() family of interfaces) then sqlite3_data_count(P) returns 0. The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer. The sqlite3_data_count(P) routine returns 0 if the previous call to sqlite3_step(P) returned SQLITE_DONE. The sqlite3_data_count(P) will return non-zero if previous call to sqlite3_step(P) returned SQLITE_ROW, except in the case of the PRAGMA incremental_vacuum where it always returns zero since each step of that multi-step pragma returns 0 columns of data. See also: sqlite3_column_count() Database File Corresponding To A Journalsqlite3_file *sqlite3_database_file_object(const char*); If X is the name of a rollback or WAL-mode journal file that is passed into the xOpen method of sqlite3_vfs, then sqlite3_database_file_object(X) returns a pointer to the sqlite3_file object that represents the main database file. This routine is intended for use in custom VFS implementations only. It is not a general-purpose interface. The argument sqlite3_file_object(X) must be a filename pointer that has been passed into sqlite3_vfs.xOpen method where the flags parameter to xOpen contains one of the bits SQLITE_OPEN_MAIN_JOURNAL or SQLITE_OPEN_WAL. Any other use of this routine results in undefined and probably undesirable behavior. Flush caches to disk mid-transactionint sqlite3_db_cacheflush(sqlite3*); If a write-transaction is open on database connection D when the sqlite3_db_cacheflush(D) interface is invoked, any dirty pages in the pager-cache that are not currently in use are written out to disk. A dirty page may be in use if a database cursor created by an active SQL statement is reading from it, or if it is page 1 of a database file (page 1 is always "in use"). The sqlite3_db_cacheflush(D) interface flushes caches for all schemas - "main", "temp", and any attached databases. If this function needs to obtain extra database locks before dirty pages can be flushed to disk, it does so. If those locks cannot be obtained immediately and there is a busy-handler callback configured, it is invoked in the usual manner. If the required lock still cannot be obtained, then the database is skipped and an attempt made to flush any dirty pages belonging to the next (if any) database. If any databases are skipped because locks cannot be obtained, but no other error occurs, this function returns SQLITE_BUSY. If any other error occurs while flushing dirty pages to disk (for example an IO error or out-of-memory condition), then processing is abandoned and an SQLite error code is returned to the caller immediately. Otherwise, if no error occurs, sqlite3_db_cacheflush() returns SQLITE_OK. This function does not set the database handle error code or message returned by the sqlite3_errcode() and sqlite3_errmsg() functions. Configure database connectionsint sqlite3_db_config(sqlite3*, int op, ...); The sqlite3_db_config() interface is used to make configuration changes to a database connection. The interface is similar to sqlite3_config() except that the changes apply to a single database connection (specified in the first argument). The second argument to sqlite3_db_config(D,V,...) is the configuration verb - an integer code that indicates what aspect of the database connection is being configured. Subsequent arguments vary depending on the configuration verb. Calls to sqlite3_db_config() return SQLITE_OK if and only if the call is considered successful. Return The Filename For A Database Connectionsqlite3_filename sqlite3_db_filename(sqlite3 *db, const char *zDbName); The sqlite3_db_filename(D,N) interface returns a pointer to the filename associated with database N of connection D. If there is no attached database N on the database connection D, or if database N is a temporary or in-memory database, then this function will return either a NULL pointer or an empty string. The string value returned by this routine is owned and managed by the database connection. The value will be valid until the database N is DETACH-ed or until the database connection closes. The filename returned by this function is the output of the xFullPathname method of the VFS. In other words, the filename will be an absolute pathname, even if the filename used to open the database originally was a URI or relative pathname. If the filename pointer returned by this routine is not NULL, then it can be used as the filename input parameter to these routines:
Find The Database Handle Of A Prepared Statementsqlite3 *sqlite3_db_handle(sqlite3_stmt*); The sqlite3_db_handle interface returns the database connection handle to which a prepared statement belongs. The database connection returned by sqlite3_db_handle is the same database connection that was the first argument to the sqlite3_prepare_v2() call (or its variants) that was used to create the statement in the first place. Retrieve the mutex for a database connectionsqlite3_mutex *sqlite3_db_mutex(sqlite3*); This interface returns a pointer to the sqlite3_mutex object that serializes access to the database connection given in the argument when the threading mode is Serialized. If the threading mode is Single-thread or Multi-thread then this routine returns a NULL pointer. Return The Schema Name For A Database Connectionconst char *sqlite3_db_name(sqlite3 *db, int N); The sqlite3_db_name(D,N) interface returns a pointer to the schema name for the N-th database on database connection D, or a NULL pointer if N is out of range. An N value of 0 means the main database file. An N of 1 is the "temp" schema. Larger values of N correspond to various ATTACH-ed databases. Space to hold the string that is returned by sqlite3_db_name() is managed by SQLite itself. The string might be deallocated by any operation that changes the schema, including ATTACH or DETACH or calls to sqlite3_serialize() or sqlite3_deserialize(), even operations that occur on a different thread. Applications that need to remember the string long-term should make their own copy. Applications that are accessing the same database connection simultaneously on multiple threads should mutex-protect calls to this API and should make their own private copy of the result prior to releasing the mutex. Determine if a database is read-onlyint sqlite3_db_readonly(sqlite3 *db, const char *zDbName); The sqlite3_db_readonly(D,N) interface returns 1 if the database N of connection D is read-only, 0 if it is read/write, or -1 if N is not the name of a database on connection D. Free Memory Used By A Database Connectionint sqlite3_db_release_memory(sqlite3*); The sqlite3_db_release_memory(D) interface attempts to free as much heap memory as possible from database connection D. Unlike the sqlite3_release_memory() interface, this interface is in effect even when the SQLITE_ENABLE_MEMORY_MANAGEMENT compile-time option is omitted. See also: sqlite3_release_memory() Declare The Schema Of A Virtual Tableint sqlite3_declare_vtab(sqlite3*, const char *zSQL); The xCreate and xConnect methods of a virtual table module call this interface to declare the format (the names and datatypes of the columns) of the virtual tables they implement. Deserialize a databaseint sqlite3_deserialize( sqlite3 *db, /* The database connection */ const char *zSchema, /* Which DB to reopen with the deserialization */ unsigned char *pData, /* The serialized database content */ sqlite3_int64 szDb, /* Number of bytes in the deserialization */ sqlite3_int64 szBuf, /* Total size of buffer pData[] */ unsigned mFlags /* Zero or more SQLITE_DESERIALIZE_* flags */ ); The sqlite3_deserialize(D,S,P,N,M,F) interface causes the database connection D to disconnect from database S and then reopen S as an in-memory database based on the serialization contained in P. If S is a NULL pointer, the main database is used. The serialized database P is N bytes in size. M is the size of the buffer P, which might be larger than N. If M is larger than N, and the SQLITE_DESERIALIZE_READONLY bit is not set in F, then SQLite is permitted to add content to the in-memory database, in page-sized chunks, as long as the total size does not exceed M bytes. The parameter M must be greater than or equal to N. Ideally, M should have a value which is N+(512×K)+20 where K determines how must extra space is available to hold new content as the database grows. K can be 0 if the database is read-only. If the database content in P is malformed in a malicious way then it is possible that SQLite might try to read a few more than N bytes from P. If the veracity of the database content P is uncertain, then applications are advised to allocate about 20 extra bytes on the end of the P buffer to avoid a memory error. If the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in F, then SQLite will invoke sqlite3_free() on the serialization buffer when the database connection closes. If the SQLITE_DESERIALIZE_RESIZEABLE bit is set, then SQLite will try to increase the buffer size using sqlite3_realloc64() if writes on the database cause it to grow larger than M bytes. Applications must not modify the buffer P or invalidate it before the database connection D is closed. The sqlite3_deserialize() interface will fail with SQLITE_BUSY if the database is currently in a read transaction or is involved in a backup operation. It is not possible to deserialize into the TEMP database. If the S argument to sqlite3_deserialize(D,S,P,N,M,F) is "temp" then the function returns SQLITE_ERROR. The deserialized database should not be in WAL mode. If the database is in WAL mode, then any attempt to use the database file will result in an SQLITE_CANTOPEN error. The application can set the file format version numbers (bytes 18 and 19) of the input database P to 0x01 prior to invoking sqlite3_deserialize(D,S,P,N,M,F) to force the database file into rollback mode and work around this limitation. If sqlite3_deserialize(D,S,P,N,M,F) fails for any reason and if the SQLITE_DESERIALIZE_FREEONCLOSE bit is set in argument F, then sqlite3_free() is invoked on argument P prior to returning. This interface is omitted if SQLite is compiled with the SQLITE_OMIT_DESERIALIZE option. Remove Unnecessary Virtual Table Implementationsint sqlite3_drop_modules( sqlite3 *db, /* Remove modules from this connection */ const char **azKeep /* Except, do not remove the ones named here */ ); The sqlite3_drop_modules(D,L) interface removes all virtual table modules from database connection D except those named on list L. The L parameter must be either NULL or a pointer to an array of pointers to strings where the array is terminated by a single NULL pointer. If the L parameter is NULL, then all virtual table modules are removed. See also: sqlite3_create_module() Enable Or Disable Extension Loadingint sqlite3_enable_load_extension(sqlite3 *db, int onoff); So as not to open security holes in older applications that are unprepared to deal with extension loading, and as a means of disabling extension loading while evaluating user-entered SQL, the following API is provided to turn the sqlite3_load_extension() mechanism on and off. Extension loading is off by default. 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. This interface enables or disables both the C-API sqlite3_load_extension() and the SQL function load_extension(). Use sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,..) to enable or disable only the C-API. Security warning: It is recommended that extension loading be enabled using the SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION method rather than this interface, so the load_extension() SQL function remains disabled. This will prevent SQL injections from giving attackers access to extension loading capabilities. Enable Or Disable Shared Pager Cacheint sqlite3_enable_shared_cache(int); 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. This interface is omitted if SQLite is compiled with -DSQLITE_OMIT_SHARED_CACHE. The -DSQLITE_OMIT_SHARED_CACHE compile-time option is recommended because the use of shared cache mode is discouraged. Cache sharing is enabled and disabled for an entire process. This is a change as of SQLite version 3.5.0 (2007-09-04). 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 to use the sharing mode that was in effect at the time they were opened. This routine returns SQLITE_OK if shared cache was enabled or disabled successfully. An error code is returned otherwise. Shared cache is disabled by default. It is recommended that it stay that way. In other words, do not use this routine. This interface continues to be provided for historical compatibility, but its use is discouraged. Any use of shared cache is discouraged. If shared cache must be used, it is recommended that shared cache only be enabled for individual database connections using the sqlite3_open_v2() interface with the SQLITE_OPEN_SHAREDCACHE flag. Note: This method is disabled on MacOS X 10.7 and iOS version 5.0 and will always return SQLITE_MISUSE. On those systems, shared cache mode should be enabled per-database connection via sqlite3_open_v2() with SQLITE_OPEN_SHAREDCACHE. This interface is threadsafe on processors where writing a 32-bit integer is atomic. See Also: SQLite Shared-Cache Mode One-Step Query Execution Interfaceint sqlite3_exec( sqlite3*, /* An open database */ const char *sql, /* SQL to be evaluated */ int (*callback)(void*,int,char**,char**), /* Callback function */ void *, /* 1st argument to callback */ char **errmsg /* Error msg written here */ ); The sqlite3_exec() interface is a convenience wrapper around sqlite3_prepare_v2(), sqlite3_step(), and sqlite3_finalize(), that allows an application to run multiple statements of SQL without having to use a lot of C code. The sqlite3_exec() interface runs zero or more UTF-8 encoded, semicolon-separated SQL statements passed into its 2nd argument, in the context of the database connection passed in as its 1st argument. If the callback function of the 3rd argument to sqlite3_exec() is not NULL, then it is invoked for each result row coming out of the evaluated SQL statements. The 4th argument to sqlite3_exec() is relayed through to the 1st argument of each callback invocation. If the callback pointer to sqlite3_exec() is NULL, then no callback is ever invoked and result rows are ignored. If an error occurs while evaluating the SQL statements passed into sqlite3_exec(), then execution of the current statement stops and subsequent statements are skipped. If the 5th parameter to sqlite3_exec() is not NULL then any error message is written into memory obtained from sqlite3_malloc() and passed back through the 5th parameter. To avoid memory leaks, the application should invoke sqlite3_free() on error message strings returned through the 5th parameter of sqlite3_exec() after the error message string is no longer needed. If the 5th parameter to sqlite3_exec() is not NULL and no errors occur, then sqlite3_exec() sets the pointer in its 5th parameter to NULL before returning. If an sqlite3_exec() callback returns non-zero, the sqlite3_exec() routine returns SQLITE_ABORT without invoking the callback again and without running any subsequent SQL statements. The 2nd argument to the sqlite3_exec() callback function is the number of columns in the result. The 3rd argument to the sqlite3_exec() callback is an array of pointers to strings obtained as if from sqlite3_column_text(), one for each column. If an element of a result row is NULL then the corresponding string pointer for the sqlite3_exec() callback is a NULL pointer. The 4th argument to the sqlite3_exec() callback is an array of pointers to strings where each entry represents the name of a corresponding result column as obtained from sqlite3_column_name(). If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer to an empty string, or a pointer that contains only whitespace and/or SQL comments, then no SQL statements are evaluated and the database is not changed. Restrictions:
Enable Or Disable Extended Result Codesint sqlite3_extended_result_codes(sqlite3*, int onoff); The sqlite3_extended_result_codes() routine enables or disables the extended result codes feature of SQLite. The extended result codes are disabled by default for historical compatibility. Destroy A Prepared Statement Objectint sqlite3_finalize(sqlite3_stmt *pStmt); The sqlite3_finalize() function is called to delete a prepared statement. If the most recent evaluation of the statement encountered no errors or if the statement has never been evaluated, then sqlite3_finalize() returns SQLITE_OK. If the most recent evaluation of statement S failed, then sqlite3_finalize(S) returns the appropriate error code or extended error code. The sqlite3_finalize(S) routine can be called at any point during the life cycle of prepared statement S: before statement S is ever evaluated, after one or more calls to sqlite3_reset(), or after any call to sqlite3_step() regardless of whether or not the statement has completed execution. Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op. The application must finalize every prepared statement in order to avoid resource leaks. It is a grievous error for the application to try to use a prepared statement after it has been finalized. Any use of a prepared statement after it has been finalized can result in undefined and undesirable behavior such as segfaults and heap corruption. Last Insert Rowidsqlite3_int64 sqlite3_last_insert_rowid(sqlite3*); Each entry in most SQLite tables (except for WITHOUT ROWID tables) 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 alias for the rowid. The sqlite3_last_insert_rowid(D) interface usually returns the rowid of the most recent successful INSERT into a rowid table or virtual table on database connection D. Inserts into WITHOUT ROWID tables are not recorded. If no successful INSERTs into rowid tables have ever occurred on the database connection D, then sqlite3_last_insert_rowid(D) returns zero. As well as being set automatically as rows are inserted into database tables, the value returned by this function may be set explicitly by sqlite3_set_last_insert_rowid() Some virtual table implementations may INSERT rows into rowid tables as part of committing a transaction (e.g. to flush data accumulated in memory to disk). In this case subsequent calls to this function return the rowid associated with these internal INSERT operations, which leads to unintuitive results. Virtual table implementations that do write to rowid tables in this way can avoid this problem by restoring the original rowid value using sqlite3_set_last_insert_rowid() before returning control to the user. If an INSERT occurs within a trigger then this routine will return the rowid of the inserted row as long as the trigger is running. Once the trigger program ends, the value returned by this routine reverts to what it was before the trigger was 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. For the purposes of this routine, an INSERT is considered to be successful even if it is subsequently rolled back. This function is accessible to SQL statements via the last_insert_rowid() SQL function. If a separate thread performs a new INSERT on the same database connection while the sqlite3_last_insert_rowid() function is running and thus changes the last insert rowid, then the value returned by sqlite3_last_insert_rowid() is unpredictable and might not equal either the old or the new last insert rowid. Run-time Limitsint sqlite3_limit(sqlite3*, int id, int newVal); This interface allows the size of various constructs to be limited on a connection by connection basis. The first parameter is the database connection whose limit is to be set or queried. The second parameter is one of the limit categories that define a class of constructs to be size limited. The third parameter is the new limit for that construct. If the new limit is a negative number, the limit is unchanged. For each limit category SQLITE_LIMIT_NAME there is a hard upper bound set at compile-time by a C preprocessor macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to "_MAX_".) Attempts to increase a limit above its hard upper bound are silently truncated to the hard upper bound. Regardless of whether or not the limit was changed, the sqlite3_limit() interface returns the prior value of the limit. Hence, to find the current value of a limit without changing it, simply invoke this interface with the third parameter set to -1. Run-time limits are intended for use in applications that manage both their own internal database and also databases that are controlled by untrusted external sources. An example application might be a web browser that has its own databases for storing history and separate databases controlled by JavaScript applications downloaded off the Internet. The internal databases can be given the large, default limits. Databases managed by external sources can be given much smaller limits designed to prevent a denial of service attack. Developers might also want to use the sqlite3_set_authorizer() interface to further control untrusted SQL. The size of the database created by an untrusted script can be contained using the max_page_count PRAGMA. New run-time limit categories may be added in future releases. Load An Extensionint 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 */ ); This interface loads an SQLite extension library from the named file. The sqlite3_load_extension() interface attempts to load an SQLite extension library contained in the file zFile. If the file cannot be loaded directly, attempts are made to load with various operating-system specific filename extensions added. So for example, if "samplelib" cannot be loaded, then names like "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might be tried also. The entry point is zProc. zProc may be 0, in which case SQLite will try to come up with an entry point name on its own. It first tries "sqlite3_extension_init". If that does not work, it tries names of the form "sqlite3_X_init" where X consists of the lower-case equivalent of all ASCII alphabetic characters or all ASCII alphanumeric characters in the filename from the last "/" to the first following "." and omitting any initial "lib". The sqlite3_load_extension() interface returns SQLITE_OK on success and SQLITE_ERROR if something goes wrong. 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(). The calling function should free this memory by calling sqlite3_free(). Extension loading must be enabled using sqlite3_enable_load_extension() or sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,1,NULL) prior to calling this API, otherwise an error will be returned. Security warning: It is recommended that the SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION method be used to enable only this interface. The use of the sqlite3_enable_load_extension() interface should be avoided. This will keep the SQL function load_extension() disabled and prevent SQL injections from giving attackers access to extension loading capabilities. See also the load_extension() SQL function. Error Logging Interfacevoid sqlite3_log(int iErrCode, const char *zFormat, ...); The sqlite3_log() interface writes a message into the error log established by the SQLITE_CONFIG_LOG option to sqlite3_config(). If logging is enabled, the zFormat string and subsequent arguments are used with sqlite3_snprintf() to generate the final output string. The sqlite3_log() interface is intended for use by extensions such as virtual tables, collating functions, and SQL functions. While there is nothing to prevent an application from calling sqlite3_log(), doing so is considered bad form. The zFormat string must not be NULL. To avoid deadlocks and other threading problems, the sqlite3_log() routine will not use dynamically allocated memory. The log message is stored in a fixed-length buffer on the stack. If the log message is longer than a few hundred characters, it will be truncated to the length of the buffer. Find the next prepared statementsqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt); This interface returns a pointer to the next prepared statement after pStmt associated with the database connection pDb. If pStmt is NULL then this interface returns a pointer to the first prepared statement associated with the database connection pDb. If no prepared statement satisfies the conditions of this routine, it returns NULL. The database connection pointer D in a call to sqlite3_next_stmt(D,S) must refer to an open database connection and in particular must not be a NULL pointer. Overload A Function For A Virtual Tableint sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg); Virtual tables can provide alternative implementations of functions using the xFindFunction method of the virtual table module. 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 placeholder function that can be overloaded by a virtual table. Query Progress Callbacksvoid sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); The sqlite3_progress_handler(D,N,X,P) interface causes the callback function X to be invoked periodically during long running calls to sqlite3_step() and sqlite3_prepare() and similar for database connection D. An example use for this interface is to keep a GUI updated during a large query. The parameter P is passed through as the only parameter to the callback function X. The parameter N is the approximate number of virtual machine instructions that are evaluated between successive invocations of the callback X. If N is less than one then the progress handler is disabled. Only a single progress handler may be defined at one time per database connection; setting a new progress handler cancels the old one. Setting parameter X to NULL disables the progress handler. The progress handler is also disabled by setting N to a value less than 1. If the progress callback returns non-zero, the operation is interrupted. This feature can be used to implement a "Cancel" button on a GUI progress dialog box. The progress handler callback must not do anything that will modify the database connection that invoked the progress handler. Note that sqlite3_prepare_v2() and sqlite3_step() both modify their database connections for the meaning of "modify" in this paragraph. The progress handler callback would originally only be invoked from the bytecode engine. It still might be invoked during sqlite3_prepare() and similar because those routines might force a reparse of the schema which involves running the bytecode engine. However, beginning with SQLite version 3.41.0, the progress handler callback might also be invoked directly from sqlite3_prepare() while analyzing and generating code for complex queries. Pseudo-Random Number Generatorvoid sqlite3_randomness(int N, void *P); SQLite contains a high-quality pseudo-random number generator (PRNG) used to select random ROWIDs when inserting new records into a table that already uses the largest possible ROWID. The PRNG is also used for the built-in random() and randomblob() SQL functions. This interface allows applications to access the same PRNG for other purposes. A call to this routine stores N bytes of randomness into buffer P. The P parameter can be a NULL pointer. If this routine has not been previously called or if the previous call had N less than one or a NULL pointer for P, then the PRNG is seeded using randomness obtained from the xRandomness method of the default sqlite3_vfs object. If the previous call to this routine had an N of 1 or more and a non-NULL P then the pseudo-randomness is generated internally and without recourse to the sqlite3_vfs xRandomness method. Attempt To Free Heap Memoryint sqlite3_release_memory(int); The sqlite3_release_memory() interface attempts to free N bytes of heap memory by deallocating non-essential memory allocations held by the database library. Memory used to cache database pages to improve performance is an example of non-essential memory. sqlite3_release_memory() returns the number of bytes actually freed, which might be more or less than the amount requested. The sqlite3_release_memory() routine is a no-op returning zero if SQLite is not compiled with SQLITE_ENABLE_MEMORY_MANAGEMENT. See also: sqlite3_db_release_memory() Reset A Prepared Statement Objectint sqlite3_reset(sqlite3_stmt *pStmt); The sqlite3_reset() function is called to reset a 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_*() API retain their values. Use sqlite3_clear_bindings() to reset the bindings. The sqlite3_reset(S) interface resets the prepared statement S back to the beginning of its program. The return code from sqlite3_reset(S) indicates whether or not the previous evaluation of prepared statement S completed successfully. If sqlite3_step(S) has never before been called on S or if sqlite3_step(S) has not been called since the previous call to sqlite3_reset(S), then sqlite3_reset(S) will return SQLITE_OK. If the most recent call to sqlite3_step(S) for the prepared statement S indicated an error, then sqlite3_reset(S) returns an appropriate error code. The sqlite3_reset(S) interface might also return an error code if there were no prior errors but the process of resetting the prepared statement caused a new error. For example, if an INSERT statement with a RETURNING clause is only stepped one time, that one call to sqlite3_step(S) might return SQLITE_ROW but the overall statement might still fail and the sqlite3_reset(S) call might return SQLITE_BUSY if locking constraints prevent the database change from committing. Therefore, it is important that applications check the return code from sqlite3_reset(S) even if no prior call to sqlite3_step(S) indicated a problem. The sqlite3_reset(S) interface does not change the values of any bindings on the prepared statement S. Reset Automatic Extension Loadingvoid sqlite3_reset_auto_extension(void); This interface disables all automatic extensions previously registered using sqlite3_auto_extension(). Return A Dynamic String From an SQL Functionvoid sqlite3_result_str(sqlite3_context*, sqlite3_str*, int); The sqlite3_result_str(C,S,F) interface causes the dynamic string S to become the return value for the application-defined function or virtual table that uses sqlite3_context C. The F flag can be one of SQLITE_COPY or SQLITE_XFER or SQLITE_FINISH. If the dynamic string is invalid or incomplete due to an out-of-memory or string-too-large error, then this routine transfers that error over to the SQL function. If the F argument is SQLITE_COPY, then a copy of the dynamic string content is made and the dynamic string object is unchanged. If the F argument is SQLITE_XFER, then ownership of the content in the dynamic is transferred to the SQL function (via a pointer copy rather than a string copy) and the dynamic string is reset to an empty string. The SQLITE_FINISH value for F works like SQLITE_RESET except that it also invokes the sqlite3_str_free(S) destructor on the dynamic string object. Setting The Subtype Of An SQL Functionvoid sqlite3_result_subtype(sqlite3_context*,unsigned int); The sqlite3_result_subtype(C,T) function causes the subtype of the result from the application-defined SQL function with sqlite3_context C to be the value T. Only the lower 8 bits of the subtype T are preserved in current versions of SQLite; higher order bits are discarded. The number of subtype bytes preserved by SQLite might increase in future releases of SQLite. Every application-defined SQL function that invokes this interface should include the SQLITE_RESULT_SUBTYPE property in its text encoding argument when the SQL function is registered. If the SQLITE_RESULT_SUBTYPE property is omitted from the function that invokes sqlite3_result_subtype(), then in some cases the sqlite3_result_subtype() might fail to set the result subtype. If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any SQL function that invokes the sqlite3_result_subtype() interface and that does not have the SQLITE_RESULT_SUBTYPE property will raise an error. Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1 by default. Serialize a databaseunsigned char *sqlite3_serialize( sqlite3 *db, /* The database connection */ const char *zSchema, /* Which DB to serialize. ex: "main", "temp", ... */ sqlite3_int64 *piSize, /* Write size of the DB here, if not NULL */ unsigned int mFlags /* Zero or more SQLITE_SERIALIZE_* flags */ ); The sqlite3_serialize(D,S,P,F) interface returns a pointer to memory that is a serialization of the S database on database connection D. If S is a NULL pointer, the main database is used. If P is not a NULL pointer, then the size of the database in bytes is written into *P. For an ordinary on-disk database file, the serialization is just a copy of the disk file. For an in-memory database or a "TEMP" database, the serialization is the same sequence of bytes which would be written to disk if that database were backed up to disk. The usual case is that sqlite3_serialize() copies the serialization of the database into memory obtained from sqlite3_malloc64() and returns a pointer to that memory. The caller is responsible for freeing the returned value to avoid a memory leak. However, if the F argument contains the SQLITE_SERIALIZE_NOCOPY bit, then no memory allocations are made, and the sqlite3_serialize() function will return a pointer to the contiguous memory representation of the database that SQLite is currently using for that database, or NULL if no such contiguous memory representation of the database exists. A contiguous memory representation of the database will usually only exist if there has been a prior call to sqlite3_deserialize(D,S,...) with the same values of D and S. The size of the database is written into *P even if the SQLITE_SERIALIZE_NOCOPY bit is set but no contiguous copy of the database exists. After the call, if the SQLITE_SERIALIZE_NOCOPY bit had been set, the returned buffer content will remain accessible and unchanged until either the next write operation on the connection or when the connection is closed, and applications must not modify the buffer. If the bit had been clear, the returned buffer will not be accessed by SQLite after the call. A call to sqlite3_serialize(D,S,P,F) might return NULL even if the SQLITE_SERIALIZE_NOCOPY bit is omitted from argument F if a memory allocation error occurs. This interface is omitted if SQLite is compiled with the SQLITE_OMIT_DESERIALIZE option. Set Error Code And Messageint sqlite3_set_errmsg(sqlite3 *db, int errcode, const char *zErrMsg); Set the error code of the database handle passed as the first argument to errcode, and the error message to a copy of nul-terminated string zErrMsg. If zErrMsg is passed NULL, then the error message is set to the default message associated with the supplied error code. Subsequent calls to sqlite3_errcode() and sqlite3_errmsg() and similar will return the values set by this routine in place of what was previously set by SQLite itself. This function returns SQLITE_OK if the error code and error message are successfully set, SQLITE_NOMEM if an OOM occurs, and SQLITE_MISUSE if the database handle is NULL or invalid. The error code and message set by this routine remains in effect until they are changed, either by another call to this routine or until they are changed to by SQLite itself to reflect the result of some subsquent API call. This function is intended for use by SQLite extensions or wrappers. The idea is that an extension or wrapper can use this routine to set error messages and error codes and thus behave more like a core SQLite feature from the point of view of an application. Set the Last Insert Rowid value.void sqlite3_set_last_insert_rowid(sqlite3*,sqlite3_int64); The sqlite3_set_last_insert_rowid(D, R) method allows the application to set the value returned by calling sqlite3_last_insert_rowid(D) to R without inserting a row into the database. Set the Setlk Timeoutint sqlite3_setlk_timeout(sqlite3*, int ms, int flags); This routine is only useful in SQLITE_ENABLE_SETLK_TIMEOUT builds. If the VFS supports blocking locks, it sets the timeout in ms used by eligible locks taken on wal mode databases by the specified database handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does not support blocking locks, this function is a no-op. Passing 0 to this function disables blocking locks altogether. Passing -1 to this function requests that the VFS blocks for a long time - indefinitely if possible. The results of passing any other negative value are undefined. Internally, each SQLite database handle stores two timeout values - the busy-timeout (used for rollback mode databases, or if the VFS does not support blocking locks) and the setlk-timeout (used for blocking locks on wal-mode databases). The sqlite3_busy_timeout() method sets both values, this function sets only the setlk-timeout value. Therefore, to configure separate busy-timeout and setlk-timeout values for a single database handle, call sqlite3_busy_timeout() followed by this function. Whenever the number of connections to a wal mode database falls from 1 to 0, the last connection takes an exclusive lock on the database, then checkpoints and deletes the wal file. While it is doing this, any new connection that tries to read from the database fails with an SQLITE_BUSY error. Or, if the SQLITE_SETLK_BLOCK_ON_CONNECT flag is passed to this API, the new connection blocks until the exclusive lock has been released. Suspend Execution For A Short Timeint sqlite3_sleep(int); The sqlite3_sleep() function causes the current thread to suspend execution for at least a number of milliseconds specified in its parameter. If the operating system does not support sleep requests with millisecond time resolution, then the time will be rounded up to the nearest second. The number of milliseconds of sleep actually requested from the operating system is returned. SQLite implements this interface by calling the xSleep() method of the default sqlite3_vfs object. If the xSleep() method of the default VFS is not implemented correctly, or not implemented at all, then the behavior of sqlite3_sleep() may deviate from the description in the previous paragraphs. If a negative argument is passed to sqlite3_sleep() the results vary by VFS and operating system. Some system treat a negative argument as an instruction to sleep forever. Others understand it to mean do not sleep at all. In SQLite version 3.42.0 and later, a negative argument passed into sqlite3_sleep() is changed to zero before it is relayed down into the xSleep method of the VFS. Compare the ages of two snapshot handles.int sqlite3_snapshot_cmp( sqlite3_snapshot *p1, sqlite3_snapshot *p2 ); The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages of two valid snapshot handles. If the two snapshot handles are not associated with the same database file, the result of the comparison is undefined. Additionally, the result of the comparison is only valid if both of the snapshot handles were obtained by calling sqlite3_snapshot_get() since the last time the wal file was deleted. The wal file is deleted when the database is changed back to rollback mode or when the number of database clients drops to zero. If either snapshot handle was obtained before the wal file was last deleted, the value returned by this function is undefined. Otherwise, this API returns a negative value if P1 refers to an older snapshot than P2, zero if the two handles refer to the same database snapshot, and a positive value if P1 is a newer snapshot than P2. This interface is only available if SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. Destroy a snapshotvoid sqlite3_snapshot_free(sqlite3_snapshot*); The sqlite3_snapshot_free(P) interface destroys sqlite3_snapshot P. The application must eventually free every sqlite3_snapshot object using this routine to avoid a memory leak. The sqlite3_snapshot_free() interface is only available when the SQLITE_ENABLE_SNAPSHOT compile-time option is used. Record A Database Snapshotint sqlite3_snapshot_get( sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot ); The sqlite3_snapshot_get(D,S,P) interface attempts to make a new sqlite3_snapshot object that records the current state of schema S in database connection D. On success, the sqlite3_snapshot_get(D,S,P) interface writes a pointer to the newly created sqlite3_snapshot object into *P and returns SQLITE_OK. If there is not already a read-transaction open on schema S when this function is called, one is opened automatically. If a read-transaction is opened by this function, then it is guaranteed that the returned snapshot object may not be invalidated by a database writer or checkpointer until after the read-transaction is closed. This is not guaranteed if a read-transaction is already open when this function is called. In that case, any subsequent write or checkpoint operation on the database may invalidate the returned snapshot handle, even while the read-transaction remains open. The following must be true for this function to succeed. If any of the following statements are false when sqlite3_snapshot_get() is called, SQLITE_ERROR is returned. The final value of *P is undefined in this case.
This function may also return SQLITE_NOMEM. If it is called with the database handle in autocommit mode but fails for some other reason, whether or not a read transaction is opened on schema S is undefined. The sqlite3_snapshot object returned from a successful call to sqlite3_snapshot_get() must be freed using sqlite3_snapshot_free() to avoid a memory leak. The sqlite3_snapshot_get() interface is only available when the SQLITE_ENABLE_SNAPSHOT compile-time option is used. Start a read transaction on an historical snapshotint sqlite3_snapshot_open( sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot ); The sqlite3_snapshot_open(D,S,P) interface either starts a new read transaction or upgrades an existing one for schema S of database connection D such that the read transaction refers to historical snapshot P, rather than the most recent change to the database. The sqlite3_snapshot_open() interface returns SQLITE_OK on success or an appropriate error code if it fails. In order to succeed, the database connection must not be in autocommit mode when sqlite3_snapshot_open(D,S,P) is called. If there is already a read transaction open on schema S, then the database handle must have no active statements (SELECT statements that have been passed to sqlite3_step() but not sqlite3_reset() or sqlite3_finalize()). SQLITE_ERROR is returned if either of these conditions is violated, or if schema S does not exist, or if the snapshot object is invalid. A call to sqlite3_snapshot_open() will fail to open if the specified snapshot has been overwritten by a checkpoint. In this case SQLITE_ERROR_SNAPSHOT is returned. If there is already a read transaction open when this function is invoked, then the same read transaction remains open (on the same database snapshot) if SQLITE_ERROR, SQLITE_BUSY or SQLITE_ERROR_SNAPSHOT is returned. If another error code - for example SQLITE_PROTOCOL or an SQLITE_IOERR error code - is returned, then the final state of the read transaction is undefined. If SQLITE_OK is returned, then the read transaction is now open on database snapshot P. A call to sqlite3_snapshot_open(D,S,P) will fail if the database connection D does not know that the database file for schema S is in WAL mode. A database connection might not know that the database file is in WAL mode if there has been no prior I/O on that database connection, or if the database entered WAL mode after the most recent I/O on the database connection. (Hint: Run "PRAGMA application_id" against a newly opened database connection in order to make it ready to use snapshots.) The sqlite3_snapshot_open() interface is only available when the SQLITE_ENABLE_SNAPSHOT compile-time option is used. Recover snapshots from a wal fileint sqlite3_snapshot_recover(sqlite3 *db, const char *zDb); If a WAL file remains on disk after all database connections close (either through the use of the SQLITE_FCNTL_PERSIST_WAL file control or because the last process to have the database opened exited without calling sqlite3_close()) and a new connection is subsequently opened on that database and WAL file, the sqlite3_snapshot_open() interface will only be able to open the last transaction added to the WAL file even though the WAL file contains other valid transactions. This function attempts to scan the WAL file associated with database zDb of database handle db and make all valid snapshots available to sqlite3_snapshot_open(). It is an error if there is already a read transaction open on the database, or if the database is not a WAL mode database. SQLITE_OK is returned if successful, or an SQLite error code otherwise. This interface is only available if SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. Deprecated Soft Heap Limit Interfacevoid sqlite3_soft_heap_limit(int N); This is a deprecated version of the sqlite3_soft_heap_limit64() interface. This routine is provided for historical compatibility only. All new applications should use the sqlite3_soft_heap_limit64() interface rather than this one. Evaluate An SQL Statementint sqlite3_step(sqlite3_stmt*); After a prepared statement has been prepared using any of sqlite3_prepare_v2(), sqlite3_prepare_v3(), sqlite3_prepare16_v2(), or sqlite3_prepare16_v3() or one of the legacy interfaces sqlite3_prepare() or sqlite3_prepare16(), this function must be called one or more times to evaluate the statement. The details of the behavior of the sqlite3_step() interface depend on whether the statement was prepared using the newer "vX" interfaces sqlite3_prepare_v3(), sqlite3_prepare_v2(), sqlite3_prepare16_v3(), sqlite3_prepare16_v2() or the older legacy interfaces sqlite3_prepare() and sqlite3_prepare16(). The use of the new "vX" interface is recommended for new applications but the legacy interface will continue to be supported. In the legacy interface, the return value will be either SQLITE_BUSY, SQLITE_DONE, SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE. With the "v2" interface, any of the other result codes or extended result codes might be returned as well. 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 an 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 column access functions. sqlite3_step() is called again to retrieve the next row of data. SQLITE_ERROR means that a run-time error (such as a constraint violation) has occurred. sqlite3_step() should not be called again on the VM. More information may be found by calling sqlite3_errmsg(). With the legacy interface, a more specific error code (for example, SQLITE_INTERRUPT, SQLITE_SCHEMA, SQLITE_CORRUPT, and so forth) can be obtained by calling sqlite3_reset() on the prepared statement. In the "v2" interface, the more specific error code is returned directly by sqlite3_step(). SQLITE_MISUSE means that this routine was called inappropriately. Perhaps it was called on a prepared statement that has already been 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. For all versions of SQLite up to and including 3.6.23.1, a call to sqlite3_reset() was required after sqlite3_step() returned anything other than SQLITE_ROW before any subsequent invocation of sqlite3_step(). Failure to reset the prepared statement using sqlite3_reset() would result in an SQLITE_MISUSE return from sqlite3_step(). But after version 3.6.23.1 (2010-03-26), sqlite3_step() began calling sqlite3_reset() automatically in this circumstance rather than returning SQLITE_MISUSE. This is not considered a compatibility break because any application that ever receives an SQLITE_MISUSE error is broken by definition. The SQLITE_OMIT_AUTORESET compile-time option can be used to restore the legacy behavior. Goofy Interface Alert: In the legacy interface, the sqlite3_step() API always returns a generic error code, SQLITE_ERROR, following any error other than SQLITE_BUSY and SQLITE_MISUSE. You must call sqlite3_reset() or sqlite3_finalize() in order to find one of the specific error codes that better describes the error. 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 sqlite3_prepare_v3() or sqlite3_prepare_v2() or sqlite3_prepare16_v2() or sqlite3_prepare16_v3() instead of the legacy sqlite3_prepare() and sqlite3_prepare16() interfaces, then the more specific error codes are returned directly by sqlite3_step(). The use of the "vX" interfaces is recommended. Determine If A Prepared Statement Has Been Resetint sqlite3_stmt_busy(sqlite3_stmt*); The sqlite3_stmt_busy(S) interface returns true (non-zero) if the prepared statement S has been stepped at least once using sqlite3_step(S) but has neither run to completion (returned SQLITE_DONE from sqlite3_step(S)) nor been reset using sqlite3_reset(S). The sqlite3_stmt_busy(S) interface returns false if S is a NULL pointer. If S is not a NULL pointer and is not a pointer to a valid prepared statement object, then the behavior is undefined and probably undesirable. This interface can be used in combination sqlite3_next_stmt() to locate all prepared statements associated with a database connection that are in need of being reset. This can be used, for example, in diagnostic routines to search for prepared statements that are holding a transaction open. Change The EXPLAIN Setting For A Prepared Statementint sqlite3_stmt_explain(sqlite3_stmt *pStmt, int eMode); The sqlite3_stmt_explain(S,E) interface changes the EXPLAIN setting for prepared statement S. If E is zero, then S becomes a normal prepared statement. If E is 1, then S behaves as if its SQL text began with "EXPLAIN". If E is 2, then S behaves as if its SQL text began with "EXPLAIN QUERY PLAN". Calling sqlite3_stmt_explain(S,E) might cause S to be reprepared. SQLite tries to avoid a reprepare, but a reprepare might be necessary on the first transition into EXPLAIN or EXPLAIN QUERY PLAN mode. Because of the potential need to reprepare, a call to sqlite3_stmt_explain(S,E) will fail with SQLITE_ERROR if S cannot be reprepared because it was created using sqlite3_prepare() instead of the newer sqlite3_prepare_v2() or sqlite3_prepare_v3() interfaces and hence has no saved SQL text with which to reprepare. Changing the explain setting for a prepared statement does not change the original SQL text for the statement. Hence, if the SQL text originally began with EXPLAIN or EXPLAIN QUERY PLAN, but sqlite3_stmt_explain(S,0) is called to convert the statement into an ordinary statement, the EXPLAIN or EXPLAIN QUERY PLAN keywords will still appear in the sqlite3_sql(S) output, even though the statement now acts like a normal SQL statement. This routine returns SQLITE_OK if the explain mode is successfully changed, or an error code if the explain mode could not be changed. The explain mode cannot be changed while a statement is active. Hence, it is good practice to call sqlite3_reset(S) immediately prior to calling sqlite3_stmt_explain(S,E). Query The EXPLAIN Setting For A Prepared Statementint sqlite3_stmt_isexplain(sqlite3_stmt *pStmt); The sqlite3_stmt_isexplain(S) interface returns 1 if the prepared statement S is an EXPLAIN statement, or 2 if the statement S is an EXPLAIN QUERY PLAN. The sqlite3_stmt_isexplain(S) interface returns 0 if S is an ordinary statement or a NULL pointer. Determine If An SQL Statement Writes The Databaseint sqlite3_stmt_readonly(sqlite3_stmt *pStmt); The sqlite3_stmt_readonly(X) interface returns true (non-zero) if and only if the prepared statement X makes no direct changes to the content of the database file. Note that application-defined SQL functions or virtual tables might change the database indirectly as a side effect. For example, if an application defines a function "eval()" that calls sqlite3_exec(), then the following SQL statement would change the database file through side-effects:
But because the SELECT statement does not change the database file directly, sqlite3_stmt_readonly() would still return true. Transaction control statements such as BEGIN, COMMIT, ROLLBACK, SAVEPOINT, and RELEASE cause sqlite3_stmt_readonly() to return true, since the statements themselves do not actually modify the database but rather they control the timing of when other statements modify the database. The ATTACH and DETACH statements also cause sqlite3_stmt_readonly() to return true since, while those statements change the configuration of a database connection, they do not make changes to the content of the database files on disk. The sqlite3_stmt_readonly() interface returns true for BEGIN since BEGIN merely sets internal flags, but the BEGIN IMMEDIATE and BEGIN EXCLUSIVE commands do touch the database and so sqlite3_stmt_readonly() returns false for those commands. This routine returns false if there is any possibility that the statement might change the database file. A false return does not guarantee that the statement will change the database file. For example, an UPDATE statement might have a WHERE clause that makes it a no-op, but the sqlite3_stmt_readonly() result would still be false. Similarly, a CREATE TABLE IF NOT EXISTS statement is a read-only no-op if the table already exists, but sqlite3_stmt_readonly() still returns false for such a statement. If prepared statement X is an EXPLAIN or EXPLAIN QUERY PLAN statement, then sqlite3_stmt_readonly(X) returns the same value as if the EXPLAIN or EXPLAIN QUERY PLAN prefix were omitted. Zero Scan-Status Countersvoid sqlite3_stmt_scanstatus_reset(sqlite3_stmt*); Zero all sqlite3_stmt_scanstatus() related event counters. This API is only available if the library is built with pre-processor symbol SQLITE_ENABLE_STMT_SCANSTATUS defined. Prepared Statement Statusint sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg); Each prepared statement maintains various SQLITE_STMTSTATUS counters that measure the number of times it has performed specific operations. These counters can be used to monitor the performance characteristics of the prepared statements. For example, if the number of table steps greatly exceeds the number of table searches or result rows, that would tend to indicate that the prepared statement is using a full table scan rather than an index. This interface is used to retrieve and reset counter values from a prepared statement. The first argument is the prepared statement object to be interrogated. The second argument is an integer code for a specific SQLITE_STMTSTATUS counter to be interrogated. The current value of the requested counter is returned. If the resetFlg is true, then the counter is reset to zero after this interface call returns. See also: sqlite3_status() and sqlite3_db_status(). Create A New Dynamic String Objectsqlite3_str *sqlite3_str_new(sqlite3*); The sqlite3_str_new(D) interface allocates and initializes a new sqlite3_str object. To avoid memory leaks, the object returned by sqlite3_str_new() must be freed by a subsequent call to sqlite3_str_finish(X). The sqlite3_str_new(D) interface always returns a pointer to a valid sqlite3_str object, though in the event of an out-of-memory error the returned object might be a special singleton that will silently reject new text, always return SQLITE_NOMEM from sqlite3_str_errcode(), always return 0 for sqlite3_str_length(), and always return NULL from sqlite3_str_finish(X). It is always safe to use the value returned by sqlite3_str_new(D) as the sqlite3_str parameter to any of the other sqlite3_str methods. The D parameter to sqlite3_str_new(D) may be NULL. If the D parameter in sqlite3_str_new(D) is not NULL, then the maximum length of the string contained in the sqlite3_str object will be the value set for sqlite3_limit(D,SQLITE_LIMIT_LENGTH) instead of SQLITE_MAX_LENGTH. String Globbingint sqlite3_strglob(const char *zGlob, const char *zStr); The sqlite3_strglob(P,X) interface returns zero if and only if string X matches the GLOB pattern P. The definition of GLOB pattern matching used in sqlite3_strglob(P,X) is the same as for the "X GLOB P" operator in the SQL dialect understood by SQLite. The sqlite3_strglob(P,X) function is case sensitive. Note that this routine returns zero on a match and non-zero if the strings do not match, the same as sqlite3_stricmp() and sqlite3_strnicmp(). See also: sqlite3_strlike(). String LIKE Matchingint sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc); The sqlite3_strlike(P,X,E) interface returns zero if and only if string X matches the LIKE pattern P with escape character E. The definition of LIKE pattern matching used in sqlite3_strlike(P,X,E) is the same as for the "X LIKE P ESCAPE E" operator in the SQL dialect understood by SQLite. For "X LIKE P" without the ESCAPE clause, set the E parameter of sqlite3_strlike(P,X,E) to 0. As with the LIKE operator, the sqlite3_strlike(P,X,E) function is case insensitive - equivalent upper and lower case ASCII characters match one another. The sqlite3_strlike(P,X,E) function matches Unicode characters, though only ASCII characters are case folded. Note that this routine returns zero on a match and non-zero if the strings do not match, the same as sqlite3_stricmp() and sqlite3_strnicmp(). See also: sqlite3_strglob(). Low-level system error codeint sqlite3_system_errno(sqlite3*); Attempt to return the underlying operating system error code or error number that caused the most recent I/O error or failure to open a file. The return value is OS-dependent. For example, on unix systems, after sqlite3_open_v2() returns SQLITE_CANTOPEN, this interface could be called to get back the underlying "errno" that caused the problem, such as ENOSPC, EAUTH, EISDIR, and so forth. Extract Metadata About A Column Of A Tableint 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 */ ); The sqlite3_table_column_metadata(X,D,T,C,....) routine returns information about column C of table T in database D on database connection X. The sqlite3_table_column_metadata() interface returns SQLITE_OK and fills in the non-NULL pointers in the final five arguments with appropriate values if the specified column exists. The sqlite3_table_column_metadata() interface returns SQLITE_ERROR if the specified column does not exist. If the column-name parameter to sqlite3_table_column_metadata() is a NULL pointer, then this routine simply checks for the existence of the table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it does not. If the table name parameter T in a call to sqlite3_table_column_metadata(X,D,T,C,...) is NULL then the result is undefined behavior. The column is identified by the second, third and fourth parameters to this function. The second parameter is either the name of the database (i.e. "main", "temp", or an attached database) containing the specified table or NULL. If it is NULL, then all attached databases are searched for the table using the same algorithm used by the database engine to resolve unqualified table references. The third and fourth parameters to this function are the table and column name of the desired column, respectively. Metadata is returned by writing to the memory locations passed as the 5th and subsequent parameters to this function. Any of these arguments may be NULL, in which case the corresponding element of metadata is omitted.
The memory pointed to by the character pointers returned for the declaration type and collation sequence is valid until the next call to any SQLite API function. If the specified table is actually a view, an error code is returned. If the specified column is "rowid", "oid" or "_rowid_" and the table is not a WITHOUT ROWID table 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 INTEGER PRIMARY KEY column, then the outputs for the rowid are set as follows: data type: "INTEGER" collation sequence: "BINARY" not null: 0 primary key: 1 auto increment: 0 This function causes all database schemas to be read from disk and parsed, if that has not already been done, and returns an error if any errors are encountered while loading the schema. Testing Interfaceint sqlite3_test_control(int op, ...); The sqlite3_test_control() interface is used to read out internal state of SQLite and to inject faults into SQLite for testing purposes. The first parameter is an operation code that determines the number, meaning, and operation of all subsequent parameters. This interface is not for use by applications. It exists solely for verifying the correct operation of the SQLite library. Depending on how the SQLite library is compiled, this interface might not exist. The details of the operation codes, their meanings, the parameters they take, and what they do are all subject to change without notice. Unlike most of the SQLite API, this function is not guaranteed to operate consistently from one release to the next. Test To See If The Library Is Threadsafeint sqlite3_threadsafe(void); The sqlite3_threadsafe() function returns zero if and only if SQLite was compiled with mutexing code omitted due to the SQLITE_THREADSAFE compile-time option being set to 0. SQLite can be compiled with or without mutexes. When the SQLITE_THREADSAFE C preprocessor macro is 1 or 2, mutexes are enabled and SQLite is threadsafe. When the SQLITE_THREADSAFE macro is 0, the mutexes are omitted. Without the mutexes, it is not safe to use SQLite concurrently from more than one thread. Enabling mutexes incurs a measurable performance penalty. So if speed is of utmost importance, it makes sense to disable the mutexes. But for maximum safety, mutexes should be enabled. The default behavior is for mutexes to be enabled. This interface can be used by an application to make sure that the version of SQLite that it is linking against was compiled with the desired setting of the SQLITE_THREADSAFE macro. This interface only reports on the compile-time mutex setting of the SQLITE_THREADSAFE flag. If SQLite is compiled with SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but can be fully or partially disabled using a call to sqlite3_config() with the verbs SQLITE_CONFIG_SINGLETHREAD, SQLITE_CONFIG_MULTITHREAD, or SQLITE_CONFIG_SERIALIZED. The return value of the sqlite3_threadsafe() function shows only the compile-time setting of thread safety, not any run-time changes to that setting made by sqlite3_config(). In other words, the return value from sqlite3_threadsafe() is unchanged by calls to sqlite3_config(). See the threading mode documentation for additional information. SQL Trace Hookint sqlite3_trace_v2( sqlite3*, unsigned uMask, int(*xCallback)(unsigned,void*,void*,void*), void *pCtx ); The sqlite3_trace_v2(D,M,X,P) interface registers a trace callback function X against database connection D, using property mask M and context pointer P. If the X callback is NULL or if the M mask is zero, then tracing is disabled. The M argument should be the bitwise OR-ed combination of zero or more SQLITE_TRACE constants. Each call to either sqlite3_trace(D,X,P) or sqlite3_trace_v2(D,M,X,P) overrides (cancels) all prior calls to sqlite3_trace(D,X,P) or sqlite3_trace_v2(D,M,X,P) for the database connection D. Each database connection may have at most one trace callback. The X callback is invoked whenever any of the events identified by mask M occur. The integer return value from the callback is currently ignored, though this may change in future releases. Callback implementations should return zero to ensure future compatibility. A trace callback is invoked with four arguments: callback(T,C,P,X). The T argument is one of the SQLITE_TRACE constants to indicate why the callback was invoked. The C argument is a copy of the context pointer. The P and X arguments are pointers whose meanings depend on T. The sqlite3_trace_v2() interface is intended to replace the legacy interfaces sqlite3_trace() and sqlite3_profile(), both of which are deprecated. Determine the transaction state of a databaseint sqlite3_txn_state(sqlite3*,const char *zSchema); The sqlite3_txn_state(D,S) interface returns the current transaction state of schema S in database connection D. If S is NULL, then the highest transaction state of any schema on database connection D is returned. Transaction states are (in order of lowest to highest):
Unlock Notificationint sqlite3_unlock_notify( sqlite3 *pBlocked, /* Waiting connection */ void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */ void *pNotifyArg /* Argument to pass to xNotify */ ); When running in shared-cache mode, a database operation may fail with an SQLITE_LOCKED error if the required locks on the shared-cache or individual tables within the shared-cache cannot be obtained. See SQLite Shared-Cache Mode for a description of shared-cache locking. This API may be used to register a callback that SQLite will invoke when the connection currently holding the required lock relinquishes it. This API is only available if the library was compiled with the SQLITE_ENABLE_UNLOCK_NOTIFY C-preprocessor symbol defined. See Also: Using the SQLite Unlock Notification Feature. Shared-cache locks are released when a database connection concludes its current transaction, either by committing it or rolling it back. When a connection (known as the blocked connection) fails to obtain a shared-cache lock and SQLITE_LOCKED is returned to the caller, the identity of the database connection (the blocking connection) that has locked the required resource is stored internally. After an application receives an SQLITE_LOCKED error, it may call the sqlite3_unlock_notify() method with the blocked connection handle as the first argument to register for a callback that will be invoked when the blocking connection's current transaction is concluded. The callback is invoked from within the sqlite3_step or sqlite3_close call that concludes the blocking connection's transaction. If sqlite3_unlock_notify() is called in a multi-threaded application, there is a chance that the blocking connection will have already concluded its transaction by the time sqlite3_unlock_notify() is invoked. If this happens, then the specified callback is invoked immediately, from within the call to sqlite3_unlock_notify(). If the blocked connection is attempting to obtain a write-lock on a shared-cache table, and more than one other connection currently holds a read-lock on the same table, then SQLite arbitrarily selects one of the other connections to use as the blocking connection. There may be at most one unlock-notify callback registered by a blocked connection. If sqlite3_unlock_notify() is called when the blocked connection already has a registered unlock-notify callback, then the new callback replaces the old. If sqlite3_unlock_notify() is called with a NULL pointer as its second argument, then any existing unlock-notify callback is canceled. The blocked connection's unlock-notify callback may also be canceled by closing the blocked connection using sqlite3_close(). The unlock-notify callback is not reentrant. If an application invokes any sqlite3_xxx API functions from within an unlock-notify callback, a crash or deadlock may be the result. Unless deadlock is detected (see below), sqlite3_unlock_notify() always returns SQLITE_OK. Callback Invocation Details When an unlock-notify callback is registered, the application provides a single void* pointer that is passed to the callback when it is invoked. However, the signature of the callback function allows SQLite to pass it an array of void* context pointers. The first argument passed to an unlock-notify callback is a pointer to an array of void* pointers, and the second is the number of entries in the array. When a blocking connection's transaction is concluded, there may be more than one blocked connection that has registered for an unlock-notify callback. If two or more such blocked connections have specified the same callback function, then instead of invoking the callback function multiple times, it is invoked once with the set of void* context pointers specified by the blocked connections bundled together into an array. This gives the application an opportunity to prioritize any actions related to the set of unblocked database connections. Deadlock Detection Assuming that after registering for an unlock-notify callback a database waits for the callback to be issued before taking any further action (a reasonable assumption), then using this API may cause the application to deadlock. For example, if connection X is waiting for connection Y's transaction to be concluded, and similarly connection Y is waiting on connection X's transaction, then neither connection will proceed and the system may remain deadlocked indefinitely. To avoid this scenario, the sqlite3_unlock_notify() performs deadlock detection. If a given call to sqlite3_unlock_notify() would put the system in a deadlocked state, then SQLITE_LOCKED is returned and no unlock-notify callback is registered. The system is said to be in a deadlocked state if connection A has registered for an unlock-notify callback on the conclusion of connection B's transaction, and connection B has itself registered for an unlock-notify callback when connection A's transaction is concluded. Indirect deadlock is also detected, so the system is also considered to be deadlocked if connection B has registered for an unlock-notify callback on the conclusion of connection C's transaction, where connection C is waiting on connection A. Any number of levels of indirection are allowed. The "DROP TABLE" Exception When a call to sqlite3_step() returns SQLITE_LOCKED, it is almost always appropriate to call sqlite3_unlock_notify(). There is however, one exception. When executing a "DROP TABLE" or "DROP INDEX" statement, SQLite checks if there are any currently executing SELECT statements that belong to the same connection. If there are, SQLITE_LOCKED is returned. In this case there is no "blocking connection", so invoking sqlite3_unlock_notify() results in the unlock-notify callback being invoked immediately. If the application then re-attempts the "DROP TABLE" or "DROP INDEX" query, an infinite loop might be the result. One way around this problem is to check the extended error code returned by an sqlite3_step() call. If there is a blocking connection, then the extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in the special "DROP TABLE/INDEX" case, the extended error code is just SQLITE_LOCKED. Data Change Notification Callbacksvoid *sqlite3_update_hook( sqlite3*, void(*)(void *,int ,char const *,char const *,sqlite3_int64), void* ); 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 in a rowid table. 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 in a rowid table. The update hook is disabled by invoking sqlite3_update_hook() with a NULL pointer as the second parameter. 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_sequence). The update hook is not invoked when WITHOUT ROWID tables are modified. In the current implementation, the update hook is not invoked when conflicting rows are deleted because of an ON CONFLICT REPLACE clause. Nor is the update hook invoked when rows are deleted using the truncate optimization. The exceptions defined in this paragraph might change in a future release of SQLite. Whether the update hook is invoked before or after the corresponding change is currently unspecified and may differ depending on the type of change. Do not rely on the order of the hook call with regards to the final result of the operation which triggers the hook. The update hook implementation must not do anything that will modify the database connection that invoked the update hook. Any actions to modify the database connection must be deferred until after the completion of the sqlite3_step() call that triggered the update hook. Note that sqlite3_prepare_v2() and sqlite3_step() both modify their database connections for the meaning of "modify" in this paragraph. The sqlite3_update_hook(D,C,P) function returns the P argument from the previous call on the same database connection D, or NULL for the first call on D. See also the sqlite3_commit_hook(), sqlite3_rollback_hook(), and sqlite3_preupdate_hook() interfaces. User Data For Functionsvoid *sqlite3_user_data(sqlite3_context*); The sqlite3_user_data() interface returns a copy of the pointer that was the pUserData parameter (the 5th parameter) of the sqlite3_create_function() and sqlite3_create_function16() routines that originally registered the application defined function. This routine must be called from the same thread in which the application-defined function is running. Report the internal text encoding state of an sqlite3_value objectint sqlite3_value_encoding(sqlite3_value*); The sqlite3_value_encoding(X) interface returns one of SQLITE_UTF8, SQLITE_UTF16BE, or SQLITE_UTF16LE according to the current text encoding of the value X, assuming that X has type TEXT. If sqlite3_value_type(X) returns something other than SQLITE_TEXT, then the return value from sqlite3_value_encoding(X) is meaningless. Calls to sqlite3_value_text(X), sqlite3_value_text16(X), sqlite3_value_text16be(X), sqlite3_value_text16le(X), sqlite3_value_bytes(X), or sqlite3_value_bytes16(X) might change the encoding of the value X and thus change the return from subsequent calls to sqlite3_value_encoding(X). This routine is intended for used by applications that test and validate the SQLite implementation. This routine is inquiring about the opaque internal state of an sqlite3_value object. Ordinary applications should not need to know what the internal state of an sqlite3_value object is and hence should not need to use this interface. Finding The Subtype Of SQL Valuesunsigned int sqlite3_value_subtype(sqlite3_value*); The sqlite3_value_subtype(V) function returns the subtype for an application-defined SQL function argument V. The subtype information can be used to pass a limited amount of context from one SQL function to another. Use the sqlite3_result_subtype() routine to set the subtype for the return value of an SQL function. Every application-defined SQL function that invokes this interface should include the SQLITE_SUBTYPE property in the text encoding argument when the function is registered. If the SQLITE_SUBTYPE property is omitted, then sqlite3_value_subtype() might return zero instead of the upstream subtype in some corner cases. Determine The Collation For a Virtual Table Constraintconst char *sqlite3_vtab_collation(sqlite3_index_info*,int); This function may only be called from within a call to the xBestIndex method of a virtual table. This function returns a pointer to a string that is the name of the appropriate collation sequence to use for text comparisons on the constraint identified by its arguments. The first argument must be the pointer to the sqlite3_index_info object that is the first parameter to the xBestIndex() method. The second argument must be an index into the aConstraint[] array belonging to the sqlite3_index_info structure passed to xBestIndex. Important: The first parameter must be the same pointer that is passed into the xBestMethod() method. The first parameter may not be a pointer to a different sqlite3_index_info object, even an exact copy. The return value is computed as follows:
Virtual Table Interface Configurationint sqlite3_vtab_config(sqlite3*, int op, ...); This function may be called by either the xConnect or xCreate method of a virtual table implementation to configure various facets of the virtual table interface. If this interface is invoked outside the context of an xConnect or xCreate virtual table method then the behavior is undefined. In the call sqlite3_vtab_config(D,C,...) the D parameter is the database connection in which the virtual table is being created and which is passed in as the first argument to the xConnect or xCreate method that is invoking sqlite3_vtab_config(). The C parameter is one of the virtual table configuration options. The presence and meaning of parameters after C depend on which virtual table configuration option is used. Determine if a virtual table query is DISTINCTint sqlite3_vtab_distinct(sqlite3_index_info*); This API may only be used from within an xBestIndex method of a virtual table implementation. The result of calling this interface from outside of xBestIndex() is undefined and probably harmful. The sqlite3_vtab_distinct() interface returns an integer between 0 and 3. The integer returned by sqlite3_vtab_distinct() gives the virtual table additional information about how the query planner wants the output to be ordered. As long as the virtual table can meet the ordering requirements of the query planner, it may set the "orderByConsumed" flag.
The following table summarizes the conditions under which the virtual table is allowed to set the "orderByConsumed" flag based on the value returned by sqlite3_vtab_distinct(). This table is a restatement of the previous four paragraphs:
For the purposes of comparing virtual table output values to see if the values are the same value for sorting purposes, two NULL values are considered to be the same. In other words, the comparison operator is "IS" (or "IS NOT DISTINCT FROM") and not "==". If a virtual table implementation is unable to meet the requirements specified above, then it must not set the "orderByConsumed" flag in the sqlite3_index_info object or an incorrect answer may result. A virtual table implementation is always free to return rows in any order it wants, as long as the "orderByConsumed" flag is not set. When the "orderByConsumed" flag is unset, the query planner will add extra bytecode to ensure that the final results returned by the SQL query are ordered correctly. The use of the "orderByConsumed" flag and the sqlite3_vtab_distinct() interface is merely an optimization. Careful use of the sqlite3_vtab_distinct() interface and the "orderByConsumed" flag might help queries against a virtual table to run faster. Being overly aggressive and setting the "orderByConsumed" flag when it is not valid to do so, on the other hand, might cause SQLite to return incorrect results. Identify and handle IN constraints in xBestIndexint sqlite3_vtab_in(sqlite3_index_info*, int iCons, int bHandle); This interface may only be used from within an xBestIndex() method of a virtual table implementation. The result of invoking this interface from any other context is undefined and probably harmful. A constraint on a virtual table of the form "column IN (...)" is communicated to the xBestIndex method as a SQLITE_INDEX_CONSTRAINT_EQ constraint. If xBestIndex wants to use this constraint, it must set the corresponding aConstraintUsage[].argvIndex to a positive integer. Then, under the usual mode of handling IN operators, SQLite generates bytecode that invokes the xFilter() method once for each value on the right-hand side of the IN operator. Thus the virtual table only sees a single value from the right-hand side of the IN operator at a time. In some cases, however, it would be advantageous for the virtual table to see all values on the right-hand of the IN operator all at once. The sqlite3_vtab_in() interfaces facilitates this in two ways:
The sqlite3_vtab_in(P,N,F) interface can be invoked multiple times within the same xBestIndex method call. For any given P,N pair, the return value from sqlite3_vtab_in(P,N,F) will always be the same within the same xBestIndex call. If the interface returns true (non-zero), that means that the constraint is an IN operator that can be processed all-at-once. If the constraint is not an IN operator or cannot be processed all-at-once, then the interface returns false. All-at-once processing of the IN operator is selected if both of the following conditions are met:
If either or both of the conditions above are false, then SQLite uses the traditional one-at-a-time processing strategy for the IN constraint. If both conditions are true, then the argvIndex-th parameter to the xFilter method will be an sqlite3_value that appears to be NULL, but which can be passed to sqlite3_vtab_in_first() and sqlite3_vtab_in_next() to find all values on the right-hand side of the IN constraint. Determine If Virtual Table Column Access Is For UPDATEint sqlite3_vtab_nochange(sqlite3_context*); If the sqlite3_vtab_nochange(X) routine is called within the xColumn method of a virtual table, then it might return true if the column is being fetched as part of an UPDATE operation during which the column value will not change. The virtual table implementation can use this hint as permission to substitute a return value that is less expensive to compute and that the corresponding xUpdate method understands as a "no-change" value. If the xColumn method calls sqlite3_vtab_nochange() and finds that the column is not changed by the UPDATE statement, then the xColumn method can optionally return without setting a result, without calling any of the sqlite3_result_xxxxx() interfaces. In that case, sqlite3_value_nochange(X) will return true for the same column in the xUpdate method. The sqlite3_vtab_nochange() routine is an optimization. Virtual table implementations should continue to give a correct answer even if the sqlite3_vtab_nochange() interface were to always return false. In the current implementation, the sqlite3_vtab_nochange() interface does always returns false for the enhanced UPDATE FROM statement. Determine The Virtual Table Conflict Policyint sqlite3_vtab_on_conflict(sqlite3 *); This function may only be called from within a call to the xUpdate method of a virtual table implementation for an INSERT or UPDATE operation. The value returned is one of SQLITE_ROLLBACK, SQLITE_IGNORE, SQLITE_FAIL, SQLITE_ABORT, or SQLITE_REPLACE, according to the ON CONFLICT mode of the SQL statement that triggered the call to the xUpdate method of the virtual table. Constraint values in xBestIndex()int sqlite3_vtab_rhs_value(sqlite3_index_info*, int, sqlite3_value **ppVal); This API may only be used from within the xBestIndex method of a virtual table implementation. The result of calling this interface from outside of an xBestIndex method are undefined and probably harmful. When the sqlite3_vtab_rhs_value(P,J,V) interface is invoked from within the xBestIndex method of a virtual table implementation, with P being a copy of the sqlite3_index_info object pointer passed into xBestIndex and J being a 0-based index into P->aConstraint[], then this routine attempts to set *V to the value of the right-hand operand of that constraint if the right-hand operand is known. If the right-hand operand is not known, then *V is set to a NULL pointer. The sqlite3_vtab_rhs_value(P,J,V) interface returns SQLITE_OK if and only if *V is set to a value. The sqlite3_vtab_rhs_value(P,J,V) inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th constraint is not available. The sqlite3_vtab_rhs_value() interface can return a result code other than SQLITE_OK or SQLITE_NOTFOUND if something goes wrong. The sqlite3_vtab_rhs_value() interface is usually only successful if the right-hand operand of a constraint is a literal value in the original SQL statement. If the right-hand operand is an expression or a reference to some other column or a host parameter, then sqlite3_vtab_rhs_value() will probably return SQLITE_NOTFOUND. Some constraints, such as SQLITE_INDEX_CONSTRAINT_ISNULL and SQLITE_INDEX_CONSTRAINT_ISNOTNULL, have no right-hand operand. For such constraints, sqlite3_vtab_rhs_value() always returns SQLITE_NOTFOUND. The sqlite3_value object returned in *V is a protected sqlite3_value and remains valid for the duration of the xBestIndex method call. When xBestIndex returns, the sqlite3_value object returned by sqlite3_vtab_rhs_value() is automatically deallocated. The "_rhs_" in the name of this routine is an abbreviation for "Right-Hand Side". Configure an auto-checkpointint sqlite3_wal_autocheckpoint(sqlite3 *db, int N); The sqlite3_wal_autocheckpoint(D,N) is a wrapper around sqlite3_wal_hook() that causes any database on database connection D to automatically checkpoint after committing a transaction if there are N or more frames in the write-ahead log file. Passing zero or a negative value as the N parameter disables automatic checkpoints entirely. The callback registered by this function replaces any existing callback registered using sqlite3_wal_hook(). Likewise, registering a callback using sqlite3_wal_hook() disables the automatic checkpoint mechanism configured by this function. The wal_autocheckpoint pragma can be used to invoke this interface from SQL. Checkpoints initiated by this mechanism are PASSIVE. Every new database connection defaults to having the auto-checkpoint enabled with a threshold of 1000 or SQLITE_DEFAULT_WAL_AUTOCHECKPOINT pages. The use of this interface is only necessary if the default setting is found to be suboptimal for a particular application. Checkpoint a databaseint sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb); The sqlite3_wal_checkpoint(D,X) is equivalent to sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). In brief, sqlite3_wal_checkpoint(D,X) causes the content in the write-ahead log for database X on database connection D to be transferred into the database file and for the write-ahead log to be reset. See the checkpointing documentation for addition information. This interface used to be the only way to cause a checkpoint to occur. But then the newer and more powerful sqlite3_wal_checkpoint_v2() interface was added. This interface is retained for backwards compatibility and as a convenience for applications that need to manually start a callback but which do not need the full power (and corresponding complication) of sqlite3_wal_checkpoint_v2(). Checkpoint a databaseint sqlite3_wal_checkpoint_v2( sqlite3 *db, /* Database handle */ const char *zDb, /* Name of attached database (or NULL) */ int eMode, /* SQLITE_CHECKPOINT_* value */ int *pnLog, /* OUT: Size of WAL log in frames */ int *pnCkpt /* OUT: Total number of frames checkpointed */ ); The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint operation on database X of database connection D in mode M. Status information is written back into integers pointed to by L and C. The M parameter must be a valid checkpoint mode:
If pnLog is not NULL, then *pnLog is set to the total number of frames in the log file or to -1 if the checkpoint could not run because of an error or because the database is not in WAL mode. If pnCkpt is not NULL,then *pnCkpt is set to the total number of checkpointed frames in the log file (including any that were already checkpointed before the function was called) or to -1 if the checkpoint could not run due to an error or because the database is not in WAL mode. Note that upon successful completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero. All calls obtain an exclusive "checkpoint" lock on the database file. If any other process is running a checkpoint operation at the same time, the lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a busy-handler configured, it will not be invoked in this case. The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the exclusive "writer" lock on the database file. If the writer lock cannot be obtained immediately, and a busy-handler is configured, it is invoked and the writer lock retried until either the busy-handler returns 0 or the lock is successfully obtained. The busy-handler is also invoked while waiting for database readers as described above. If the busy-handler returns 0 before the writer lock is obtained or while waiting for database readers, the checkpoint operation proceeds from that point in the same way as SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible without blocking any further. SQLITE_BUSY is returned in this case. If parameter zDb is NULL or points to a zero length string, then the specified operation is attempted on all WAL databases attached to database connection db. In this case the values written to output parameters *pnLog and *pnCkpt are undefined. If an SQLITE_BUSY error is encountered when processing one or more of the attached WAL databases, the operation is still attempted on any remaining attached databases and SQLITE_BUSY is returned at the end. If any other error occurs while processing an attached database, processing is abandoned and the error code is returned to the caller immediately. If no error (SQLITE_BUSY or otherwise) is encountered while processing the attached databases, SQLITE_OK is returned. If database zDb is the name of an attached database that is not in WAL mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If zDb is not NULL (or a zero length string) and is not the name of any attached database, SQLITE_ERROR is returned to the caller. Unless it returns SQLITE_MISUSE, the sqlite3_wal_checkpoint_v2() interface sets the error information that is queried by sqlite3_errcode() and sqlite3_errmsg(). The PRAGMA wal_checkpoint command can be used to invoke this interface from SQL. Write-Ahead Log Commit Hookvoid *sqlite3_wal_hook( sqlite3*, int(*)(void *,sqlite3*,const char*,int), void* ); The sqlite3_wal_hook() function is used to register a callback that is invoked each time data is committed to a database in wal mode. The callback is invoked by SQLite after the commit has taken place and the associated write-lock on the database released, so the implementation may read, write or checkpoint the database as required. The first parameter passed to the callback function when it is invoked is a copy of the third parameter passed to sqlite3_wal_hook() when registering the callback. The second is a copy of the database handle. The third parameter is the name of the database that was written to - either "main" or the name of an ATTACH-ed database. The fourth parameter is the number of pages currently in the write-ahead log file, including those that were just committed. The callback function should normally return SQLITE_OK. If an error code is returned, that error will propagate back up through the SQLite code base to cause the statement that provoked the callback to report an error, though the commit will have still occurred. If the callback returns SQLITE_ROW or SQLITE_DONE, or if it returns a value that does not correspond to any valid SQLite error code, the results are undefined. A single database handle may have at most a single write-ahead log callback registered at one time. Calling sqlite3_wal_hook() replaces the default behavior or previously registered write-ahead log callback. The return value is a copy of the third parameter from the previous call, if any, or 0. The sqlite3_wal_autocheckpoint() interface and the wal_autocheckpoint pragma both invoke sqlite3_wal_hook() and will overwrite any prior sqlite3_wal_hook() settings. If a write-ahead log callback is set using this function then sqlite3_wal_checkpoint_v2() or PRAGMA wal_checkpoint should be invoked periodically to keep the write-ahead log file from growing without bound. Passing a NULL pointer for the callback disables automatic checkpointing entirely. To re-enable the default behavior, call sqlite3_wal_autocheckpoint(db,1000) or use PRAGMA wal_checkpoint. Result Codes#define SQLITE_OK 0 /* Successful result */ /* beginning-of-error-codes */ #define SQLITE_ERROR 1 /* Generic error */ #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */ #define SQLITE_PERM 3 /* Access permission denied */ #define SQLITE_ABORT 4 /* Callback routine requested an abort */ #define SQLITE_BUSY 5 /* The database file is locked */ #define SQLITE_LOCKED 6 /* A table in the database is locked */ #define SQLITE_NOMEM 7 /* A malloc() failed */ #define SQLITE_READONLY 8 /* Attempt to write a readonly database */ #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/ #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */ #define SQLITE_CORRUPT 11 /* The database disk image is malformed */ #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */ #define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */ #define SQLITE_EMPTY 16 /* No content */ #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 /* Not used */ #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_NOTICE 27 /* Notifications from sqlite3_log() */ #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */ #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */ #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */ /* end-of-error-codes */ Many SQLite functions return an integer result code from the set shown here in order to indicate success or failure. New error codes may be added in future versions of SQLite. See also: extended result code definitions Extended Result Codes#define SQLITE_ERROR_MISSING_COLLSEQ (SQLITE_ERROR | (1<<8)) #define SQLITE_ERROR_RETRY (SQLITE_ERROR | (2<<8)) #define SQLITE_ERROR_SNAPSHOT (SQLITE_ERROR | (3<<8)) #define SQLITE_ERROR_RESERVESIZE (SQLITE_ERROR | (4<<8)) #define SQLITE_ERROR_KEY (SQLITE_ERROR | (5<<8)) #define SQLITE_ERROR_UNABLE (SQLITE_ERROR | (6<<8)) #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8)) #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8)) #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8)) #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8)) #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8)) #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8)) #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8)) #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8)) #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8)) #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8)) #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8)) #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8)) #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8)) #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8)) #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8)) #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8)) #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8)) #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8)) #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8)) #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8)) #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8)) #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8)) #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8)) #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8)) #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8)) #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) #define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8)) #define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8)) #define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8)) #define SQLITE_IOERR_DATA (SQLITE_IOERR | (32<<8)) #define SQLITE_IOERR_CORRUPTFS (SQLITE_IOERR | (33<<8)) #define SQLITE_IOERR_IN_PAGE (SQLITE_IOERR | (34<<8)) #define SQLITE_IOERR_BADKEY (SQLITE_IOERR | (35<<8)) #define SQLITE_IOERR_CODEC (SQLITE_IOERR | (36<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_LOCKED_VTAB (SQLITE_LOCKED | (2<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_BUSY_TIMEOUT (SQLITE_BUSY | (3<<8)) #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8)) #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8)) #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8)) #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8)) #define SQLITE_CANTOPEN_DIRTYWAL (SQLITE_CANTOPEN | (5<<8)) /* Not Used */ #define SQLITE_CANTOPEN_SYMLINK (SQLITE_CANTOPEN | (6<<8)) #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8)) #define SQLITE_CORRUPT_SEQUENCE (SQLITE_CORRUPT | (2<<8)) #define SQLITE_CORRUPT_INDEX (SQLITE_CORRUPT | (3<<8)) #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8)) #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8)) #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8)) #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8)) #define SQLITE_READONLY_CANTINIT (SQLITE_READONLY | (5<<8)) #define SQLITE_READONLY_DIRECTORY (SQLITE_READONLY | (6<<8)) #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8)) #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8)) #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8)) #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8)) #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8)) #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8)) #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8)) #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8)) #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8)) #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8)) #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8)) #define SQLITE_CONSTRAINT_PINNED (SQLITE_CONSTRAINT |(11<<8)) #define SQLITE_CONSTRAINT_DATATYPE (SQLITE_CONSTRAINT |(12<<8)) #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8)) #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8)) #define SQLITE_NOTICE_RBU (SQLITE_NOTICE | (3<<8)) #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8)) #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8)) #define SQLITE_OK_LOAD_PERMANENTLY (SQLITE_OK | (1<<8)) #define SQLITE_OK_SYMLINK (SQLITE_OK | (2<<8)) /* internal only */ In its default configuration, SQLite API routines return one of 30 integer result codes. However, experience has shown that many of these result codes are too coarse-grained. They do not provide as much information about problems as programmers might like. In an effort to address this, newer versions of SQLite (version 3.3.8 2006-10-09 and later) include support for additional result codes that provide more detailed information about errors. These extended result codes are enabled or disabled on a per database connection basis using the sqlite3_extended_result_codes() API. Or, the extended code for the most recent error can be obtained using sqlite3_extended_errcode(). Flags for the xAccess VFS method#define SQLITE_ACCESS_EXISTS 0 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */ #define SQLITE_ACCESS_READ 2 /* Unused */ These integer constants can be used as the third parameter to the xAccess method of an sqlite3_vfs object. They determine what kind of permissions the xAccess method is looking for. With SQLITE_ACCESS_EXISTS, the xAccess method simply checks whether the file exists. With SQLITE_ACCESS_READWRITE, the xAccess method checks whether the named directory is both readable and writable (in other words, if files can be added, removed, and renamed within the directory). The SQLITE_ACCESS_READWRITE constant is currently used only by the temp_store_directory pragma, though this could change in a future release of SQLite. With SQLITE_ACCESS_READ, the xAccess method checks whether the file is readable. The SQLITE_ACCESS_READ constant is currently unused, though it might be used in a future release of SQLite. Authorizer Action Codes/******************************************* 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 /* Operation 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 /* NULL Function Name */ #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */ #define SQLITE_RECURSIVE 33 /* NULL NULL */ The sqlite3_set_authorizer() interface registers a callback function that is invoked to authorize 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. The case of strings in the 3rd through the 6th argument to the authorization callback is arbitrary. Authorization callbacks implementations should use sqlite3_stricmp() or similar when doing comparisons against those values. Text Encodings#define SQLITE_UTF8 1 /* IMP: R-37514-35566 */ #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */ #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */ #define SQLITE_UTF16 4 /* Use native byte order */ #define SQLITE_ANY 5 /* Deprecated */ #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */ #define SQLITE_UTF8_ZT 16 /* Zero-terminated UTF8 */ These constants define integer codes that represent the various text encodings supported by SQLite.
Fundamental Datatypes#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 Every value in SQLite has one of five fundamental datatypes:
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. Datatypes for the CARRAY table-valued function#define SQLITE_CARRAY_INT32 0 /* Data is 32-bit signed integers */ #define SQLITE_CARRAY_INT64 1 /* Data is 64-bit signed integers */ #define SQLITE_CARRAY_DOUBLE 2 /* Data is doubles */ #define SQLITE_CARRAY_TEXT 3 /* Data is char* */ #define SQLITE_CARRAY_BLOB 4 /* Data is struct iovec */ The fifth argument to the sqlite3_carray_bind() interface musts be one of the following constants, to specify the datatype of the array that is being bound into the carray table-valued function. Checkpoint Mode Values#define SQLITE_CHECKPOINT_NOOP -1 /* Do no work at all */ #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */ #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */ #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for readers */ #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */ These constants define all valid values for the "checkpoint mode" passed as the third parameter to the sqlite3_wal_checkpoint_v2() interface. See the sqlite3_wal_checkpoint_v2() documentation for details on the meaning of each of these checkpoint modes. Configuration Options#define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */ #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */ #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_SCRATCH 6 /* No longer used */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */ #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */ /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */ #define SQLITE_CONFIG_PCACHE 14 /* no-op */ #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */ #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */ #define SQLITE_CONFIG_URI 17 /* int */ #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */ #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */ #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */ #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */ #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ #define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */ #define SQLITE_CONFIG_SORTERREF_SIZE 28 /* int nByte */ #define SQLITE_CONFIG_MEMDB_MAXSIZE 29 /* sqlite3_int64 */ #define SQLITE_CONFIG_ROWID_IN_VIEW 30 /* int* */ These constants are the available integer configuration options that can be passed as the first argument to the sqlite3_config() interface. Most of the configuration options for sqlite3_config() will only work if invoked prior to sqlite3_initialize() or after sqlite3_shutdown(). The few exceptions to this rule are called "anytime configuration options". Calling sqlite3_config() with a first argument that is not an anytime configuration option in between calls to sqlite3_initialize() and sqlite3_shutdown() is a no-op that returns SQLITE_MISUSE. The set of anytime configuration options can change (by insertions and/or deletions) from one release of SQLite to the next. As of SQLite version 3.42.0, the complete set of anytime configuration options is:
New configuration options may be added in future releases of SQLite. Existing configuration options might be discontinued. Applications should check the return code from sqlite3_config() to make sure that the call worked. The sqlite3_config() interface will return a non-zero error code if a discontinued or unsupported configuration option is invoked.
Control Flags For sqlite3_result_str()#define SQLITE_COPY 0 /* Results copied. Dynamic string unchanged */ #define SQLITE_XFER 1 /* Results transfered. Dynamic string reset */ #define SQLITE_FINISH 2 /* Like SQLITE_XFER, plus dynamic string freed */ The following integers can be used as the third "F" argument to sqlite3_result_str(C,S,F). Database Connection Configuration Options#define SQLITE_DBCONFIG_MAINDBNAME 1000 /* const char* */ #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */ #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */ #define SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE 1006 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_QPSG 1007 /* int int* */ #define SQLITE_DBCONFIG_TRIGGER_EQP 1008 /* int int* */ #define SQLITE_DBCONFIG_RESET_DATABASE 1009 /* int int* */ #define SQLITE_DBCONFIG_DEFENSIVE 1010 /* int int* */ #define SQLITE_DBCONFIG_WRITABLE_SCHEMA 1011 /* int int* */ #define SQLITE_DBCONFIG_LEGACY_ALTER_TABLE 1012 /* int int* */ #define SQLITE_DBCONFIG_DQS_DML 1013 /* int int* */ #define SQLITE_DBCONFIG_DQS_DDL 1014 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_VIEW 1015 /* int int* */ #define SQLITE_DBCONFIG_LEGACY_FILE_FORMAT 1016 /* int int* */ #define SQLITE_DBCONFIG_TRUSTED_SCHEMA 1017 /* int int* */ #define SQLITE_DBCONFIG_STMT_SCANSTATUS 1018 /* int int* */ #define SQLITE_DBCONFIG_REVERSE_SCANORDER 1019 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE 1020 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE 1021 /* int int* */ #define SQLITE_DBCONFIG_ENABLE_COMMENTS 1022 /* int int* */ #define SQLITE_DBCONFIG_FP_DIGITS 1023 /* int int* */ #define SQLITE_DBCONFIG_MAX 1023 /* Largest DBCONFIG */ These constants are the available integer configuration options that can be passed as the second parameter to the sqlite3_db_config() interface. The sqlite3_db_config() interface is a var-args function. It takes a variable number of parameters, though always at least two. The number of parameters passed into sqlite3_db_config() depends on which of these constants is given as the second parameter. This documentation page refers to parameters beyond the second as "arguments". Thus, when this page says "the N-th argument" it means "the N-th parameter past the configuration option" or "the (N+2)-th parameter to sqlite3_db_config()". New configuration options may be added in future releases of SQLite. Existing configuration options might be discontinued. Applications should check the return code from sqlite3_db_config() to make sure that the call worked. The sqlite3_db_config() interface will return a non-zero error code if a discontinued or unsupported configuration option is invoked.
Arguments To SQLITE_DBCONFIG OptionsMost of the SQLITE_DBCONFIG options take two arguments, so that the overall call to sqlite3_db_config() has a total of four parameters. The first argument (the third parameter to sqlite3_db_config()) is an integer. The second argument is a pointer to an integer. If the first argument is 1, then the option becomes enabled. If the first integer argument is 0, then the option is disabled. If the first argument is -1, then the option setting is unchanged. The second argument, the pointer to an integer, may be NULL. If the second argument is not NULL, then a value of 0 or 1 is written into the integer to which the second argument points, depending on whether the setting is disabled or enabled after applying any changes specified by the first argument. While most SQLITE_DBCONFIG options use the argument format described in the previous paragraph, the SQLITE_DBCONFIG_MAINDBNAME, SQLITE_DBCONFIG_LOOKASIDE, and SQLITE_DBCONFIG_FP_DIGITS options are different. See the documentation of those exceptional options for details. Authorizer Return Codes#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 */ The 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 authorizer documentation for additional information. Note that SQLITE_IGNORE is also used as a conflict resolution mode returned from the sqlite3_vtab_on_conflict() interface. Flags for sqlite3_deserialize()#define SQLITE_DESERIALIZE_FREEONCLOSE 1 /* Call sqlite3_free() on close */ #define SQLITE_DESERIALIZE_RESIZEABLE 2 /* Resize using sqlite3_realloc64() */ #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */ The following are allowed values for the 6th argument (the F argument) to the sqlite3_deserialize(D,S,P,N,M,F) interface. The SQLITE_DESERIALIZE_FREEONCLOSE means that the database serialization in the P argument is held in memory obtained from sqlite3_malloc64() and that SQLite should take ownership of this memory and automatically free it when it has finished using it. Without this flag, the caller is responsible for freeing any dynamically allocated memory. The SQLITE_DESERIALIZE_RESIZEABLE flag means that SQLite is allowed to grow the size of the database using calls to sqlite3_realloc64(). This flag should only be used if SQLITE_DESERIALIZE_FREEONCLOSE is also used. Without this flag, the deserialized database cannot increase in size beyond the number of bytes specified by the M parameter. The SQLITE_DESERIALIZE_READONLY flag means that the deserialized database should be treated as read-only. Function Flags#define SQLITE_DETERMINISTIC 0x000000800 #define SQLITE_DIRECTONLY 0x000080000 #define SQLITE_SUBTYPE 0x000100000 #define SQLITE_INNOCUOUS 0x000200000 #define SQLITE_RESULT_SUBTYPE 0x001000000 #define SQLITE_SELFORDER1 0x002000000 These constants may be ORed together with the preferred text encoding as the fourth argument to sqlite3_create_function(), sqlite3_create_function16(), or sqlite3_create_function_v2().
Conflict resolution modes#define SQLITE_ROLLBACK 1 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */ #define SQLITE_FAIL 3 /* #define SQLITE_ABORT 4 // Also an error code */ #define SQLITE_REPLACE 5 These constants are returned by sqlite3_vtab_on_conflict() to inform a virtual table implementation of the ON CONFLICT mode for the SQL statement being evaluated. Note that the SQLITE_IGNORE constant is also used as a potential return value from the sqlite3_set_authorizer() callback and that SQLITE_ABORT is also a result code. Standard File Control Opcodes#define SQLITE_FCNTL_LOCKSTATE 1 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3 #define SQLITE_FCNTL_LAST_ERRNO 4 #define SQLITE_FCNTL_SIZE_HINT 5 #define SQLITE_FCNTL_CHUNK_SIZE 6 #define SQLITE_FCNTL_FILE_POINTER 7 #define SQLITE_FCNTL_SYNC_OMITTED 8 #define SQLITE_FCNTL_WIN32_AV_RETRY 9 #define SQLITE_FCNTL_PERSIST_WAL 10 #define SQLITE_FCNTL_OVERWRITE 11 #define SQLITE_FCNTL_VFSNAME 12 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13 #define SQLITE_FCNTL_PRAGMA 14 #define SQLITE_FCNTL_BUSYHANDLER 15 #define SQLITE_FCNTL_TEMPFILENAME 16 #define SQLITE_FCNTL_MMAP_SIZE 18 #define SQLITE_FCNTL_TRACE 19 #define SQLITE_FCNTL_HAS_MOVED 20 #define SQLITE_FCNTL_SYNC 21 #define SQLITE_FCNTL_COMMIT_PHASETWO 22 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23 #define SQLITE_FCNTL_WAL_BLOCK 24 #define SQLITE_FCNTL_ZIPVFS 25 #define SQLITE_FCNTL_RBU 26 #define SQLITE_FCNTL_VFS_POINTER 27 #define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29 #define SQLITE_FCNTL_PDB 30 #define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31 #define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32 #define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33 #define SQLITE_FCNTL_LOCK_TIMEOUT 34 #define SQLITE_FCNTL_DATA_VERSION 35 #define SQLITE_FCNTL_SIZE_LIMIT 36 #define SQLITE_FCNTL_CKPT_DONE 37 #define SQLITE_FCNTL_RESERVE_BYTES 38 #define SQLITE_FCNTL_CKPT_START 39 #define SQLITE_FCNTL_EXTERNAL_READER 40 #define SQLITE_FCNTL_CKSM_FILE 41 #define SQLITE_FCNTL_RESET_CACHE 42 #define SQLITE_FCNTL_NULL_IO 43 #define SQLITE_FCNTL_BLOCK_ON_CONNECT 44 #define SQLITE_FCNTL_FILESTAT 45 These integer constants are opcodes for the xFileControl method of the sqlite3_io_methods object and for the sqlite3_file_control() interface.
Virtual Table Constraint Operator Codes#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 #define SQLITE_INDEX_CONSTRAINT_LIKE 65 #define SQLITE_INDEX_CONSTRAINT_GLOB 66 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67 #define SQLITE_INDEX_CONSTRAINT_NE 68 #define SQLITE_INDEX_CONSTRAINT_ISNOT 69 #define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70 #define SQLITE_INDEX_CONSTRAINT_ISNULL 71 #define SQLITE_INDEX_CONSTRAINT_IS 72 #define SQLITE_INDEX_CONSTRAINT_LIMIT 73 #define SQLITE_INDEX_CONSTRAINT_OFFSET 74 #define SQLITE_INDEX_CONSTRAINT_FUNCTION 150 These macros define the allowed values for the sqlite3_index_info.aConstraint[].op field. Each value represents an operator that is part of a constraint term in the WHERE clause of a query that uses a virtual table. The left-hand operand of the operator is given by the corresponding aConstraint[].iColumn field. An iColumn of -1 indicates the left-hand operand is the rowid. The SQLITE_INDEX_CONSTRAINT_LIMIT and SQLITE_INDEX_CONSTRAINT_OFFSET operators have no left-hand operand, and so for those operators the corresponding aConstraint[].iColumn is meaningless and should not be used. All operator values from SQLITE_INDEX_CONSTRAINT_FUNCTION through value 255 are reserved to represent functions that are overloaded by the xFindFunction method of the virtual table implementation. The right-hand operands for each constraint might be accessible using the sqlite3_vtab_rhs_value() interface. Usually the right-hand operand is only available if it appears as a single constant literal in the input SQL. If the right-hand operand is another column or an expression (even a constant expression) or a parameter, then the sqlite3_vtab_rhs_value() probably will not be able to extract it. The SQLITE_INDEX_CONSTRAINT_ISNULL and SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand and hence calls to sqlite3_vtab_rhs_value() for those operators will always return SQLITE_NOTFOUND. The collating sequence to be used for comparison can be found using the sqlite3_vtab_collation() interface. For most real-world virtual tables, the collating sequence of constraints does not matter (for example because the constraints are numeric) and so the sqlite3_vtab_collation() interface is not commonly needed. Virtual Table Scan Flags
Virtual table implementations are allowed to set the sqlite3_index_info.idxFlags field to some combination of these bits. Device Characteristics#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 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000 #define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000 #define SQLITE_IOCAP_SUBPAGE_READ 0x00008000 The xDeviceCharacteristics method of the sqlite3_io_methods object returns an integer which is a vector of 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(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that after reboot following a crash or power loss, the only bytes in a file that were written at the application level might have changed and that adjacent bytes, even bytes within the same sector are guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN flag indicates that a file cannot be deleted when open. The SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on read-only media and cannot be changed even by processes with elevated privileges. The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying filesystem supports doing multiple write operations atomically when those write operations are bracketed by SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and SQLITE_FCNTL_COMMIT_ATOMIC_WRITE. The SQLITE_IOCAP_SUBPAGE_READ property means that it is ok to read from the database file in amounts that are not a multiple of the page size and that do not begin at a page boundary. Without this property, SQLite is careful to only do full-page reads and write on aligned pages, with the one exception that it will do a sub-page read of the first page to access the database header. File Locking Levels#define SQLITE_LOCK_NONE 0 /* xUnlock() only */ #define SQLITE_LOCK_SHARED 1 /* xLock() or xUnlock() */ #define SQLITE_LOCK_RESERVED 2 /* xLock() only */ #define SQLITE_LOCK_PENDING 3 /* xLock() only */ #define SQLITE_LOCK_EXCLUSIVE 4 /* xLock() only */ 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. These values are ordered from least restrictive to most restrictive. The argument to xLock() is always SHARED or higher. The argument to xUnlock is either SHARED or NONE. Mutex Types#define SQLITE_MUTEX_FAST 0 #define SQLITE_MUTEX_RECURSIVE 1 #define SQLITE_MUTEX_STATIC_MAIN 2 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */ #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */ #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */ #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_randomness() */ #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */ #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */ #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */ #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */ #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */ #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */ #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */ #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */ The sqlite3_mutex_alloc() interface takes a single argument which is one of these integer constants. The set of static mutexes may change from one SQLite release to the next. Applications that override the built-in mutex logic must be prepared to accommodate additional static mutexes. Flags For File Open Operations#define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */ #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */ #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */ #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */ #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */ #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */ #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */ #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */ #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */ #define SQLITE_OPEN_SUPER_JOURNAL 0x00004000 /* VFS only */ #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */ #define SQLITE_OPEN_NOFOLLOW 0x01000000 /* Ok for sqlite3_open_v2() */ #define SQLITE_OPEN_EXRESCODE 0x02000000 /* Extended result codes */ These bit values are intended for use in the 3rd parameter to the sqlite3_open_v2() interface and in the 4th parameter to the sqlite3_vfs.xOpen method. Only those flags marked as "Ok for sqlite3_open_v2()" may be used as the third argument to the sqlite3_open_v2() interface. The other flags have historically been ignored by sqlite3_open_v2(), though future versions of SQLite might change so that an error is raised if any of the disallowed bits are passed into sqlite3_open_v2(). Applications should not depend on the historical behavior. Note in particular that passing the SQLITE_OPEN_EXCLUSIVE flag into sqlite3_open_v2() does *not* cause the underlying database file to be opened using O_EXCL. Passing SQLITE_OPEN_EXCLUSIVE into sqlite3_open_v2() has historically been a no-op and might become an error in future versions of SQLite. Prepare Flags#define SQLITE_PREPARE_PERSISTENT 0x01 #define SQLITE_PREPARE_NORMALIZE 0x02 #define SQLITE_PREPARE_NO_VTAB 0x04 #define SQLITE_PREPARE_DONT_LOG 0x10 #define SQLITE_PREPARE_FROM_DDL 0x20 These constants define various flags that can be passed into the "prepFlags" parameter of the sqlite3_prepare_v3() and sqlite3_prepare16_v3() interfaces. New flags may be added in future releases of SQLite.
Prepared Statement Scan Status#define SQLITE_SCANSTAT_COMPLEX 0x0001 Prepared Statement Scan Status Opcodes#define SQLITE_SCANSTAT_NLOOP 0 #define SQLITE_SCANSTAT_NVISIT 1 #define SQLITE_SCANSTAT_EST 2 #define SQLITE_SCANSTAT_NAME 3 #define SQLITE_SCANSTAT_EXPLAIN 4 #define SQLITE_SCANSTAT_SELECTID 5 #define SQLITE_SCANSTAT_PARENTID 6 #define SQLITE_SCANSTAT_NCYCLE 7 The following constants can be used for the T parameter to the sqlite3_stmt_scanstatus(S,X,T,V) interface. Each constant designates a different metric for sqlite3_stmt_scanstatus() to return. When the value returned to V is a string, space to hold that string is managed by the prepared statement S and will be automatically freed when S is finalized. Not all values are available for all query elements. When a value is not available, the output variable is set to -1 if the value is numeric, or to NULL if it is a string (SQLITE_SCANSTAT_NAME).
Compile-Time Library Version Numbers#define SQLITE_VERSION "3.54.1" #define SQLITE_VERSION_NUMBER 3054001 #define SQLITE_SOURCE_ID "2026-10-16 14:45:20 555e07ef33f69a0957d24d8e555b702464a131d6f1607f4c3c1e4551e8e6ca76" #define SQLITE_SCM_BRANCH "branch-3.54" #define SQLITE_SCM_TAGS "release version-3.54.1" #define SQLITE_SCM_DATETIME "2026-10-16T14:45:20.546Z" The SQLITE_VERSION C preprocessor macro in the sqlite3.h header evaluates to a string literal that is the SQLite version in the format "X.Y.Z" where X is the major version number (always 3 for SQLite3) and Y is the minor version number and Z is the release number. The SQLITE_VERSION_NUMBER C preprocessor macro resolves to an integer with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same numbers used in SQLITE_VERSION. The SQLITE_VERSION_NUMBER for any given release of SQLite will also be larger than the release from which it is derived. Either Y will be held constant and Z will be incremented or else Y will be incremented and Z will be reset to zero. Since version 3.6.18 (2009-09-11), SQLite source code has been stored in the Fossil configuration management system. The SQLITE_SOURCE_ID macro evaluates to a string which identifies a particular check-in of SQLite within its configuration management system. The SQLITE_SOURCE_ID string contains the date and time of the check-in (UTC) and a SHA1 or SHA3-256 hash of the entire source tree. If the source code has been edited in any way since it was last checked in, then the last four hexadecimal digits of the hash may be modified. See also: sqlite3_libversion(), sqlite3_libversion_number(), sqlite3_sourceid(), sqlite_version() and sqlite_source_id(). Flags for the xShmLock VFS method#define SQLITE_SHM_UNLOCK 1 #define SQLITE_SHM_LOCK 2 #define SQLITE_SHM_SHARED 4 #define SQLITE_SHM_EXCLUSIVE 8 These integer constants define the various locking operations allowed by the xShmLock method of sqlite3_io_methods. The following are the only legal combinations of flags to the xShmLock method:
When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as was given on the corresponding lock. The xShmLock method can transition between unlocked and SHARED or between unlocked and EXCLUSIVE. It cannot transition between SHARED and EXCLUSIVE. Constants Defining Special Destructor Behaviortypedef void (*sqlite3_destructor_type)(void*); #define SQLITE_STATIC ((sqlite3_destructor_type)0) #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1) These are special values 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. Status Parameters#define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 #define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */ #define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */ #define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PAGECACHE_SIZE 7 #define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */ #define SQLITE_STATUS_MALLOC_COUNT 9 These integer constants designate various run-time status parameters that can be returned by sqlite3_status().
New status parameters may be added from time to time. Synchronization Type Flags#define SQLITE_SYNC_NORMAL 0x00002 #define SQLITE_SYNC_FULL 0x00003 #define SQLITE_SYNC_DATAONLY 0x00010 When SQLite invokes the xSync() method of an sqlite3_io_methods object it uses a combination of 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. If the lower four bits of the flag equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics. If the lower four bits equal SQLITE_SYNC_FULL, that means to use Mac OS X style fullsync instead of fsync(). Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags with the PRAGMA synchronous=NORMAL and PRAGMA synchronous=FULL settings. The synchronous pragma determines when calls to the xSync VFS method occur and applies uniformly across all platforms. The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how energetic or rigorous or forceful the sync operations are and only make a difference on Mac OSX for the default SQLite code. (Third-party VFS implementations might also make the distinction between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the operating systems natively supported by SQLite, only Mac OSX cares about the difference.) Testing Interface Operation Codes#define SQLITE_TESTCTRL_FIRST 5 #define SQLITE_TESTCTRL_PRNG_SAVE 5 #define SQLITE_TESTCTRL_PRNG_RESTORE 6 #define SQLITE_TESTCTRL_PRNG_RESET 7 /* NOT USED */ #define SQLITE_TESTCTRL_FK_NO_ACTION 7 #define SQLITE_TESTCTRL_BITVEC_TEST 8 #define SQLITE_TESTCTRL_FAULT_INSTALL 9 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10 #define SQLITE_TESTCTRL_PENDING_BYTE 11 #define SQLITE_TESTCTRL_ASSERT 12 #define SQLITE_TESTCTRL_ALWAYS 13 #define SQLITE_TESTCTRL_RESERVE 14 /* NOT USED */ #define SQLITE_TESTCTRL_JSON_SELFCHECK 14 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15 #define SQLITE_TESTCTRL_ISKEYWORD 16 /* NOT USED */ #define SQLITE_TESTCTRL_GETOPT 16 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */ #define SQLITE_TESTCTRL_INTERNAL_FUNCTIONS 17 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21 #define SQLITE_TESTCTRL_BYTEORDER 22 #define SQLITE_TESTCTRL_ISINIT 23 #define SQLITE_TESTCTRL_SORTER_MMAP 24 #define SQLITE_TESTCTRL_IMPOSTER 25 #define SQLITE_TESTCTRL_PARSER_COVERAGE 26 #define SQLITE_TESTCTRL_RESULT_INTREAL 27 #define SQLITE_TESTCTRL_PRNG_SEED 28 #define SQLITE_TESTCTRL_EXTRA_SCHEMA_CHECKS 29 #define SQLITE_TESTCTRL_SEEK_COUNT 30 #define SQLITE_TESTCTRL_TRACEFLAGS 31 #define SQLITE_TESTCTRL_TUNE 32 #define SQLITE_TESTCTRL_LOGEST 33 #define SQLITE_TESTCTRL_USELONGDOUBLE 34 /* NOT USED */ #define SQLITE_TESTCTRL_ATOF 34 #define SQLITE_TESTCTRL_LAST 34 /* Largest TESTCTRL */ These constants are the valid operation code parameters used as the first argument to sqlite3_test_control(). These parameters and their meanings are subject to change without notice. These values are for testing purposes only. Applications should not use any of these parameters or the sqlite3_test_control() interface. SQL Trace Event Codes#define SQLITE_TRACE_STMT 0x01 #define SQLITE_TRACE_PROFILE 0x02 #define SQLITE_TRACE_ROW 0x04 #define SQLITE_TRACE_CLOSE 0x08 These constants identify classes of events that can be monitored using the sqlite3_trace_v2() tracing logic. The M argument to sqlite3_trace_v2(D,M,X,P) is an OR-ed combination of one or more of the following constants. The first argument to the trace callback is one of the following constants. New tracing constants may be added in future releases. A trace callback has four arguments: xCallback(T,C,P,X). The T argument is one of the integer type codes above. The C argument is a copy of the context pointer passed in as the fourth argument to sqlite3_trace_v2(). The P and X arguments are pointers whose meanings depend on T.
Allowed return values from sqlite3_txn_state()#define SQLITE_TXN_NONE 0 #define SQLITE_TXN_READ 1 #define SQLITE_TXN_WRITE 2 These constants define the current transaction state of a database file. The sqlite3_txn_state(D,S) interface returns one of these constants in order to describe the transaction state of schema S in database connection D.
Virtual Table Configuration Options#define SQLITE_VTAB_CONSTRAINT_SUPPORT 1 #define SQLITE_VTAB_INNOCUOUS 2 #define SQLITE_VTAB_DIRECTONLY 3 #define SQLITE_VTAB_USES_ALL_SCHEMAS 4 These macros define the various options to the sqlite3_vtab_config() interface that virtual table implementations can use to customize and optimize their behavior.
Win32 Directory Types#define SQLITE_WIN32_DATA_DIRECTORY_TYPE 1 #define SQLITE_WIN32_TEMP_DIRECTORY_TYPE 2 These macros are only available on Windows. They define the allowed values for the type argument to the sqlite3_win32_set_directory interface. Run-Time Limit Categories#define SQLITE_LIMIT_LENGTH 0 #define SQLITE_LIMIT_SQL_LENGTH 1 #define SQLITE_LIMIT_COLUMN 2 #define SQLITE_LIMIT_EXPR_DEPTH 3 #define SQLITE_LIMIT_COMPOUND_SELECT 4 #define SQLITE_LIMIT_VDBE_OP 5 #define SQLITE_LIMIT_FUNCTION_ARG 6 #define SQLITE_LIMIT_ATTACHED 7 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8 #define SQLITE_LIMIT_VARIABLE_NUMBER 9 #define SQLITE_LIMIT_TRIGGER_DEPTH 10 #define SQLITE_LIMIT_WORKER_THREADS 11 #define SQLITE_LIMIT_PARSER_DEPTH 12 #define SQLITE_LIMIT_SCHEMA 13 #define SQLITE_LIMIT_TRIGGER_STEPS 14 These constants define various performance limits that can be lowered at run-time using sqlite3_limit(). A concise description of these limits follows, and additional information is available at Limits in SQLite.
Status Parameters for database connections#define SQLITE_DBSTATUS_LOOKASIDE_USED 0 #define SQLITE_DBSTATUS_CACHE_USED 1 #define SQLITE_DBSTATUS_SCHEMA_USED 2 #define SQLITE_DBSTATUS_STMT_USED 3 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6 #define SQLITE_DBSTATUS_CACHE_HIT 7 #define SQLITE_DBSTATUS_CACHE_MISS 8 #define SQLITE_DBSTATUS_CACHE_WRITE 9 #define SQLITE_DBSTATUS_DEFERRED_FKS 10 #define SQLITE_DBSTATUS_CACHE_USED_SHARED 11 #define SQLITE_DBSTATUS_CACHE_SPILL 12 #define SQLITE_DBSTATUS_TEMPBUF_SPILL 13 #define SQLITE_DBSTATUS_MAX 13 /* Largest defined DBSTATUS */ These constants are the available integer "verbs" that can be passed as the second argument to the sqlite3_db_status() interface. New verbs may be added in future releases of SQLite. Existing verbs might be discontinued. Applications should check the return code from sqlite3_db_status() to make sure that the call worked. The sqlite3_db_status() interface will return a non-zero error code if a discontinued or unsupported verb is invoked.
Status Parameters for prepared statements#define SQLITE_STMTSTATUS_FULLSCAN_STEP 1 #define SQLITE_STMTSTATUS_SORT 2 #define SQLITE_STMTSTATUS_AUTOINDEX 3 #define SQLITE_STMTSTATUS_VM_STEP 4 #define SQLITE_STMTSTATUS_REPREPARE 5 #define SQLITE_STMTSTATUS_RUN 6 #define SQLITE_STMTSTATUS_FILTER_MISS 7 #define SQLITE_STMTSTATUS_FILTER_HIT 8 #define SQLITE_STMTSTATUS_MEMUSED 99 These preprocessor macros define integer codes that name counter values associated with the sqlite3_stmt_status() interface. The meanings of the various counters are as follows:
Database Snapshot
An instance of the snapshot object records the state of a WAL mode database for some specific point in history. In WAL mode, multiple database connections that are open on the same database file can each be reading a different historical version of the database file. When a database connection begins a read transaction, that connection sees an unchanging copy of the database as it existed for the point in time when the transaction first started. Subsequent changes to the database from other connections are not seen by the reader until a new read transaction is started. The sqlite3_snapshot object records state information about an historical version of the database file so that it is possible to later open a new read transaction that sees that historical version of the database rather than the most recent version. 1 Constructor using this object: sqlite3_snapshot_get() 1 Destructor using this object: sqlite3_snapshot_free() 3 Methods using this object: sqlite3_snapshot_cmp(), sqlite3_snapshot_open(), sqlite3_snapshot_recover() 64-Bit Integer Types
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. The sqlite3_int64 and sqlite_int64 types can store integer values between -9223372036854775808 and +9223372036854775807 inclusive. The sqlite3_uint64 and sqlite_uint64 types can store integer values between 0 and +18446744073709551615 inclusive. Virtual Table Object
This structure, sometimes called a "virtual table module", defines the implementation of a virtual table. This structure consists mostly of methods for the module. A virtual table module is created by filling in a persistent instance of this structure and passing a pointer to that instance to sqlite3_create_module() or sqlite3_create_module_v2(). The registration remains valid until it is replaced by a different module or until the database connection closes. The content of this structure must not change while it is registered with any database connection. Virtual Table Cursor Object
Every virtual table 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 and are destroyed by the xClose method. Cursors are used by the xFilter, xNext, xEof, xColumn, and xRowid methods 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. A Handle To An Open BLOBtypedef struct sqlite3_blob sqlite3_blob; An instance of this object represents an open BLOB on which incremental BLOB I/O can be performed. Objects of this type are 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. 1 Constructor using this object: sqlite3_blob_open() 1 Destructor using this object: sqlite3_blob_close() 4 Methods using this object: sqlite3_blob_bytes(), sqlite3_blob_read(), sqlite3_blob_reopen(), sqlite3_blob_write() Database Connection Handletypedef struct sqlite3 sqlite3; Each open SQLite database is represented by a pointer to an instance of the opaque structure named "sqlite3". It is useful to think of an sqlite3 pointer as an object. The sqlite3_open(), sqlite3_open16(), and sqlite3_open_v2() interfaces are its constructors, and sqlite3_close() and sqlite3_close_v2() are its destructors. There are many other interfaces (such as sqlite3_prepare_v2(), sqlite3_create_function(), and sqlite3_busy_timeout() to name but three) that are methods on an sqlite3 object. 3 Constructors using this object: sqlite3_open(), sqlite3_open16(), sqlite3_open_v2() 2 Destructors using this object: sqlite3_close(), sqlite3_close_v2() 80 Methods using this object: Dynamic String Objecttypedef struct sqlite3_str sqlite3_str; An instance of the sqlite3_str object contains a dynamically-sized string under construction. The lifecycle of an sqlite3_str object is as follows: 1 Constructor using this object: sqlite3_str_new() 2 Destructors using this object: sqlite3_str_finish(), sqlite3_str_free() 10 Methods using this object: Application Defined Page Cache.
The sqlite3_config(SQLITE_CONFIG_PCACHE2, ...) interface can register an alternative page cache implementation by passing in an instance of the sqlite3_pcache_methods2 structure. In many applications, most of the heap memory allocated by SQLite is used for the page cache. By implementing a custom page cache using this API, an application can better control the amount of memory consumed by SQLite, the way in which that memory is allocated and released, and the policies used to determine exactly which parts of a database file are cached and for how long. The alternative page cache mechanism is an extreme measure that is only needed by the most demanding applications. The built-in page cache is recommended for most uses. The contents of the sqlite3_pcache_methods2 structure are copied to an internal buffer by SQLite within the call to sqlite3_config. Hence the application may discard the parameter after the call to sqlite3_config() returns. The xInit() method is called once for each effective call to sqlite3_initialize() (usually only once during the lifetime of the process). The xInit() method is passed a copy of the sqlite3_pcache_methods2.pArg value. The intent of the xInit() method is to set up global data structures required by the custom page cache implementation. If the xInit() method is NULL, then the built-in default page cache is used instead of the application defined page cache. The xShutdown() method is called by sqlite3_shutdown(). It can be used to clean up any outstanding resources before process shutdown, if required. The xShutdown() method may be NULL. SQLite automatically serializes calls to the xInit method, so the xInit method need not be threadsafe. The xShutdown method is only called from sqlite3_shutdown() so it does not need to be threadsafe either. All other methods must be threadsafe in multithreaded applications. SQLite will never invoke xInit() more than once without an intervening call to xShutdown(). SQLite invokes the xCreate() method to construct a new cache instance. SQLite will typically create one cache instance for each open database file, though this is not guaranteed. The first parameter, szPage, is the size in bytes of the pages that must be allocated by the cache. szPage will always be a power of two. The second parameter szExtra is a number of bytes of extra storage associated with each page cache entry. The szExtra parameter will be a number less than 250. SQLite will use the extra szExtra bytes on each page to store metadata about the underlying database page on disk. The value passed into szExtra depends on the SQLite version, the target platform, and how SQLite was compiled. The third argument to xCreate(), bPurgeable, is true if the cache being created will be used to cache database pages of a file stored on disk, or false if it is used for an in-memory database. The cache implementation does not have to do anything special based upon the value of bPurgeable; it is purely advisory. On a cache where bPurgeable is false, SQLite will never invoke xUnpin() except to deliberately delete a page. In other words, calls to xUnpin() on a cache with bPurgeable set to false will always have the "discard" flag set to true. Hence, a cache created with bPurgeable set to false will never contain any unpinned pages. The xCachesize() method may be called at any time by SQLite to set the suggested maximum cache-size (number of pages stored) for the cache instance passed as the first argument. This is the value configured using the SQLite "PRAGMA cache_size" command. As with the bPurgeable parameter, the implementation is not required to do anything with this value; it is advisory only. The xPagecount() method must return the number of pages currently stored in the cache, both pinned and unpinned. The xFetch() method locates a page in the cache and returns a pointer to an sqlite3_pcache_page object associated with that page, or a NULL pointer. The pBuf element of the returned sqlite3_pcache_page object will be a pointer to a buffer of szPage bytes used to store the content of a single database page. The pExtra element of sqlite3_pcache_page will be a pointer to the szExtra bytes of extra storage that SQLite has requested for each entry in the page cache. The page to be fetched is determined by the key. The minimum key value is 1. After it has been retrieved using xFetch, the page is considered to be "pinned". If the requested page is already in the page cache, then the page cache implementation must return a pointer to the page buffer with its content intact. If the requested page is not already in the cache, then the cache implementation should use the value of the createFlag parameter to help it determine what action to take:
SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite will only use a createFlag of 2 after a prior call with a createFlag of 1 failed. In between the xFetch() calls, SQLite may attempt to unpin one or more cache pages by spilling the content of pinned pages to disk and synching the operating system disk cache. xUnpin() is called by SQLite with a pointer to a currently pinned page as its second argument. If the third parameter, discard, is non-zero, then the page must be evicted from the cache. If the discard parameter is zero, then the page may be discarded or retained at the discretion of the page cache implementation. The page cache implementation may choose to evict unpinned pages at any time. The cache must not perform any reference counting. A single call to xUnpin() unpins the page regardless of the number of prior calls to xFetch(). The xRekey() method is used to change the key value associated with the page passed as the second argument. If the cache previously contains an entry associated with newKey, it must be discarded. Any prior cache entry associated with newKey is guaranteed not to be pinned. When SQLite calls the xTruncate() method, the cache must discard all existing cache entries with page numbers (keys) greater than or equal to the value of the iLimit parameter passed to xTruncate(). If any of these pages are pinned, they become implicitly unpinned, meaning that they can be safely discarded. The xDestroy() method is used to delete a cache allocated by xCreate(). All resources associated with the specified cache should be freed. After calling the xDestroy() method, SQLite considers the sqlite3_pcache* handle invalid, and will not use it with any other sqlite3_pcache_methods2 functions. SQLite invokes the xShrink() method when it wants the page cache to free up as much of heap memory as possible. The page cache implementation is not obligated to free any memory, but well-behaved implementations should do their best. Prepared Statement Objecttypedef struct sqlite3_stmt sqlite3_stmt; An instance of this object represents a single SQL statement that has been compiled into binary form and is ready to be evaluated. Think of each SQL statement as a separate computer program. The original SQL text is source code. A prepared statement object is the compiled object code. All SQL must be converted into a prepared statement before it can be run. The life-cycle of a prepared statement object usually goes like this: 6 Constructors using this object: 1 Destructor using this object: sqlite3_finalize() 53 Methods using this object: Dynamically Typed Value Objecttypedef struct sqlite3_value sqlite3_value; SQLite uses the sqlite3_value object to represent all values that can be stored in a database table. SQLite uses dynamic typing for the values it stores. Values stored in sqlite3_value objects can be integers, floating point values, strings, BLOBs, or NULL. An sqlite3_value object may be either "protected" or "unprotected". Some interfaces require a protected sqlite3_value. Other interfaces will accept either a protected or an unprotected sqlite3_value. Every interface that accepts sqlite3_value arguments specifies whether or not it requires a protected sqlite3_value. The sqlite3_value_dup() interface can be used to construct a new protected sqlite3_value from an unprotected sqlite3_value. The terms "protected" and "unprotected" refer to whether or not a mutex is held. An internal mutex is held for a protected sqlite3_value object but no mutex is held for an unprotected sqlite3_value object. If SQLite is compiled to be single-threaded (with SQLITE_THREADSAFE=0 and with sqlite3_threadsafe() returning 0) or if SQLite is run in one of reduced mutex modes SQLITE_CONFIG_SINGLETHREAD or SQLITE_CONFIG_MULTITHREAD then there is no distinction between protected and unprotected sqlite3_value objects and they can be used interchangeably. However, for maximum code portability it is recommended that applications still make the distinction between protected and unprotected sqlite3_value objects even when not strictly required. The sqlite3_value objects that are passed as parameters into the implementation of application-defined SQL functions are protected. The sqlite3_value objects returned by sqlite3_vtab_rhs_value() are protected. The sqlite3_value object returned by sqlite3_column_value() is unprotected. Unprotected sqlite3_value objects may only be used as arguments to sqlite3_result_value(), sqlite3_bind_value(), and sqlite3_value_dup(). The sqlite3_value_type() family of interfaces require protected sqlite3_value objects. 19 Methods using this object: Deprecated Functions
These functions are deprecated. In order to maintain backwards compatibility with older code, these functions continue to be supported. However, new applications should avoid the use of these functions. To encourage programmers to avoid these functions, we will not explain what they do. Online Backup API.sqlite3_backup *sqlite3_backup_init( sqlite3 *pDest, /* Destination database handle */ const char *zDestName, /* Destination database name */ sqlite3 *pSource, /* Source database handle */ const char *zSourceName /* Source database name */ ); int sqlite3_backup_step(sqlite3_backup *p, int nPage); int sqlite3_backup_finish(sqlite3_backup *p); int sqlite3_backup_remaining(sqlite3_backup *p); int sqlite3_backup_pagecount(sqlite3_backup *p); The backup API copies the content of one database into another. It is useful either for creating backups of databases or for copying in-memory databases to or from persistent files. See Also: Using the SQLite Online Backup API SQLite holds a write transaction open on the destination database file for the duration of the backup operation. The source database is read-locked only while it is being read; it is not locked continuously for the entire backup operation. Thus, the backup may be performed on a live source database without preventing other database connections from reading or writing to the source database while the backup is underway. To perform a backup operation: sqlite3_backup_init() The D and N arguments to sqlite3_backup_init(D,N,S,M) are the database connection associated with the destination database and the database name, respectively. The database name is "main" for the main database, "temp" for the temporary database, or the name specified after the AS keyword in an ATTACH statement for an attached database. The S and M arguments passed to sqlite3_backup_init(D,N,S,M) identify the database connection and database name of the source database, respectively. The source and destination database connections (parameters S and D) must be different or else sqlite3_backup_init(D,N,S,M) will fail with an error. A call to sqlite3_backup_init() will fail, returning NULL, if there is already a read or read-write transaction open on the destination database. If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is returned and an error code and error message are stored in the destination database connection D. The error code and message for the failed call to sqlite3_backup_init() can be retrieved using the sqlite3_errcode(), sqlite3_errmsg(), and/or sqlite3_errmsg16() functions. A successful call to sqlite3_backup_init() returns a pointer to an sqlite3_backup object. The sqlite3_backup object may be used with the sqlite3_backup_step() and sqlite3_backup_finish() functions to perform the specified backup operation. sqlite3_backup_step() Function sqlite3_backup_step(B,N) will copy up to N pages between the source and destination databases specified by sqlite3_backup object B. If N is negative, all remaining source pages are copied. If sqlite3_backup_step(B,N) successfully copies N pages and there are still more pages to be copied, then the function returns SQLITE_OK. If sqlite3_backup_step(B,N) successfully finishes copying all pages from source to destination, then it returns SQLITE_DONE. If an error occurs while running sqlite3_backup_step(B,N), then an error code is returned. As well as SQLITE_OK and SQLITE_DONE, a call to sqlite3_backup_step() may return SQLITE_READONLY, SQLITE_NOMEM, SQLITE_BUSY, SQLITE_LOCKED, or an SQLITE_IOERR_XXX extended error code. The sqlite3_backup_step() might return SQLITE_READONLY if If sqlite3_backup_step() cannot obtain a required file-system lock, then the busy-handler function is invoked (if one is specified). If the busy-handler returns non-zero before the lock is available, then SQLITE_BUSY is returned to the caller. In this case the call to sqlite3_backup_step() can be retried later. If the source database connection is being used to write to the source database when sqlite3_backup_step() is called, then SQLITE_LOCKED is returned immediately. Again, in this case the call to sqlite3_backup_step() can be retried later on. If SQLITE_IOERR_XXX, SQLITE_NOMEM, or SQLITE_READONLY is returned, then there is no point in retrying the call to sqlite3_backup_step(). These errors are considered fatal. The application must accept that the backup operation has failed and pass the backup operation handle to the sqlite3_backup_finish() to release associated resources. The first call to sqlite3_backup_step() obtains an exclusive lock on the destination file. The exclusive lock is not released until either sqlite3_backup_finish() is called or the backup operation is complete and sqlite3_backup_step() returns SQLITE_DONE. Every call to sqlite3_backup_step() obtains a shared lock on the source database that lasts for the duration of the sqlite3_backup_step() call. Because the source database is not locked between calls to sqlite3_backup_step(), the source database may be modified mid-way through the backup process. If the source database is modified by an external process or via a database connection other than the one being used by the backup operation, then the backup will be automatically restarted by the next call to sqlite3_backup_step(). If the source database is modified by using the same database connection as is used by the backup operation, then the backup database is automatically updated at the same time. sqlite3_backup_finish() When sqlite3_backup_step() has returned SQLITE_DONE, or when the application wishes to abandon the backup operation, the application should destroy the sqlite3_backup by passing it to sqlite3_backup_finish(). The sqlite3_backup_finish() interfaces releases all resources associated with the sqlite3_backup object. If sqlite3_backup_step() has not yet returned SQLITE_DONE, then any active write-transaction on the destination database is rolled back. The sqlite3_backup object is invalid and may not be used following a call to sqlite3_backup_finish(). The value returned by sqlite3_backup_finish is SQLITE_OK if no sqlite3_backup_step() errors occurred, regardless of whether or not sqlite3_backup_step() completed. If an out-of-memory condition or IO error occurred during any prior sqlite3_backup_step() call on the same sqlite3_backup object, then sqlite3_backup_finish() returns the corresponding error code. A return of SQLITE_BUSY or SQLITE_LOCKED from sqlite3_backup_step() is not a permanent error and does not affect the return value of sqlite3_backup_finish(). sqlite3_backup_remaining() and sqlite3_backup_pagecount() The sqlite3_backup_remaining() routine returns the number of pages still to be backed up at the conclusion of the most recent sqlite3_backup_step(). The sqlite3_backup_pagecount() routine returns the total number of pages in the source database at the conclusion of the most recent sqlite3_backup_step(). The values returned by these functions are only updated by sqlite3_backup_step(). If the source database is modified in a way that changes the size of the source database or the number of pages remaining, those changes are not reflected in the output of sqlite3_backup_pagecount() and sqlite3_backup_remaining() until after the next sqlite3_backup_step(). Concurrent Usage of Database Handles The source database connection may be used by the application for other purposes while a backup operation is underway or being initialized. If SQLite is compiled and configured to support threadsafe database connections, then the source database connection may be used concurrently from within other threads. However, the application must guarantee that the destination database connection is not passed to any other API (by any thread) after sqlite3_backup_init() is called and before the corresponding call to sqlite3_backup_finish(). SQLite does not currently check to see if the application incorrectly accesses the destination database connection and so no error code is reported, but the operations may malfunction nevertheless. Use of the destination database connection while a backup is in progress might also cause a mutex deadlock. If running in shared cache mode, the application must guarantee that the shared cache used by the destination database is not accessed while the backup is running. In practice this means that the application must guarantee that the disk file being backed up to is not accessed by any connection within the process, not just the specific connection that was passed to sqlite3_backup_init(). The sqlite3_backup object itself is partially threadsafe. Multiple threads may safely make multiple concurrent calls to sqlite3_backup_step(). However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount() APIs are not strictly speaking threadsafe. If they are invoked at the same time as another thread is invoking sqlite3_backup_step() it is possible that they return invalid values. Alternatives To Using The Backup API Other techniques for safely creating a consistent backup of an SQLite database include: Bind array values to the CARRAY table-valued functionint sqlite3_carray_bind_v2( sqlite3_stmt *pStmt, /* Statement to be bound */ int i, /* Parameter index */ void *aData, /* Pointer to array data */ int nData, /* Number of data elements */ int mFlags, /* CARRAY flags */ void (*xDel)(void*), /* Destructor for aData */ void *pDel /* Optional argument to xDel() */ ); int sqlite3_carray_bind( sqlite3_stmt *pStmt, /* Statement to be bound */ int i, /* Parameter index */ void *aData, /* Pointer to array data */ int nData, /* Number of data elements */ int mFlags, /* CARRAY flags */ void (*xDel)(void*) /* Destructor for aData */ ); The sqlite3_carray_bind_v2(S,I,P,N,F,X,D) interface binds an array value to parameter that is the first argument of the carray() table-valued function. The S parameter is a pointer to the prepared statement that uses the carray() functions. I is the parameter index to be bound. I must be the index of the parameter that is the first argument to the carray() table-valued function. P is a pointer to the array to be bound, and N is the number of elements in the array. The F argument is one of constants SQLITE_CARRAY_INT32, SQLITE_CARRAY_INT64, SQLITE_CARRAY_DOUBLE, SQLITE_CARRAY_TEXT, or SQLITE_CARRAY_BLOB to indicate the datatype of the array P. If the X argument is not a NULL pointer or one of the special values SQLITE_STATIC or SQLITE_TRANSIENT, then SQLite will invoke the function X with argument D when it is finished using the data in P. The call to X(D) is a destructor for the array P. The destructor X(D) is invoked even if the call to sqlite3_carray_bind_v2() fails. If the X parameter is the special-case value SQLITE_STATIC, then SQLite assumes that the data static and the destructor is never invoked. If the X parameter is the special-case value SQLITE_TRANSIENT, then sqlite3_carray_bind_v2() makes its own private copy of the data prior to returning and never invokes the destructor X. The sqlite3_carray_bind() function works the same as sqlite3_carray_bind_v2() with a D parameter set to P. In other words, sqlite3_carray_bind(S,I,P,N,F,X) is same as sqlite3_carray_bind_v2(S,I,P,N,F,X,P). Count The Number Of Rows Modifiedint sqlite3_changes(sqlite3*); sqlite3_int64 sqlite3_changes64(sqlite3*); These functions return the number of rows modified, inserted or deleted by the most recently completed INSERT, UPDATE or DELETE statement on the database connection specified by the only parameter. The two functions are identical except for the type of the return value and that if the number of rows modified by the most recent INSERT, UPDATE, or DELETE is greater than the maximum value supported by type "int", then the return value of sqlite3_changes() is undefined. Executing any other type of SQL statement does not modify the value returned by these functions. For the purposes of this interface, a CREATE TABLE AS SELECT statement does not count as an INSERT, UPDATE or DELETE statement and hence the rows added to the new table by the CREATE TABLE AS SELECT statement are not counted. Only changes made directly by the INSERT, UPDATE or DELETE statement are considered - auxiliary changes caused by triggers, foreign key actions or REPLACE constraint resolution are not counted. Changes to a view that are intercepted by INSTEAD OF triggers are not counted. The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero. Only changes made to real tables are counted. Things are more complicated if the sqlite3_changes() function is executed while a trigger program is running. This may happen if the program uses the changes() SQL function, or if some other callback function invokes sqlite3_changes() directly. Essentially: This means that if the changes() SQL function (or similar) is used by the first INSERT, UPDATE or DELETE statement within a trigger, it returns the value as set when the calling statement began executing. If it is used by the second or subsequent such statement within a trigger program, the value returned reflects the number of rows modified by the previous INSERT, UPDATE or DELETE statement within the same trigger. If a separate thread makes changes on the same database connection while sqlite3_changes() is running then the value returned is unpredictable and not meaningful. See also: Closing A Database Connectionint sqlite3_close(sqlite3*); int sqlite3_close_v2(sqlite3*); The sqlite3_close() and sqlite3_close_v2() routines are destructors for the sqlite3 object. Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if the sqlite3 object is successfully destroyed and all associated resources are deallocated. Ideally, applications should finalize all prepared statements, close all BLOB handles, and finish all sqlite3_backup objects associated with the sqlite3 object prior to attempting to close the object. If the database connection is associated with unfinalized prepared statements, BLOB handlers, and/or unfinished sqlite3_backup objects then sqlite3_close() will leave the database connection open and return SQLITE_BUSY. If sqlite3_close_v2() is called with unfinalized prepared statements, unclosed BLOB handlers, and/or unfinished sqlite3_backups, it returns SQLITE_OK regardless, but instead of deallocating the database connection immediately, it marks the database connection as an unusable "zombie" and makes arrangements to automatically deallocate the database connection after all prepared statements are finalized, all BLOB handles are closed, and all backups have finished. The sqlite3_close_v2() interface is intended for use with host languages that are garbage collected, and where the order in which destructors are called is arbitrary. If an sqlite3 object is destroyed while a transaction is open, the transaction is automatically rolled back. The C parameter to sqlite3_close(C) and sqlite3_close_v2(C) must be either a NULL pointer or an sqlite3 object pointer obtained from sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2(), and not previously closed. Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. Collation Needed Callbacksint 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*) ); To avoid having to register all collation sequences before a database can be used, a single callback function may be registered with the database connection to be invoked 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 the existing collation-needed 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 connection. The third argument is one of SQLITE_UTF8, SQLITE_UTF16BE, or SQLITE_UTF16LE, indicating the most desirable form of the collation sequence function required. The fourth parameter is the name of the required collation sequence. The callback function should register the desired collation using sqlite3_create_collation(), sqlite3_create_collation16(), or sqlite3_create_collation_v2(). Source Of Data In A Query Resultconst 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); These routines provide a means to determine the database, table, and table column that is the origin of a particular result column in a SELECT statement. The name of the database or table or column can be returned as either a UTF-8 or UTF-16 string. The _database_ routines return the database name, the _table_ routines return the table name, and the origin_ routines return the column name. The returned string is valid until the prepared statement is destroyed using sqlite3_finalize() or until the statement is automatically reprepared by the first call to sqlite3_step() for a particular run 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 these interfaces is a prepared statement. These functions return information about the Nth result column returned by the statement, where N is the second function argument. The left-most column is column 0 for these routines. If the Nth column returned by the statement is an expression or subquery and is not a column value, then all of these functions return NULL. These routines might also return NULL if a memory allocation error occurs. Otherwise, they return the name of the attached database, table, or column that query result column was extracted from. As with all other SQLite APIs, those whose names end with "16" return UTF-16 encoded strings and the other functions return UTF-8. These APIs are only available if the library was compiled with the SQLITE_ENABLE_COLUMN_METADATA C-preprocessor symbol. If two or more threads call one or more column metadata interfaces for the same prepared statement and result column at the same time then the results are undefined. Declared Datatype Of A Query Resultconst char *sqlite3_column_decltype(sqlite3_stmt*,int); const void *sqlite3_column_decltype16(sqlite3_stmt*,int); 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 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, given the database schema: CREATE TABLE t1(c1 VARIANT); and the following statement to be compiled: SELECT c1 + 1, c1 FROM t1; this routine would return the string "VARIANT" for the second result column (i==1), and a NULL pointer for the first result column (i==0). 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. Column Names In A Result Setconst char *sqlite3_column_name(sqlite3_stmt*, int N); const void *sqlite3_column_name16(sqlite3_stmt*, int N); These routines return the name assigned to a particular column in the result set of a SELECT statement. The sqlite3_column_name() interface returns a pointer to a zero-terminated UTF-8 string and sqlite3_column_name16() returns a pointer to a zero-terminated UTF-16 string. The first parameter is the prepared statement that implements the SELECT statement. The second parameter is the column number. The leftmost column is number 0. The returned string [Page truncated to keep GeezerVison snappy.] | ||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |