Sqlite3
Description
Bindings to version 3.x of the SQLite API.
Author
Repository
This egg is hosted on the CHICKEN Subversion repository:
https://anonymous@code.call-cc.org/svn/chicken-eggs/release/5/sqlite3
If you want to check out the source code repository of this egg and you are not familiar with Subversion, see this page.
Requirements
Documentation
The API of SQLite changed significantly from version 2.x to 3.x. These are new bindings to the modified API, which are reasonably complete -- most procedures that take callback arguments are missing, though.
For in-depth information on the functionality of the routines and general information you should consult the SQLite documentation as well as this manual.
Exceptions
Unless otherwise indicated, all procedures and methods in this egg may throw an exception of the kind (exn sqlite3) if something goes wrong. This exception will contain a status property indicating the return value of the operation that failed:
- error
- SQL error or missing database
- internal
- An internal logic error in SQLite
- permission
- Access permission denied
- abort
- Callback routine requested an abort
- busy
- The database file is locked
- locked
- A table in the database is locked
- no-memory
- A malloc() failed
- read-only
- Attempt to write a readonly database
- interrupt
- Operation terminated by sqlite-interrupt()
- io-error
- Some kind of disk I/O error occurred
- corrupt
- The database disk image is malformed
- not-found
- (Internal Only) Table or record not found
- full
- Insertion failed because database is full
- cant-open
- Unable to open the database file
- protocol
- Database lock protocol error
- empty
- (Internal Only) Database table is empty
- schema
- The database schema changed
- too-big
- Too much data for one row of a table
- constraint
- Abort due to contraint violation
- mismatch
- Data type mismatch
- misuse
- Library used incorrectly
- no-lfs
- Uses OS features not supported on host
- authorization
- Authorization denied
- done
- step! has finished executing, so no further data is ready
Abstract data types
[procedure] (database? OBJECT) => BOOLEANChecks whether a value represents an SQLite database.
[procedure] (error-database LOCATION OBJECT [ARGUMENT-NAME]) => VOIDRaises a type error saying that a database was expected instead of the given value.
[procedure] (check-database LOCATION OBJECT [ARGUMENT-NAME]) => VOIDRaises a type error like error-database does, unless the given value satisfies database?
[procedure] (statement? OBJECT) => BOOLEANChecks whether the value v represents an SQL statement.
[procedure] (error-statement LOCATION OBJECT [ARGUMENT-NAME]) => VOIDRaises a type error saying that a statement was expected instead of the given value.
[procedure] (check-statement LOCATION OBJECT [ARGUMENT-NAME]) => VOIDRaises a type error like error-statement does, unless the given value satisfies statement?
Managing databases
[procedure] (open-database PATH) => DATABASEOpens the indicated database file and returns a database object for it.
Since version 3.6.0 the given path is passed to SQLite3 without modifications. Before it was subject to special expansions like paths passed to open-input-file and similar procedures used to be.
[procedure] (define-collation DATABASE NAME [PROC]) => VOIDIf a procedure is given, registers a new collation sequence identified by name for use in the context of database handle db. If no procedure is passed, the collation sequence with the given name is removed.
PROC should have the signature (PROC STRING STRING) => FIXNUM. It should return a negative number if the first argument sorts before the second, a positive number if the second sorts before the first and zero if they are equal.
As PROC will be called in a callback context from within step!, safety measures are installed to avoid throwing any exceptions, invoking continuations or returning invalid values from it. Attempts to do so will result in a 0 return value and warning messages.
[procedure] (define-function DATABASE NAME N PROC) => VOID[procedure] (define-function DATABASE NAME N STEP-PROC SEED [FINAL-PROC]) => VOID
Registers a new SQL function identified by NAME for use in the context of the given database handle. If STEP-PROC and SEED are given, the new function becomes an aggregate function. Once registered, functions cannot be deleted.
N is the number of parameters the new SQL function takes or -1 to allow any number of arguments.
PROC should have the signature (PROC . PARAMS) => OBJECT. It is called with the N parameters given to the SQL function converted into Scheme objects like by column-data. The return value is converted into an SQLite data object like by bind!. A return value satisfying sql-null? corresponds to NULL in SQLite.
STEP-PROC should have the signature (STEP-PROC SEED PARAMS) => SEED. It is called with the parameters given to the SQL function for every row being processed. The seed value passed is initially the one given as an argument to define-function; for subsequent calls it is the last value returned by STEP-PROC and after completion of FINAL-PROC it will be the initial value again.
FINAL-PROC should have the signature (FINAL-PROC SEED) => OBJECT and transforms the last seed value into the value to be returned from the aggregate function. If it is not explicitly specified, STEP-PROC defaults to the identity function.
As PROC, STEP-PROC and FINAL-PROC will be called in a callback context from within step!, safety measures are installed to avoid throwing any exceptions, invoking continuations or returning invalid values from them. Attempts to do such things will result in NULL return values and warning messages.
[procedure] (set-busy-handler! DATABASE PROC) => VOIDInstalls the supplied procedure as the application's busy handler, or removes it if #f. When the database returns a busy error code, the egg will invoke this handler repeatedly until it returns #f. The handler will be called with arguments DATABASE and COUNT (number of times invoked for the same operation).
As PROC is not called in a callback context, it is legal to invoke captured continuations, and it is safe in the presence of multiple threads. In general, this handler should give up at some point to avoid possible deadlock.
For an example handler, see the code of make-busy-timeout.
[procedure] (make-busy-timeout MS) => PROCReturns a handler suitable for use with set-busy-handler!. It polls in increasing intervals until the timeout in milliseconds is reached. The handler is non-blocking.
(define open-database/timeout
(let ((handler (make-busy-timeout 2000)))
(lambda (db-name)
(let ((db (open-database db-name)))
(set-busy-handler! db handler)
db))))
[procedure] (interrupt! DATABASE) => VOID
Cancels any running database operation as soon as possible.
This function is always successful and never throws an exception.
[procedure] (auto-committing? DATABASE) => BOOLEANChecks whether the database is currently in auto committing mode, i.e. no transaction is currently active.
This function always returns a state and never throws an exception.
[procedure] (change-count DATABASE [TOTAL]) => CARDINAL-INTEGERReturns the number of rows changed by the last statement (if (not TOTAL), which is the default) or since the database was opened (if TOTAL).
This function always returns a count and never throws an exception.
[procedure] (last-insert-rowid DATABASE) => INTEGERReturns the row ID of the last row inserted in db. This function always returns a number and never throws an exception.
[procedure] (finalize! DATABASE [FINALIZE-STATEMENTS?]) => VOID[procedure] (finalize! STATEMENT) => VOID
Closes the given database or finalizes the given statement.
Every statement must be finalized to free its resources and discard it before the database itself can be finalized. However, if FINALIZE-STATEMENTS? is not #f, finalizing the database triggers automatic finalization of all statements first. FINALIZE-STATEMENTS? defaults to #f.
Note that both the SQLite3 egg and the SQLite3 library itself try to detect the use of already finalized statement or database handles in API calls, but the detection is not always possible and you might crash the program by using an already finalized handle.
Managing statements
[procedure] (prepare DATABASE SQL) => STATEMENT, SQLCompiles the first SQL statement in SQL and returns a statement and the tail of the SQL code, which was not compiled (or an empty string).
[procedure] (source-sql STATEMENT) => STRINGRetrieves the SQL source code of a statement.
[procedure] (column-count STATEMENT) => CARDINAL-INTEGERCan be applied to any statement and returns the number of columns it will return as results.
This procedure always succeeds and never throws an exception.
[procedure] (column-name STATEMENT I) => STRINGCan be applied to any statement and returns the name of the column number I (counting from 0) as a string or #f if the column has no name.
This procedure always succeeds and never throws an exception.
[procedure] (column-declared-type STATEMENT I) => STRINGCan be applied to any statement and returns the declared type (as given in the CREATE statement) of the column number I (counting from 0) as a string or #f if the column has no declared type.
This procedure always succeeds and never throws an exception.
[procedure] (bind-parameter-count STATEMENT) => CARDINAL-INTEGERCan be applied to any statement and returns the number of free parameters that can be bound in the statement.
This procedure always succeeds and never throws an exception.
[procedure] (bind-parameter-index STATEMENT NAME) => CARDINAL-INTEGERCan be applied to any statement and returns the index of the bindable parameter called NAME or #f if no such parameter exists.
This procedure always succeeds and never throws an exception.
[procedure] (bind-parameter-name STATEMENT I) => STRINGCan be applied to any statement and returns the name of the bindable parameter number I (counting from 0) or #f if no such parameter exists or the parameter has no name.
This procedure always succeeds and never throws an exception.
[procedure] (bind! STATEMENT I OBJECT) => VOIDCan be applied to any statement to bind its free parameter number I(counting from 0) to the given value. Scheme types of the value map to SQLite types as follows:
Scheme type | SQLite type |
---|---|
boolean? | integer: #t = 1, #f = 0 |
fixnum? | integer |
real? | float |
string? | text |
blob? | blob |
sql-null? | null |
Unless there is internal trouble in SQLite, this method should always succeeds and never throw an exception. For invalid parameter indices the method just silently does nothing.
[procedure] (bind-parameters! STATEMENT . PARAMETERS) => VOIDResets the statement and binds all its free parameters.
In addition to just listing the values to bind to the statement's parameters in sequence, you may specify parameters prefixed by keywords that are resolved to parameter indices by prefixing their names with ":" and resolving them using bind-parameter-index.
[procedure] (step! STATEMENT) => BOOLEANSingle-steps the execution of STATEMENT and returns #t if a result row was produced, #f if no further results are available as the statement has been stepped through. This procedure must be called at least once before any results can be retrieved from the statement.
[procedure] (column-type STATEMENT I) => SYMBOLCan be applied to a statement that has just been stepped (otherwise it returns #f) and returns the SQLite type of the result column number I (counting from 0) as a symbol.
The return value can be one of the symbols null, integer, float, text or blob.
This procedure always succeeds and never throws an exception.
[procedure] (column-data STATEMENT I) => OBJECTCan be applied to a statement that has just been stepped. Consults column-type and column-declared-type to determine the type of the indicated column and to return its data as an appropriate Scheme object:
SQLite type | Scheme type |
---|---|
integer, declared "bool"" | boolean? |
integer | integer? |
float | real? |
text | string? |
blob | blob? |
null | sql-null? |
The declared type of a column is considered to be boolean if the type declaration contains the character sequence "bool" anywhere, ignoring case.
This procedure always succeeds and never throws an exception.
[procedure] (reset! STATEMENT) => VOIDCan be applied to any statement and resets it such that execution using step! will perform all operations of the statement again.
Simple statement interface
[procedure] (call-with-temporary-statements PROC DATABASE . SQLS) => OBJECTCompiles the SQL sources into statements in the context of DATABASE, applies PROC to these statements and returns PROC's result. The statements are created and finalized in dynamic-wind entry and exit blocks around the application of PROC.
[procedure] (execute STATEMENT . PARAMETERS) => VOID)[procedure] (execute DATABASE SQL . PARAMETERS) => VOID
(Compiles the given SQL), resets the statement, binds the statement's free parameters and executes the statement ignoring possible results from it.
[procedure] (update STATEMENT . PARAMETERS) => CARDINAL-INTEGER[procedure] (update DATABASE SQL . PARAMETERS) => CARDINAL-INTEGER
(Compiles the given SQL), resets the statement, binds the statement's free parameters and executes the specified statement ignoring possible results from it, returning the result of applying change-count to the affected database after the execution of the statement instead.
[procedure] (first-result STATEMENT . PARAMETERS) => OBJECT[procedure] (first-result DATABASE SQL . PARAMETERS) => OBJECT
(Compiles the given SQL), resets the statement, binds the statement's free parameters and single-steps the statement once returning the value of the first column in the first result row. Resets the statement again just before returning.
If the given statement does not yield any results, an (exn sqlite3) is thrown with the status-property set to done.
[procedure] (first-row STATEMENT . PARAMETERS) => LIST[procedure] (first-row DATABASE SQL . PARAMETERS) => LIST
(Compiles the given SQL), resets the statement, binds the statement's free parameters and single-steps the statement once returning all columns in the first result row as a list.
If the given statement does not yield any results, an (exn sqlite3) is thrown with the status-property set to done.
[procedure] (fold-row PROC INIT STATEMENT . PARAMETERS) => OBJECT[procedure] (fold-row PROC INIT DATABASE SQL . PARAMETERS) => OBJECT
(Compiles the given SQL), resets the statement, binds the statement's free parameters and executes it step by step. After each step, the column values of the current result row are retrieved and PROC is applied to the current folded value, set to INIT in the first step, and the column values. The result of the application becomes the new folded value.
[procedure] (for-each-row PROC STATEMENT . PARAMETERS) => VOID[procedure] (for-each-row PROC DATABASE SQL . PARAMETERS) => VOID
(Compiles the given SQL), resets the statement, binds the statement's free parameters and executes it step by step. After each step, the column values of the current result row are retrieved and PROC is applied to them. The results of this application are discarded.
[procedure] (map-row PROC STATEMENT . PARAMETERS) => LIST[procedure] (map-row PROC DATABASE SQL . PARAMETERS) => LIST
(Compiles the given SQL), resets the statement, binds the statement's free parameters and executes it step by step. After each step, the column values of the current result row are retrieved and PROC is applied to them. The results of these applications are collected into a list.
Utility functions
[procedure] (with-transaction DATABASE THUNK [TYPE]) => OBJECTRuns THUNK within the scope of a transaction on the database and returns the return value from THUNK.
The transaction is committed upon exit from THUNK if THUNK returns a true value. If THUNK returns a false value or throws an exception, the transaction is rolled back.
The TYPE" of the transaction can be specified as one of the symbols deferred (the default), immediate or exclusive.
[procedure] (sql-complete? SQL) => BOOLEANChecks whether SQL comprises at least one complete SQL statement.
[procedure] (enable-shared-cache! BOOLEAN) => BOOLEANEnables (or disables) the sharing of the database cache and schema data structures between connections to the same database.
Returns whether the shared cache is now enabled. If sqlite3 was compiled with the feature disable-shared-cache defined, this procedure will unconditionally return #f, otherwise it will either return the value of its only argument or throw an error.
[procedure] (enable-load-extension! DATABASE BOOLEAN) => BOOLEANEnables (or disables) the loading of native code extensions into the database engine through the use of SQL statements.
[procedure] (database-version) => STRINGReturns a string identifying the version of SQLite in use.
[procedure] (database-memory-used) => CARDINAL-INTEGERReturns the amount of memory currently in use by the database engine.
[procedure] (database-memory-highwater [RESET?]) => CARDINAL-INTEGERReturns the maximum amount of memory that was in use by the database engine since the counter was last reset or since the program started. Resets the counter if RESET? is not #f. RESET? defaults to #f.
Changelog
- 3.7.0 Added enable-load-extension! procedure
- 3.6.1 Added a compilation option to disable shared cache functionality
- 3.6.0 Removed use of ##sys#expand-home-path, which no longer exists
- 3.5.1 Corrected parameter error checks for define-function
- 3.5.0 Switched to less error prone internal C API
- 3.4.0 Added optional automatic statement finalization when a database is finalized
- 3.3.1 Added bindings for database memory statistics
- 3.3.0 Switched to using (sql-null) for NULL values
- 3.2.1 Added a test suite
- 3.2.0 Removed the unsafe busy handler and timeout APIs, since a safe API exists
- 3.1.0 bind-parameters! can now handle keyword arguments
- 3.0.0 Ported to CHICKEN 4, removed dependencies on TinyCLOS and EasyFFI
- 2.0.8 Add busy handler callbacks; ensure finalize! is called on exception. [Jim Ursetto]
- 2.0.7 Restore error reporting. [Jim Ursetto]
- 2.0.6 Add enable-shared-cache!, requires 3.3.0 or later. [Jim Ursetto]
- 2.0.5 Added some <boolean> support. Change for NULL (<void>) handling. [Kon Lovett]
- 2.0.4 Added sqlite3:fold-row & sqlite3:bind-parameters!. Fix for introduced bug in sqlite3:changes. [Kon Lovett]
- 2.0.3 Added sqlite3:null-value, sqlite3:null-value?, and sqlite3:null. [Kon Lovett]
- 2.0.2 Use of extended define-foreign-enum. Removed deprecated pointer use. [Kon Lovett]
- 2.0.1 Deprecated <byte-vector>, use <blob> [Kon Lovett]
- 2.0.0 Now using (void) to represent NULL
- 1.5.9 dll extension not used anymore in newer chickens [felix]
- 1.5.8 Update for synch 1.3 [Kon Lovett]
- 1.5.7 Updated compiler flags to pull in tinyclos and easyffi
- 1.5.6 Replaced deprecated synch operations [Kon Lovett]
- 1.5.5 Correction in the documentation, added sqlite3:with-transaction
- 1.5.4 Typo fixed thanks to the new imports checking code
- 1.5.3 Proper multithreading locks for the callback code
- 1.5.2 Code cleanups
- 1.5.1 Potential memory leaks removed
- 1.5.0 Support for user defined collation sequences and functions has been added
- 1.4.0 Stale statement handles due to schema changes are now automagically recompiled to keep them valid
- 1.3.1 Several small routines added
- 1.3.0 Special hacks removed as CVS version of SQLite3.3.4 has been fixed
- 1.2.0 Special hacks to deal with "valid" NULL statements
- 1.1.4 Tightened security measures against #f pointers
- 1.1.3 Integers not fitting in a fixnum are now read correctly from the database [thanks to Zbigniew]
- 1.1.2 Setup file patched to call compiled output .dll on Windows
- 1.1.1 All procedures now reset prepared statements where you would do that by hand anyway
- 1.1.0 Promoted sqlite3:call-with-temporary-statement to sqlite3:call-with-temporary-statements and fixed a really stupid coding mistake in sqlite3:changes
- 1.0.3 Fixed C compiler warnings
- 1.0.2 Added a typecheck for increased safety
- 1.0.1 Fixed type mistakes in the source
- 1.0.0 Initial release
License
Copyright (c) 2005-2009, Thomas Chust <chust@web.de>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.