Small. Fast. Reliable.
Choose any three.

C/C++ Interface For SQLite Version 3

This page defined the C-language interface to SQLite.

This is not a tutorial. These pages are designed to be precise, not easy to read. For a tutorial introduction see SQLite In 3 Minutes Or Less and/or the Introduction To The SQLite C/C++ Interface.

This page contains all C-language interface information in a single HTML file. The same information is also available broken out into lots of small pages for easier viewing, if you prefer.

This document is created by a script which scans comments in the source code files.


Experimental And Deprecated Interfaces

SQLite interfaces can be subdivided into three categories:

  1. Stable
  2. Experimental
  3. Deprecated

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.

Experiemental interfaces are subject to change. Applications that use experiemental interfaces may need to be modified when upgrading to a newer SQLite release. 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 superceded 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:


Objects:

Note: Objects marked with "exp" are experimental and objects marked with "(obs)" are deprecated.


Constants:

Note: Constants marked with "(exp)" are experimental and constants marked with "(obs)" are deprecated


Functions:

Note: Functions marked with "(exp)" are experimental and functions marked with (obs) are deprecated.


Configuration Options

#define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */

Important: This interface is experimental and is subject to change without notice.

These constants are the available integer configuration options that can be passed as the second argument to the sqlite3_db_config() interface.

New configuration options may be added in future releases of SQLite. Existing configuration options might be discontinued. Applications should check the return code from sqlite3_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.

