Appendix E. C Interface Reference

This appendix lists the C library functions that can be used to communicate with a SQLite database.

The Core API

The core interface to the SQLite library is considered to be just three functions that allow you to open and close a database and to execute a query using a user-defined callback function. In this section we'll also look at the error codes returned from the core API.

Opening and Closing a Database

You can open and close a database as follows:

sqlite *sqlite_open(
  const char *dbname,
  int mode,
  char **errmsg
);

void sqlite_close(sqlite *db);

The return value of sqlite_open() and the argument to sqlite_close() is an opaque sqlite data structure.

typedef struct sqlite sqlite;

Executing a Query

You can execute a query as follows:

int sqlite_exec(
  sqlite *db,
  char *sql,
  int (*xCallback)(void *, int, char **, char **),
  void pArg,
  char **errmsg
);

The callback function has the following prototype:

int callback(void *pArg, int argc, char **argv, char **columnNames) {
  return 0;
}

Error Codes

This section describes SQLite error codes; each error code is followed by a description of its meaning.

#define SQLITE_OK           0   /* Successful result */

Returned if everything worked and there were no errors.

#define SQLITE_ERROR        1   /* SQL error or missing database */

Indicates an error in the SQL statement being executed.

#define SQLITE_INTERNAL     2   /* An internal logic error in SQLite */

Indicates that an internal consistency check within the SQLite library failed. This code will only ever be returned as a result of a bug, and such occurrences should be reported to the SQLite mailing list.

#define SQLITE_PERM         3   /* Access permission denied */

Indicates that the database file cannot be opened due to insufficient file permissions.

#define SQLITE_ABORT        4   /* Callback routine requested an abort */

This value is returned if the callback function returns a non-zero value.

#define SQLITE_BUSY         5   /* The database file is locked */

Indicates that another program or thread has the database locked. Only one thread can open a database file for writing at a time, though multiple reads can take place simultaneously.

#define SQLITE_LOCKED       6   /* A table in the database is locked */

Indicates that the database is locked by a recursive call to sqlite_exec(). Calls to sqlite_exec() from within a callback function are permitted as long as they do not attempt to write to the same table.

#define SQLITE_NOMEM        7   /* A malloc() failed */

This value is returned if a call to malloc() fails due to not enough system memory being available.

#define SQLITE_READONLY     8   /* Attempt to write a readonly database */

Indicates that an attempt was made to write to a database file that was opened in read-only mode.

#define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite_interrupt() */

This value is returned if a database operation is interrupted by the sqlite_interrupt() function being called.

#define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */

This value is returned if the operating system fails to perform a disk I/O operation, for instance if there is no space left on the device.

#define SQLITE_CORRUPT     11   /* The database disk image is malformed */

This value would only be returned as a consequence of an unknown error in SQLite or a hardware or operating-system malfunction. It may indicate that the database file has become corrupted, or that a disk I/O error has forced SQLite to leave the database file in a corrupted state.

#define SQLITE_NOTFOUND    12   /* (Internal Only) Table or record not found */

For internal use only. This value will never be returned by sqlite_exec().

#define SQLITE_FULL        13   /* Insertion failed because database is full */

This value is returned if an insert operation fails because the database is too big to take any more information, for instance when the size of the database file would exceed the operating system's file size limit.

#define SQLITE_CANTOPEN    14   /* Unable to open the database file */

This value indicates that that database file could not be opened for some other reason that does not have its own return code.

#define SQLITE_PROTOCOL    15   /* Database lock protocol error */

Indicates that the file-locking protocol on SQLite's rollback journal files has been violated.

#define SQLITE_EMPTY       16   /* (Internal Only) Database table is empty */

For internal use only. This value will never be returned by sqlite_exec().

#define SQLITE_SCHEMA      17   /* The database schema changed */

Indicates that another process has altered the database schema since it was first read into memory when the database was initially opened. SQLite will re-read the schema when this happens but will not be able to complete the SQL statement that was being processed. Submitting the statement a second time will usually allow the command to be executed.

#define SQLITE_TOOBIG      18   /* Too much data for one row of a table */