SQLITE_DBCONFIG_LOOKASIDE
This option takes three additional arguments that determine the lookaside memory allocator configuration for the database connection. The first argument (the third parameter to sqlite3_db_config() is a pointer to an 8-byte aligned memory buffer to use for lookaside memory. The first argument may be NULL in which case SQLite will allocate the lookaside buffer itself using sqlite3_malloc(). The second argument is the size of each lookaside buffer slot and the third argument is the number of slots. The size of the buffer in the first argument must be greater than or equal to the product of the second and third arguments.


Status Parameters for database connections

#define SQLITE_DBSTATUS_LOOKASIDE_USED     0

Important: This interface is experimental and is subject to change without notice.

Status verbs for sqlite3_db_status().

SQLITE_DBSTATUS_LOOKASIDE_USED
This parameter returns the number of lookaside memory slots currently checked out.


Online Backup Object

typedef struct sqlite3_backup sqlite3_backup;

Important: This interface is experimental and is subject to change without notice.

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 Object

typedef 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 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().


OS Interface Open File Handle

typedef struct sqlite3_file sqlite3_file;
struct sqlite3_file {
  const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
};

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.


OS Interface File Virtual Methods Object

typedef struct sqlite3_io_methods sqlite3_io_methods;
struct sqlite3_io_methods {
  int iVersion;
  int (*xClose)(sqlite3_file*);
  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  int (*xSync)(sqlite3_file*, int flags);
  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  int (*xLock)(sqlite3_file*, int);
  int (*xUnlock)(sqlite3_file*, int);
  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  int (*xSectorSize)(sqlite3_file*);
  int (*xDeviceCharacteristics)(sqlite3_file*);
  /* Additional methods may be added in future releases */
};

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 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 xOpen reported that it failed. The only way to prevent a call to xClose following a failed xOpen is for the 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

xLock() increases the lock. xUnlock() decreases the lock. The xCheckReservedLock() method checks whether any database connection, either in this process or in some other process, is holding a RESERVED, PENDING, or EXCLUSIVE lock on the file. It returns true if such a lock exists and false otherwise.

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.

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

typedef struct sqlite3_mem_methods sqlite3_mem_methods;
struct sqlite3_mem_methods {
  void *(*xMalloc)(int);         /* Memory allocation function */
  void (*xFree)(void*);          /* Free a prior allocation */
  void *(*xRealloc)(void*,int);  /* Resize an allocation */
  int (*xSize)(void*);           /* Return the size of an allocation */
  int (*xRoundup)(int);          /* Round up request size to allocation size */
  int (*xInit)(void*);           /* Initialize the memory allocator */
  void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
  void *pAppData;                /* Argument to xInit() and xShutdown() */
};

Important: This interface is experimental and is subject to change without notice.

An instance of this object defines the interface between SQLite and low-level memory allocation routines.

This object is used in only one place in the SQLite interface. A pointer to an instance of this object is the argument to sqlite3_config() when the configuration option is SQLITE_CONFIG_MALLOC. By creating an instance of this object and passing it to sqlite3_config() during configuration, an application can specify an alternative memory allocation subsystem for SQLite to use for all of its dynamic memory needs.

Note that SQLite comes with a built-in memory allocator that is perfectly adequate for the overwhelming majority of applications and that this object is only useful to a tiny minority of applications with specialized memory allocation requirements. This object is also used during testing of SQLite in order to specify an alternative memory allocator that simulates memory out-of-memory conditions in order to verify that SQLite recovers gracefully from such conditions.

The xMalloc, xFree, and xRealloc methods must work like the malloc(), free(), and realloc() functions from the standard library.

xSize should return the allocated size of a memory allocation previously obtained from xMalloc or xRealloc. The allocated size is always at least as big as the requested size but may be larger.

The xRoundup method returns what would be the allocated size of a memory allocation given a particular requested size. Most memory allocators round up memory allocations at least to the next multiple of 8. Some allocators round up to a larger multiple or to a power of 2.

The xInit method initializes the memory allocator. (For example, it might allocate any require mutexes or initialize internal data structures. The xShutdown method is invoked (indirectly) by sqlite3_shutdown() and should deallocate any resources acquired by xInit. The pAppData pointer is used as the only parameter to xInit and xShutdown.


Mutex Handle

typedef 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

typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
struct sqlite3_mutex_methods {
  int (*xMutexInit)(void);
  int (*xMutexEnd)(void);
  sqlite3_mutex *(*xMutexAlloc)(int);
  void (*xMutexFree)(sqlite3_mutex *);
  void (*xMutexEnter)(sqlite3_mutex *);
  int (*xMutexTry)(sqlite3_mutex *);
  void (*xMutexLeave)(sqlite3_mutex *);
  int (*xMutexHeld)(sqlite3_mutex *);
  int (*xMutexNotheld)(sqlite3_mutex *);
};

Important: This interface is experimental and is subject to change without notice.

An instance of this structure defines the low-level routines used to allocate and use mutexes.

Usually, the default mutex implementations provided by SQLite are sufficient, however the user has the option of substituting a custom implementation for specialized deployments or systems for which SQLite does not provide a suitable implementation. In this case, the user creates and populates an instance of this structure to pass to sqlite3_config() along with the SQLITE_CONFIG_MUTEX option. Additionally, an instance of this structure can be used as an output variable when querying the system for the current mutex implementation, using the SQLITE_CONFIG_GETMUTEX option.

The xMutexInit method defined by this structure is invoked as part of system initialization by the sqlite3_initialize() function. The xMutexInit routine shall be called by SQLite once for each effective call to sqlite3_initialize().

The xMutexEnd method defined by this structure is invoked as part of system shutdown by the sqlite3_shutdown() function. The implementation of this method is expected to release all outstanding resources obtained by the mutex methods implementation, especially those obtained by the xMutexInit method. The xMutexEnd() interface shall be invoked once for each call to sqlite3_shutdown().

The remaining seven methods defined by this structure (xMutexAlloc, xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and xMutexNotheld) implement the following interfaces (respectively):

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).


Custom Page Cache Object

typedef struct sqlite3_pcache sqlite3_pcache;

Important: This interface is experimental and is subject to change without notice.

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_methods for additional information.


Application Defined Page Cache.

typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
struct sqlite3_pcache_methods {
  void *pArg;
  int (*xInit)(void*);
  void (*xShutdown)(void*);
  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  int (*xPagecount)(sqlite3_pcache*);
  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  void (*xDestroy)(sqlite3_pcache*);
};

Important: This interface is experimental and is subject to change without notice.

The sqlite3_config(SQLITE_CONFIG_PCACHE, ...) interface can register an alternative page cache implementation by passing in an instance of the sqlite3_pcache_methods structure. The majority of the heap memory used by sqlite is used by the page cache to cache data read from, or ready to be written to, the database file. By implementing a custom page cache using this API, an application can control more precisely the amount of memory consumed by sqlite, the way in which said 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 contents of the structure are copied to an internal buffer by sqlite within the call to sqlite3_config.

The xInit() method is called once for each call to sqlite3_initialize() (usually only once during the lifetime of the process). It is passed a copy of the sqlite3_pcache_methods.pArg value. It can be used to set up global structures and mutexes required by the custom page cache implementation. The xShutdown() method is called from within sqlite3_shutdown(), if the application invokes this API. It can be used to clean up any outstanding resources before process shutdown, if required.

The xCreate() method is used to construct a new cache instance. The first parameter, szPage, is the size in bytes of the pages that must be allocated by the cache. szPage will not be a power of two. The second argument, bPurgeable, is true if the cache being created will be used to cache database pages read from 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 on the value of bPurgeable, it is purely advisory.

The xCachesize() method may be called at any time by SQLite to set the suggested maximum cache-size (number of pages stored by) 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 special with this value, it is advisory only.

The xPagecount() method should return the number of pages currently stored in the cache supplied as an argument.

The xFetch() method is used to fetch a page and return a pointer to it. A 'page', in this context, is a buffer of szPage bytes aligned at an 8-byte boundary. The page to be fetched is determined by the key. The mimimum 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 a pointer to the cached buffer should be returned with its contents intact. If the page is not already in the cache, then the expected behaviour of the cache is determined by the value of the createFlag parameter passed to xFetch, according to the following table:

createFlagExpected Behaviour
0NULL should be returned. No new cache entry is created.
1If createFlag is set to 1, this indicates that SQLite is holding pinned pages that can be unpinned by writing their contents to the database file (a relatively expensive operation). In this situation the cache implementation has two choices: it can return NULL, in which case SQLite will attempt to unpin one or more pages before re-requesting the same page, or it can allocate a new page and return a pointer to it. If a new page is allocated, then the first sizeof(void*) bytes of it (at least) must be zeroed before it is returned.
2If createFlag is set to 2, then SQLite is not holding any pinned pages associated with the specific cache passed as the first argument to xFetch() that can be unpinned. The cache implementation should attempt to allocate a new cache entry and return a pointer to it. Again, the first sizeof(void*) bytes of the page should be zeroed before it is returned. If the xFetch() method returns NULL when createFlag==2, SQLite assumes that a memory allocation failed and returns SQLITE_NOMEM to the user.

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 should be evicted from the cache. In this case SQLite assumes that the next time the page is retrieved from the cache using the xFetch() method, it will be zeroed. If the discard parameter is zero, then the page is considered to be unpinned. The cache implementation may choose to reclaim (free or recycle) unpinned pages at any time. SQLite assumes that next time the page is retrieved from the cache it will either be zeroed, or contain the same data that it did when it was unpinned.

The cache is not required to 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 from oldKey to newKey. If the cache previously contains an entry associated with newKey, it should 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 are 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_methods functions.


Name Of The Folder Holding Temporary Files

SQLITE_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 will be placed in that directory. If this variable is a NULL pointer, then SQLite performs a search for an appropriate temporary file directory.

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.


OS Interface Object

typedef struct sqlite3_vfs sqlite3_vfs;
struct sqlite3_vfs {
  int iVersion;            /* Structure version number */
  int szOsFile;            /* Size of subclassed sqlite3_file */
  int mxPathname;          /* Maximum file pathname length */
  sqlite3_vfs *pNext;      /* Next registered VFS */
  const char *zName;       /* Name of this virtual file system */
  void *pAppData;          /* Pointer to application-specific data */
  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
               int flags, int *pOutFlags);
  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  void (*xDlClose)(sqlite3_vfs*, void*);
  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  int (*xSleep)(sqlite3_vfs*, int microseconds);
  int (*xCurrentTime)(sqlite3_vfs*, double*);
  int (*xGetLastError)(sqlite3_vfs*, int, char *);
  /* New fields may be appended in figure versions.  The iVersion
  ** value will increment whenever this happens. */
};

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".

The value of the iVersion field is initially 1 but may be larger in future versions of SQLite. Additional fields may be appended to this object when the iVersion value is increased. Note that the structure of the sqlite3_vfs object changes in the transaction between SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not modified.

The 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 will guarantee that the zFilename parameter to xOpen is either a NULL pointer or string obtained from xFullPathname(). SQLite further guarantees that the string will be valid and unchanged until xClose() is called. 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 is 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, journals and for 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 file can be a directory.

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(), and xCurrentTime() interfaces are not strictly a part of the filesystem, but they are included in the VFS structure for completeness. The xRandomness() function attempts to return nBytes bytes of good-quality randomness into zOut. The return value is the actual number of bytes of randomness obtained. The xSleep() method causes the calling thread to sleep for at least the number of microseconds given. The xCurrentTime() method returns a Julian Day Number for the current date and time.


Virtual Table Instance Object

struct sqlite3_vtab {
  const sqlite3_module *pModule;  /* The module for this virtual table */
  int nRef;                       /* Used internally */
  char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
  /* Virtual table implementations will typically add additional fields */
};

Important: This interface is experimental and is subject to change without notice.

Every virtual table module implementation uses a subclass of the following structure 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 Context

void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);

The implementation of aggregate SQL functions use this routine to allocate a structure for storing their state.

The first time the sqlite3_aggregate_context() routine is called for a particular aggregate, SQLite allocates nBytes of memory, zeroes out that memory, and returns a pointer to it. On second and subsequent calls to sqlite3_aggregate_context() for the same aggregate function index, the same buffer is returned. The implementation of the aggregate can use the returned buffer to accumulate data.

SQLite automatically frees the allocated buffer when the aggregate query concludes.

The first parameter should be a copy of the SQL function context that is the first parameter to the callback routine that implements the aggregate function.