Indicates that the maximum row size for a table would be exceeded. The limit is defined at compile time by the MAX_BYTES_PER_ROW value in sqliteInt.h.

#define SQLITE_CONSTRAINT  19   /* Abort due to contraint violation */

Indicates that the SQL statement would have violated a database constraint.

#define SQLITE_MISMATCH    20   /* Data type mismatch */

This value is returned when an attempt is made to insert non-integer data into an INTEGER PRIMARY KEY column.

#define SQLITE_MISUSE      21   /* Library used incorrectly */

Indicates that the SQLite library has been misused in some way, for instance calling sqlite_exec() after the database has been closed, or calling sqlite_step() after a SQLITE_DONE or SQLITE_ERROR return code.

#define SQLITE_NOLFS       22   /* Uses OS features not supported on host */

This value is returned if an attempt is made to access a database file larger than 2GB in size on a legacy operating system that does not include large file support.

#define SQLITE_AUTH        23   /* Authorization denied */

Indicates that the authorizer callback has disallowed the SQL you are attempting to execute.

The Non-Callback API

The non-callback API provides an alternative way to retrieve data from a SQLite database by compiling an SQL statement into a virtual machine of type sqlite_vm:

typedef struct sqlite_vm sqlite_vm;

Creating a Virtual Machine

You can create a SQLite virtual machine as follows:

int sqlite_compile(
  sqlite *db,              /* The open database */
  const char *zSql,        /* SQL statement to be compiled */
  const char **pzTail,     /* OUT: uncompiled tail of zSql */
  sqlite_vm **ppVm,        /* OUT: the virtual machine to execute zSql */
  char **pzErrmsg          /* OUT: Error message. */
);

The return code from sqlite_compile() is SQLITE_OK if the operation is successful; otherwise, one of the error codes listed in the preceding example is returned.

Step-by-Step Execution of an SQL Statement

Each invocation of sqlite_step() for a virtual machine, except the last one, returns a single row of the result:

int sqlite_step(
  sqlite_vm *pVm,          /* The virtual machine to execute */
  int *pN,                 /* OUT: Number of columns in result */
  const char ***pazValue,  /* OUT: Column data */
  const char ***pazColName /* OUT: Column names and datatypes */
);

int sqlite_finalize(
  sqlite_vm *pVm,          /* The virtual machine to be finalized */
  char **pzErrMsg          /* OUT: Error message */
);

Return Codes

The return code from sqlite_step() can be SQLITE_BUSY, SQLITE_ERROR, SQLITE_MISUSE, or either of the following.

#define SQLITE_ROW         100  /* sqlite_step() has another row ready */

Indicates that another row of result data is available.

#define SQLITE_DONE        101  /* sqlite_step() has finished executing */

Indicates that the SQL statement has been completely executed and sqlite_finalize() should now be called.

The return code from sqlite_finalize() indicates the overall success of the SQL command and will be the same as if the query had been executed using sqlite_exec().

The Extended API

The extended API provides a range of non-core functions to assist with development of software that uses an embedded SQLite database.

Finding Information About the SQLite Library

const char sqlite_version[];

Contains the current library version number.

const char sqlite_encoding[];

Contains the current library encoding version.

Finding Information About Changes to the Database

Several functions can return information about changes that have been made to the database.

int sqlite_last_insert_rowid(sqlite *db);

Returns the most recently assigned autoincrementing value of an INTEGER PRIMARY KEY field.

int sqlite_changes(sqlite *db);

Returns the number of rows affected by an UPDATE or DELETE statement.

Checking SQL Statements

int sqlite_complete(const char *sql);

Returns TRUE if a complete SQL statement is provided, that is, the statement ends with a semicolon. Returns FALSE if more characters are required.

Interrupting an SQL Statement

void sqlite_interrupt(sqlite *db);

Causes the current database operation to exist at the first opportunity, returning SQLITE_INTERRUPT to the calling function.

Convenience Functions

The following function fetches the entire result of a database query with a single function call:

int sqlite_get_table(
  sqlite *db,
  char *sql,
  char ***result,
  int *nrow,
  int *ncolumn,
  char **errmsg
);

The result will be an array of string pointers containing one element for each column of each row in the result. The first ncolumn elements contain the column names returned. Use nrow and ncolumn to determine which elements of the array correspond to which values.