This routine must be called from the same thread in which the aggregate SQL function is running.

Requirements: H16211 H16213 H16215 H16217


Automatically Load An Extensions

int sqlite3_auto_extension(void (*xEntryPoint)(void));

This API can be invoked at program startup in order to register one or more statically linked extensions that will be available to all new database connections.

This routine stores a pointer to the extension in an array that is obtained from sqlite3_malloc(). If you run a memory leak checker on your program and it reports a leak because of this array, invoke sqlite3_reset_auto_extension() prior to shutdown to free the memory.

This function registers an extension entry point that is automatically invoked whenever a new database connection is opened using sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().

Duplicate extensions are detected so calling this routine multiple times with the same extension is harmless.

This routine stores a pointer to the extension in an array that is obtained from sqlite3_malloc().

Automatic extensions apply across all threads.


Number Of SQL Parameters

int 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 are used, there may be gaps in the list.

See also: sqlite3_bind(), sqlite3_bind_parameter_name(), and sqlite3_bind_parameter_index().

Requirements: H13601


Index Of A Parameter With A Given Name

int 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().

See also: sqlite3_bind(), sqlite3_bind_parameter_count(), and sqlite3_bind_parameter_index().

Requirements: H13641


Name Of A Host Parameter

const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);

This routine returns a pointer to the name of the n-th SQL parameter in a prepared statement. SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA" have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA" respectively. In other words, the initial ":" or "$" or "@" or "?" is included as part of the name. Parameters of the form "?" without a following integer have no name and are also referred to as "anonymous parameters".

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() or sqlite3_prepare16_v2().

See also: sqlite3_bind(), sqlite3_bind_parameter_count(), and sqlite3_bind_parameter_index().

Requirements: H13621


Return The Size Of An Open BLOB

int 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 overwriting 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.

Requirements: H17843


Close A BLOB Handle

int sqlite3_blob_close(sqlite3_blob *);

Closes an open BLOB handle.

Closing a BLOB shall cause the current transaction to commit if there are no other BLOBs, no pending prepared statements, and the database connection is in autocommit mode. If any writes were made to the BLOB, they might be held in cache until the close operation if they will fit.

Closing the BLOB often forces the changes out to disk and so if any I/O errors occur, they will likely occur at the time when the BLOB is closed. Any errors that occur during closing are reported as a non-zero return value.

The BLOB is closed unconditionally. Even if this routine returns an error code, the BLOB is still closed.

Calling this routine with a null pointer (which as would be returned by failed call to sqlite3_blob_open()) is a harmless no-op.

Requirements: H17833 H17836 H17839


Open A BLOB For Incremental I/O

int 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;

If the flags parameter is non-zero, then the BLOB is opened for read and write access. If it is zero, the BLOB is opened for read access.

Note that the database name is not the filename that contains the database but rather the symbolic name of the database that is assigned when the database is connected using ATTACH. For the main database file, the database name is "main". For TEMP tables, the database name is "temp".

On success, SQLITE_OK is returned and the new BLOB handle is written to *ppBlob. Otherwise an error code is returned and *ppBlob is set to be a null pointer. This function sets the database connection error code and message accessible via sqlite3_errcode() and sqlite3_errmsg() and related functions. Note that the *ppBlob variable is always initialized in a way that makes it safe to invoke sqlite3_blob_close() on *ppBlob regardless of the success or failure of this routine.

If the row that a BLOB handle points to is modified by an UPDATE, DELETE, or by ON CONFLICT side-effects then the BLOB handle is marked as "expired". This is true if any column of the row is changed, even a column other than the one the BLOB handle is open on. Calls to sqlite3_blob_read() and sqlite3_blob_write() for a expired BLOB handle fail with an return code of SQLITE_ABORT. Changes written into a BLOB prior to the BLOB expiring are not rollback by the expiration of the BLOB. Such changes will eventually commit if the transaction continues to completion.

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 underface. 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 can be used, if desired, to create an empty, zero-filled blob in which to read or write using this interface.

To avoid a resource leak, every open BLOB handle should eventually be released by a call to sqlite3_blob_close().

Requirements: H17813 H17814 H17816 H17819 H17821 H17824


Read Data From A BLOB Incrementally

int 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, SQLITE_OK is returned. 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().

Requirements: H17853 H17856 H17859 H17862 H17863 H17865 H17868


Write Data Into A BLOB Incrementally

int 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.

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. If N is less than zero 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.

An attempt to write to an expired BLOB handle fails with an error code of SQLITE_ABORT. Writes to the BLOB that occurred before the BLOB handle expired are not rolled back by the expiration of the handle, though of course those changes might have been overwritten by the statement that expired the BLOB handle or by other independent statements.

On success, SQLITE_OK is returned. Otherwise, an error code or an extended error code is returned.

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().

Requirements: H17873 H17874 H17875 H17876 H17877 H17879 H17882 H17885 H17888


Register A Callback To Handle SQLITE_BUSY Errors

int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);

This routine sets a callback function that might be invoked whenever an attempt is made to open a database table that another thread or process has locked.

If the busy callback is NULL, then SQLITE_BUSY or SQLITE_IOERR_BLOCKED is returned immediately upon encountering the lock. If the busy callback is not NULL, then the callback will be invoked with two arguments.

The first argument to the handler is a copy of the void* pointer which is the third argument to sqlite3_busy_handler(). The second argument to the handler callback is the number of times that the busy handler has been invoked for this locking event. If the busy callback returns 0, then no additional attempts are made to access the database and SQLITE_BUSY or SQLITE_IOERR_BLOCKED is returned. If the callback returns non-zero, then another attempt is made to open the database for reading and the cycle repeats.

The presence of a busy handler does not guarantee that it will be invoked when there is lock contention. If SQLite determines that invoking the busy handler could result in a deadlock, it will go ahead and return SQLITE_BUSY or SQLITE_IOERR_BLOCKED instead of invoking the busy handler. Consider a scenario where one process is holding a read lock that it is trying to promote to a reserved lock and a second process is holding a reserved lock that it is trying to promote to an exclusive lock. The first process cannot proceed because it is blocked by the second and the second process cannot proceed because it is blocked by the first. If both processes invoke the busy handlers, neither will make any progress. Therefore, SQLite returns SQLITE_BUSY for the first process, hoping that this will induce the first process to release its read lock and allow the second process to proceed.

The default busy callback is NULL.

The SQLITE_BUSY error is converted to SQLITE_IOERR_BLOCKED when SQLite is in the middle of a large transaction where all the changes will not fit into the in-memory cache. SQLite will already hold a RESERVED lock on the database file, but it needs to promote this lock to EXCLUSIVE so that it can spill cache pages into the database file without harm to concurrent readers. If it is unable to promote the lock, then the in-memory cache will be left in an inconsistent state and so the error code is promoted from the relatively benign SQLITE_BUSY to the more severe SQLITE_IOERR_BLOCKED. This error code promotion forces an automatic rollback of the changes. See the CorruptionFollowingBusyError wiki page for a discussion of why this is important.

There can only be a single busy handler defined for each database connection. Setting a new busy handler clears any previously set handler. Note that calling sqlite3_busy_timeout() will also set or clear the busy handler.

The busy callback should not take any actions which modify the database connection that invoked the busy handler. Any such actions result in undefined behavior.

Requirements: H12311 H12312 H12314 H12316 H12318

A busy handler must not close the database connection or prepared statement that invoked the busy handler.


Set A Busy Timeout

int 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 "ms" milliseconds of sleeping, the handler returns 0 which causes sqlite3_step() to return SQLITE_BUSY or SQLITE_IOERR_BLOCKED.

Calling this routine with an argument less than or equal to zero turns off all busy handlers.

There can only be a single busy handler for a particular database connection any any given moment. If another busy handler was defined (using sqlite3_busy_handler()) prior to calling this routine, that other busy handler is cleared.

Requirements: H12341 H12343 H12344


Count The Number Of Rows Modified

int sqlite3_changes(sqlite3*);

This function returns the number of database rows that were changed or inserted or deleted by the most recently completed SQL statement on the database connection specified by the first parameter. Only changes that are directly specified by the INSERT, UPDATE, or DELETE statement are counted. Auxiliary changes caused by triggers are not counted. Use the sqlite3_total_changes() function to find the total number of changes including changes caused by triggers.

Changes to a view that are simulated by an INSTEAD OF trigger are not counted. Only real table changes are counted.

A "row change" is a change to a single row of a single table caused by an INSERT, DELETE, or UPDATE statement. Rows that are changed as side effects of REPLACE constraint resolution, rollback, ABORT processing, DROP TABLE, or by any other mechanisms do not count as direct row changes.

A "trigger context" is a scope of execution that begins and ends with the script of a trigger. Most SQL statements are evaluated outside of any trigger. This is the "top level" trigger context. If a trigger fires from the top level, a new trigger context is entered for the duration of that one trigger. Subtriggers create subcontexts for their duration.

Calling sqlite3_exec() or sqlite3_step() recursively does not create a new trigger context.

This function returns the number of direct row changes in the most recent INSERT, UPDATE, or DELETE statement within the same trigger context.

Thus, when called from the top level, this function returns the number of changes in the most recent INSERT, UPDATE, or DELETE that also occurred at the top level. Within the body of a trigger, the sqlite3_changes() interface can be called to find the number of changes in the most recently completed INSERT, UPDATE, or DELETE statement within the body of the same trigger. However, the number returned does not include changes caused by subtriggers since those have their own context.