The return code from sqlite_get_table() is the same as if sqlite_exec() had executed the query.

void sqlite_free_table(char **azResult);

Frees memory allocated by sqlite_get_table() when it is no longer required.

The _printf() Wrapper Functions

char *sqlite_mprintf(const char *zFormat, ...);

Works like sprintf() but also allows the format strings %q and %Q to manipulate strings for database storage. %q escapes any single quotes by doubling the quote character; %Q additionally encloses the result string within single quotes.

int sqlite_exec_printf(
  sqlite *db,
  char *sqlFormat,
  int (*)(void *, int, char **, char **),
  void *pArg,
  char **errmsg,
  ...
);

Combines sqlite_exec() with sqlite_mprintf(). The format string references items from the sixth argument onwards.

int sqlite_get_table_printf(
  sqlite *db,
  char *sql,
  char ***result,
  int *nrow,
  int *ncolumn,
  char **errmsg,
  ...
);

Combines sqlite_get_table() with sqlite_mprintf(). The format string references items from the seventh argument onwards.

Memory Management

void sqlite_freemem(void *p);

Where the library allocates memory using malloc() and returns a pointer to that data, such as errmsg or the result of sqlite_mprintf(), it is the responsibility of the calling program to free that memory.

Dealing with Locked Database Files

void sqlite_busy_timeout(
  sqlite *db,
  int ms
);

Specifies an amount of time in milliseconds for which SQLite will wait for a file lock to clear before returning SQLITE_BUSY.

void sqlite_busy_handler(
  sqlite *db,
  int (*xBusy)(void *, const char *, int),
  void *pArg
);

Specifies an alternative busy handler function xBusy. A non-zero response from the handler will cause SQLite to retry; a zero response causes SQLITE_BUSY to be returned.

Performing Background Jobs During Large Queries

void sqlite_progress_handler(
  sqlite *db,
  int nOps,
  int (*xProgress)(void *),
  void *pArg
);

Registers a callback routine xProgress to be invoked every nOps virtual machine operations during long-running query execution.

Adding New SQL Functions

SQLite allows you to add new functions to the SQL language that can subsequently be used in your queries.

Registering Functions

int sqlite_create_function(
  sqlite *db,
  const char *zName,
  int nArg,
  void (*xFunc)(sqlite_func*,int,const char**),
  void *pUserData
);

Creates a regular function in SQL from the function pointed to by xFunc.

int sqlite_create_aggregate(
  sqlite *db,
  const char *zName,
  int nArg,
  void (*xStep)(sqlite_func*,int,const char**),
  void (*xFinalize)(sqlite_func*),
  void *pUserData
);

Creates an aggregating function with function xStep executed once for each row returned by the query, and xFinalize invoked once after all rows have been returned.

The xFunc and xStep arguments are pointers to functions with the following prototype.

void xFunc(
  sqlite_func *context,
  int argc,
  const char **argv
);

The finalize function requires only the context argument.

void xFinalize(sqlite_func *context);

The context argument is an opaque data type sqlite_func.

typedef struct sqlite_func sqlite_func;

Setting Return Values

char *sqlite_set_result_string(
  sqlite_func *p,
  const char *zResult,
  int n
);

void sqlite_set_result_int(
  sqlite_func *p,
  int iResult
);

void sqlite_set_result_double(
  sqlite_func *p,
  double rResult
);

Use the appropriate function for the data type that is to be returned to SQL.

void sqlite_set_result_error(
  sqlite_func *p,
  const char *zMsg,
  int n);

Returns an error code to SQLite.

The integer n parameter to sqlite_set_result_string() and sqlite_set_result_error() is the number of characters to be returned. A negative value will return up to and including the first character.

Referencing Arbitrary Data

void *sqlite_user_data(sqlite_func *p);

Returns the pUserData pointer given in the corresponding sqlite_create_function() or sqlite_create_aggregate() call.

void *sqlite_aggregate_context(
  sqlite_func *p,
  int nBytes
);

Allocates memory that is unique to a particular instance of the SQL function being called. Memory allocated is automatically cleaned up when the finalize function is invoked.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.126.242