See also the sqlite3_total_changes() interface and the count_changes pragma.

Requirements: H12241 H12243

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.


Reset All Bindings On A Prepared Statement

int 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.

Requirements: H13661


Closing A Database Connection

int sqlite3_close(sqlite3 *);

This routine is the destructor for the sqlite3 object.

Applications should finalize all prepared statements and close all BLOB handles associated with the sqlite3 object prior to attempting to close the object. The sqlite3_next_stmt() interface can be used to locate all prepared statements associated with a database connection if desired. Typical code might look like this:

sqlite3_stmt *pStmt;
while( (pStmt = sqlite3_next_stmt(db, 0))!=0 ){
    sqlite3_finalize(pStmt);
}

If sqlite3_close() is invoked while a transaction is open, the transaction is automatically rolled back.

The C parameter to sqlite3_close(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.

Requirements: H12011 H12012 H12013 H12014 H12015 H12019


Number Of Columns In A Result Set

int sqlite3_column_count(sqlite3_stmt *pStmt);

Return the number of columns in the result set returned by the prepared statement. This routine returns 0 if pStmt is an SQL statement that does not return data (for example an UPDATE).

Requirements: H13711


Configuring The SQLite Library

int sqlite3_config(int, ...);

Important: This interface is experimental and is subject to change without notice.

The sqlite3_config() interface is used to make global configuration changes to SQLite in order to tune SQLite to the specific needs of the application. The default configuration is recommended for most applications and so this routine is usually not necessary. It is provided to support rare applications with unusual needs.

The sqlite3_config() interface is not threadsafe. The application must insure that no other SQLite interfaces are invoked by other threads while sqlite3_config() is running. Furthermore, sqlite3_config() may only be invoked prior to library initialization using sqlite3_initialize() or after shutdown by sqlite3_shutdown(). Note, however, that sqlite3_config() can be called as part of the implementation of an application-defined sqlite3_os_init().

The first argument to sqlite3_config() is an integer configuration option that determines what property of SQLite is to be configured. Subsequent arguments vary depending on the configuration option in the first argument.

When a configuration option is set, sqlite3_config() returns SQLITE_OK. If the option is unknown or SQLite is unable to set the option then this routine returns a non-zero error code.

Requirements: H14103 H14106 H14120 H14123 H14126 H14129 H14132 H14135 H14138 H14141 H14144 H14147 H14150 H14153 H14156 H14159 H14162 H14165 H14168


Database Connection For Functions

sqlite3 *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.

Requirements: H16253


Register A Virtual Table Implementation

int sqlite3_create_module(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *p,   /* Methods for the module */
  void *pClientData          /* Client data for xCreate/xConnect */
);

Important: This interface is experimental and is subject to change without notice.

This routine is used to register a new virtual table module name. Module names must be registered before creating a new virtual table using the module, or before using a preexisting virtual table for the module.

The module name is registered on the database connection specified by the first parameter. The name of the module is given by the second parameter. The third parameter is a pointer to the implementation of the virtual table module. The fourth parameter is an arbitrary client data pointer that is passed through into the xCreate and xConnect methods of the virtual table module when a new virtual table is be being created or reinitialized.

This interface has exactly the same effect as calling sqlite3_create_module_v2() with a NULL client data destructor.


Register A Virtual Table Implementation

int sqlite3_create_module_v2(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *p,   /* Methods for the module */
  void *pClientData,         /* Client data for xCreate/xConnect */
  void(*xDestroy)(void*)     /* Module destructor function */
);

Important: This interface is experimental and is subject to change without notice.

This routine is identical to the sqlite3_create_module() method, except that it has an extra parameter to specify a destructor function for the client data pointer. SQLite will invoke the destructor function (if it is not NULL) when SQLite no longer needs the pClientData pointer.


Number of columns in a result set

int sqlite3_data_count(sqlite3_stmt *pStmt);

Returns the number of values in the current row of the result set.

Requirements: H13771 H13772


Configure database connections

int sqlite3_db_config(sqlite3*, int op, ...);

Important: This interface is experimental and is subject to change without notice.

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 sqlite3_db_config() interface can only be used immediately after the database connection is created using sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().

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. The only choice for this value is SQLITE_DBCONFIG_LOOKASIDE. New verbs are likely to be added in future releases of SQLite. Additional arguments depend on the verb.

Requirements: H14203 H14206 H14209 H14212 H14215


Find The Database Handle Of A Prepared Statement

sqlite3 *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.

Requirements: H13123


Retrieve the mutex for a database connection

sqlite3_mutex *sqlite3_db_mutex(sqlite3*);

This interface returns a pointer 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.


Database Connection Status

int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);

Important: This interface is experimental and is subject to change without notice.

This interface is used to retrieve runtime status information about a single database connection. The first argument is the database connection object to be interrogated. The second argument is the parameter to interrogate. Currently, the only allowed value for the second parameter is SQLITE_DBSTATUS_LOOKASIDE_USED. Additional options will likely appear in future releases of SQLite.

The current value of the requested parameter is written into *pCur and the highest instantaneous value is written into *pHiwtr. If the resetFlg is true, then the highest instantaneous value is reset back down to the current value.

See also: sqlite3_status() and sqlite3_stmt_status().


Declare The Schema Of A Virtual Table

int sqlite3_declare_vtab(sqlite3*, const char *zSQL);

Important: This interface is experimental and is subject to change without notice.

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.


Enable Or Disable Extension Loading

int 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. See ticket #1863.

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.

Extension loading is off by default.


One-Step Query Execution Interface

int 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 convenient way of running one or more SQL statements without having to write a lot of C code. The UTF-8 encoded SQL statements are passed in as the second parameter to sqlite3_exec(). The statements are evaluated one by one until either an error or an interrupt is encountered, or until they are all done. The 3rd parameter is an optional callback that is invoked once for each row of any query results produced by the SQL statements. The 5th parameter tells where to write any error messages.

The error message passed back through the 5th parameter is held in memory obtained from sqlite3_malloc(). To avoid a memory leak, the calling application should call sqlite3_free() on any error message returned through the 5th parameter when it has finished using the error message.

If the SQL statement in the 2nd parameter is NULL or an empty string or a string containing only whitespace and comments, then no SQL statements are evaluated and the database is not changed.

The sqlite3_exec() interface is implemented in terms of sqlite3_prepare_v2(), sqlite3_step(), and sqlite3_finalize(). The sqlite3_exec() routine does nothing to the database that cannot be done by sqlite3_prepare_v2(), sqlite3_step(), and sqlite3_finalize().

The first parameter to sqlite3_exec() must be an valid and open database connection.

The database connection must not be closed while sqlite3_exec() is running.

The calling function should use sqlite3_free() to free the memory that *errmsg is left pointing at once the error message is no longer needed.

The SQL statement text in the 2nd parameter to sqlite3_exec() must remain unchanged while sqlite3_exec() is running.

Requirements: H12101 H12102 H12104 H12105 H12107 H12110 H12113 H12116 H12119 H12122 H12125 H12131 H12134 H12137 H12138


Enable Or Disable Extended Result Codes

int 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 considerations.

Requirements: H12201 H12202


Low-Level Control Of Database Files

int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);

The sqlite3_file_control() interface makes a direct call to the xFileControl method for the sqlite3_io_methods object associated with a particular database identified by the second argument. The name of the database is the name assigned to the database by the ATTACH SQL command that opened the database. To control the main database file, use the name "main" or a NULL pointer. The third and fourth parameters to this routine are passed directly through to the second and third parameters of the xFileControl method. The return value of the xFileControl method becomes the return value of this routine.

If the second parameter (zDbName) does not match the name of any open database file, then SQLITE_ERROR is returned. This error code is not remembered and will not be recalled by sqlite3_errcode() or sqlite3_errmsg(). The underlying xFileControl method might also return SQLITE_ERROR. There is no way to distinguish between an incorrect zDbName and an SQLITE_ERROR return from the underlying xFileControl method.

See also: SQLITE_FCNTL_LOCKSTATE


Destroy A Prepared Statement Object

int sqlite3_finalize(sqlite3_stmt *pStmt);

The sqlite3_finalize() function is called to delete a prepared statement. If the statement was executed successfully or not executed at all, then SQLITE_OK is returned. If execution of the statement failed then an error code or extended error code is returned.

This routine can be called at any point during the execution of the prepared statement. If the virtual machine has not completed execution when this routine is called, that is like encountering an error or an interrupt. Incomplete updates may be rolled back and transactions canceled, depending on the circumstances, and the error code returned will be SQLITE_ABORT.

Requirements: H11302 H11304


Interrupt A Long-Running Query

void sqlite3_interrupt(sqlite3*);

This function causes any pending database operation to abort and return at its earliest opportunity. This routine is typically called in response to a user action such as pressing "Cancel" or Ctrl-C where the user wants a long query operation to halt immediately.

It is safe to call this routine from a thread different from the thread that is currently running the database operation. But it is not safe to call this routine with a database connection that is closed or might close before sqlite3_interrupt() returns.

If an SQL operation is very nearly finished at the time when sqlite3_interrupt() is called, then it might not have an opportunity to be interrupted and might continue to completion.

An SQL operation that is interrupted will return SQLITE_INTERRUPT. If the interrupted SQL operation is an INSERT, UPDATE, or DELETE that is inside an explicit transaction, then the entire transaction will be rolled back automatically.

The sqlite3_interrupt(D) call is in effect until all currently running SQL statements on database connection D complete. Any new SQL statements that are started after the sqlite3_interrupt() call and before the running statements reaches zero are interrupted as if they had been running prior to the sqlite3_interrupt() call. New SQL statements that are started after the running statement count reaches zero are not effected by the sqlite3_interrupt(). A call to sqlite3_interrupt(D) that occurs when there are no running SQL statements is a no-op and has no effect on SQL statements that are started after the sqlite3_interrupt() call returns.

Requirements: H12271 H12272

If the database connection closes while sqlite3_interrupt() is running then bad things will likely happen.


Last Insert Rowid

sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);

Each entry in an SQLite table has a unique 64-bit signed integer key called the "rowid". The rowid is always available as an undeclared column named ROWID, OID, or _ROWID_ as long as those names are not also used by explicitly declared columns. If the table has a column of type INTEGER PRIMARY KEY then that column is another alias for the rowid.

This routine returns the rowid of the most recent successful INSERT into the database from the database connection in the first argument. If no successful INSERTs have ever occurred on that database connection, zero is returned.

If an INSERT occurs within a trigger, then the rowid of the inserted row is returned by this routine as long as the trigger is running. But once the trigger terminates, the value returned by this routine reverts to the last value inserted before the trigger fired.

An INSERT that fails due to a constraint violation is not a successful INSERT and does not change the value returned by this routine. Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK, and INSERT OR ABORT make no changes to the return value of this routine when their insertion fails. When INSERT OR REPLACE encounters a constraint violation, it does not fail. The INSERT continues to completion after deleting rows that caused the constraint problem so INSERT OR REPLACE will always change the return value of this interface.

For the purposes of this routine, an INSERT is considered to be successful even if it is subsequently rolled back.

Requirements: H12221 H12223

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 Limits

int 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. The function returns the old limit.

If the new limit is a negative number, the limit is unchanged. For the limit category of SQLITE_LIMIT_XYZ there is a hard upper bound set by a compile-time C preprocessor macro named SQLITE_MAX_XYZ. (The "_LIMIT_" in the name is changed to "_MAX_".) Attempts to increase a limit above its hard upper bound are silently truncated to the hard upper limit.

Run time limits are intended for use in applications that manage both their own internal database and also databases that are controlled by untrusted external sources. An example application might be a 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.

Requirements: H12762 H12766 H12769


Load An Extension

int sqlite3_load_extension(
  sqlite3 *db,          /* Load the extension into this database connection */
  const char *zFile,    /* Name of the shared library containing extension */
  const char *zProc,    /* Entry point.  Derived from zFile if 0 */
  char **pzErrMsg       /* Put error message here if not 0 */
);

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.

The entry point is zProc.

zProc may be 0, in which case the name of the entry point defaults to "sqlite3_extension_init".

The sqlite3_load_extension() interface shall return 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() prior to calling this API, otherwise an error will be returned.


Find the next prepared statement

sqlite3_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.

Requirements: H13143 H13146 H13149 H13152


Overload A Function For A Virtual Table

int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);

Important: This interface is experimental and is subject to change without notice.

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 Callbacks

void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);

This routine configures a callback function - the progress callback - that is invoked periodically during long running calls to sqlite3_exec(), sqlite3_step() and sqlite3_get_table(). An example use for this interface is to keep a GUI updated during a large query.

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 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.

Requirements: H12911 H12912 H12913 H12914 H12915 H12916 H12917 H12918


Pseudo-Random Number Generator

void 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 build-in random() and randomblob() SQL functions. This interface allows applications to access the same PRNG for other purposes.

A call to this routine stores N bytes of randomness into buffer P.

The first time this routine is invoked (either internally or by the application) the PRNG is seeded using randomness obtained from the xRandomness method of the default sqlite3_vfs object. On all subsequent invocations, the pseudo-randomness is generated internally and without recourse to the sqlite3_vfs xRandomness method.

Requirements: H17392


Attempt To Free Heap Memory

int 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.

Requirements: H17341 H17342


Reset A Prepared Statement Object

int 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.

If the most recent call to sqlite3_step(S) for the prepared statement S returned SQLITE_ROW or SQLITE_DONE, or if sqlite3_step(S) has never before been called on S, then sqlite3_reset(S) returns SQLITE_OK.

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 does not change the values of any bindings on the prepared statement S.


Reset Automatic Extension Loading

void sqlite3_reset_auto_extension(void);

This function disables all previously registered automatic extensions. It undoes the effect of all prior