Module Sqlite3
API for Sqlite 3.* databases
Exceptions
exception
InternalError of string
InternalError reason
is raised when the bindings detect an unknown/unsupported situation.
exception
Error of string
Error reason
is raised when some SQL operation is called on a nonexistent handle and the functions does not return a return code, or if there is no error code corresponding to this error. Functions returning return codes communicate errors by returning the specific error code.
exception
RangeError of int * int
RangeError (index, maximum)
is raised if some column or bind operation refers to a nonexistent column or binding. The first entry of the returned tuple is the specified index, the second is the limit which was violated.
Library Information
Types
type db
Database handle. Used to store information regarding open databases and the error code from the last operation if the function implementing that operation takes a database handle as a parameter.
- see https://sqlite.org/threadsafe.html
about thread safety when accessing database handles and also consider using the
mutex
flag withdb_open
if necessary.NOTE: database handles are closed (see
db_close
) automatically when they are reclaimed by the GC unless they have already been closed earlier by the user. It is good practice to manually close database handles to free resources as quickly as possible.
type stmt
Compiled statement handle. Stores information about compiled statements created by the
prepare
orprepare_tail
functions.- see https://sqlite.org/threadsafe.html
about thread safety when accessing statement handles.
type headers
= header array
Type of names of columns returned by queries.
Return codes
module Rc : sig ... end
Column data types
module Data : sig ... end
General database operations
val db_open : ?mode:[ `READONLY | `NO_CREATE ] -> ?uri:bool -> ?memory:bool -> ?mutex:[ `NO | `FULL ] -> ?cache:[ `SHARED | `PRIVATE ] -> ?vfs:string -> string -> db
db_open ?mode ?uri ?memory ?mutex ?cache ?vfs filename
opens the database filefilename
, and returns a database handle.Special filenames: ":memory:" and "" open an in-memory or temporary database respectively. Behaviour explained here: https://www.sqlite.org/inmemorydb.html
The optional arguments
mode
,uri
,memory
andmutex
are only meaningful with SQLite versions >= 3.5,cache
only for versions >= 3.6.18. For older versions an exception will be raised if any of them is set to a non-default value. The database is opened read-only if`READONLY
is passed as mode. The database file will not be created if it is missing and`NO_CREATE
is set. Theuri
parameter enables URI filename interpretation and corresponds toSQLITE_OPEN_URI
in the SQLite3 API. Thememory
parameter opens an in-memory database and corresponds toSQLITE_OPEN_MEMORY
in the SQLite3 API.mutex
determines how the database is accessed. The mutex parameters`NO
and`FULL
correspond toSQLITE_OPEN_NOMUTEX
andSQLITE_OPEN_FULLMUTEX
in the SQLite3 API respectively. The cache parameters`SHARED
and`PRIVATE
correspond toSQLITE_OPEN_SHAREDCACHE
andSQLITE_OPEN_PRIVATECACHE
in the SQLite3 API respectively.- parameter mode
default = read-write, create
- parameter uri
default = false
- parameter memory
default = false
- parameter mutex
default = nothing
- parameter cache
default = nothing
- parameter vfs
default = nothing
val db_close : db -> bool
db_close db
closes databasedb
and invalidates the handle.- returns
false
if database was busy (database not closed in this case!),true
otherwise.
- raises SqliteError
if an invalid database handle is passed.
val let& : db -> (db -> 'a) -> 'a
let& db = db_open "..." in ...scope that uses db...
ensures that the databasedb
is safely closed at the end of the scope, even if there is an exception somewhere in the scope.- raises Fun.Finally_raised
if the database could not be closed successfully.
val enable_load_extension : db -> bool -> bool
enable_load_extension db onoff
enable/disable the SQLite3 load extension.- returns
false
if the operation fails,true
otherwise.
val errcode : db -> Rc.t
errcode db
- returns
the error code of the last operation on database
db
.
- raises SqliteError
if an invalid database handle is passed.
val errmsg : db -> string
errmsg db
- returns
the error message of the last operation on database
db
.
- raises SqliteError
if an invalid database handle is passed.
val last_insert_rowid : db -> int64
last_insert_rowid db
- returns
the index of the row inserted by the last operation on database
db
.
- raises SqliteError
if an invalid database handle is passed.
val exec : db -> ?cb:(row -> headers -> unit) -> string -> Rc.t
exec db ?cb sql
performs SQL-operationsql
on databasedb
. If the operation contains query statements, then the callback functioncb
will be called for each matching row. The first parameter of the callback contains the contents of the row, the second parameter contains the headers of the columns associated with the row. Exceptions raised within the callback will abort the execution and escapeexec
.- returns
the return code of the operation.
- parameter cb
default = no callback
- raises SqliteError
if an invalid database handle is passed.
val exec_no_headers : db -> cb:(row -> unit) -> string -> Rc.t
exec_no_headers db ?cb sql
performs SQL-operationsql
on databasedb
. If the operation contains query statements, then the callback functioncb
will be called for each matching row. The parameter of the callback is the contents of the row. Exceptions raised within the callback will abort the execution and escapeexec_no_headers
.- returns
the return code of the operation.
- raises SqliteError
if an invalid database handle is passed.
val exec_not_null : db -> cb:(row_not_null -> headers -> unit) -> string -> Rc.t
exec_not_null db ~cb sql
performs SQL-operationsql
on databasedb
. If the operation contains query statements, then the callback functioncb
will be called for each matching row. The first parameter of the callback is the contents of the row, which must not contain NULL-values, the second paramater are the headers of the columns associated with the row. Exceptions raised within the callback will abort the execution and escapeexec_not_null
.- returns
the return code of the operation.
- raises SqliteError
if an invalid database handle is passed.
- raises SqliteError
if a row contains NULL.
val exec_not_null_no_headers : db -> cb:(row_not_null -> unit) -> string -> Rc.t
exec_not_null_no_headers db ~cb sql
performs SQL-operationsql
on databasedb
. If the operation contains query statements, then the callback functioncb
will be called for each matching row. The parameter of the callback is the contents of the row, which must not contain NULL-values. Exceptions raised within the callback will abort the execution and escapeexec_not_null_no_headers
.- returns
the return code of the operation.
- raises SqliteError
if an invalid database handle is passed.
- raises SqliteError
if a row contains NULL.
val changes : db -> int
changes db
- returns
the number of rows that were changed or inserted or deleted by the most recently completed SQL statement on database
db
.
Prepared Statements
val prepare : db -> string -> stmt
prepare db sql
compile SQL-statementsql
for databasedb
into bytecode. The statement may be only partially compiled. In this caseprepare_tail
can be called on the returned statement to compile the remaining part of the SQL-statement.NOTE: this really uses the C-function
sqlite3_prepare_v2
, i.e. avoids the older, deprecatedsqlite3_prepare
-function.- raises SqliteError
if an invalid database handle is passed.
- raises SqliteError
if the statement could not be prepared.
val prepare_or_reset : db -> stmt option Stdlib.ref -> string -> stmt
prepare_or_reset db opt_stmt_ref sql
ifopt_stmt_ref
containsSome stmt
, thenstmt
will be reset and returned. Otherwise fresh statementstmt
will be prepared, stored asSome stmt
inopt_stmt_ref
and then returned. This is useful for executing multiple identical commands in a loop, because we can more efficiently reuse the statement from previous iterations.- raises SqliteError
if the statement could not be prepared or reset.
val prepare_tail : stmt -> stmt option
prepare_tail stmt
compile the remaining part of the SQL-statementstmt
to bytecode.- returns
None
if there was no remaining part, orSome remaining_part
otherwise.NOTE: this really uses the C-function
sqlite3_prepare_v2
, i.e. avoids the older, deprecatedsqlite3_prepare
-function.
- raises SqliteError
if the statement could not be prepared.
val recompile : stmt -> unit
recompile stmt
recompiles the SQL-statement associated withstmt
to bytecode. The statement may be only partially compiled. In this caseprepare_tail
can be called on the statement to compile the remaining part of the SQL-statement. Call this function if the statement expires due to some schema change.- raises SqliteError
if the statement could not be recompiled.
val finalize : stmt -> Rc.t
finalize stmt
finalizes the statementstmt
. After finalization, the only valid usage of the statement is to use it inprepare_tail
, or torecompile
it.- returns
the return code of this operation.
- raises SqliteError
if the statement could not be finalized.
Data query
val data_count : stmt -> int
data_count stmt
- returns
the number of columns in the result of the last step of statement
stmt
.
- raises SqliteError
if the statement is invalid.
val column_count : stmt -> int
column_count stmt
- returns
the number of columns that would be returned by executing statement
stmt
.
- raises SqliteError
if the statement is invalid.
val column : stmt -> int -> Data.t
column stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_bool : stmt -> int -> bool
column_bool stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
as abool
.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_text : stmt -> int -> string
column_text stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
as text (astring
).
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_int : stmt -> int -> int
column_int stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
as anint
.
- raises RangeError
if
n
is out of range.
- raises Failure
if the integer conversion over- or underflows.
- raises SqliteError
if the statement is invalid.
val column_nativeint : stmt -> int -> nativeint
column_nativeint stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
as anativeint
.
- raises RangeError
if
n
is out of range.
- raises Failure
if the integer conversion over- or underflows.
- raises SqliteError
if the statement is invalid.
val column_int32 : stmt -> int -> int32
column_int32 stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
as anint32
. Note that this function exactly corresponds to the C-library functionsqlite3_column_int
and does not check for over- or underflow during integer conversions.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_int64 : stmt -> int -> int64
column_int64 stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
as anint64
. Note that this function exactly corresponds to the C-library functionsqlite3_column_int64
and does not check for over- or underflow during integer conversions.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_double : stmt -> int -> float
column_double stmt n
- returns
the data in column
n
of the result of the last step of statementstmt
as a doublefloat
.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_blob : stmt -> int -> string
column_blob stmt n
- returns
the blob string in column
n
of the result of the last step of statementstmt
as astring
.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_name : stmt -> int -> header
column_name stmt n
- returns
the header of column
n
in the result set of statementstmt
.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
val column_decltype : stmt -> int -> string option
column_decltype stmt n
- returns
the declared type of the specified column in the result set of statement
stmt
asSome str
if available, or asNone
otherwise.
- raises RangeError
if
n
is out of range.
- raises SqliteError
if the statement is invalid.
Binding data to statements
val bind : stmt -> int -> Data.t -> Rc.t
bind stmt pos data
binds the valuedata
to the free variable at positionpos
of statementstmt
. NOTE: the first variable has index1
!- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_text : stmt -> int -> string -> Rc.t
bind_text stmt pos str
binds the stringstr
to the parameter at positionpos
of the statementstmt
as text.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_bool : stmt -> int -> bool -> Rc.t
bind_bool stmt pos b
binds the booleanb
to the parameter at positionpos
of the statementstmt
without having to manually convert it to anint64
for use withData.INT
.true
is turned into 1,false
into 0.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_int : stmt -> int -> int -> Rc.t
bind_int stmt pos n
binds the integern
to the parameter at positionpos
of the statementstmt
without having to manually convert it to anint64
for use withData.INT
.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_nativeint : stmt -> int -> nativeint -> Rc.t
bind_nativeint stmt pos n
binds the integern
to the parameter at positionpos
of the statementstmt
without having to manually convert it to anint64
for use withData.INT
.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_int32 : stmt -> int -> int32 -> Rc.t
bind_int32 stmt pos n
binds the 32-bit integern
to the parameter at positionpos
of the statementstmt
without having to manually convert it to anint64
for use withData.INT
.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_int64 : stmt -> int -> int64 -> Rc.t
bind_int64 stmt pos n
binds the 64-bit integern
to the parameter at positionpos
of the statementstmt
.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_double : stmt -> int -> float -> Rc.t
bind_double stmt pos n
binds the floatn
to the parameter at positionpos
of the statementstmt
.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_blob : stmt -> int -> string -> Rc.t
bind_blob stmt pos str
binds the stringstr
to the parameter at positionpos
of the statementstmt
as a blob.- returns
the return code of this operation.
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_values : stmt -> Data.t list -> Rc.t
bind_values stmt lst
binds the Nth element oflst
to the Nth parameter of the statement.- returns
the return code of the first binding that fails, or
Rc.OK
.
- raises RangeError
if there aren't at least as many parameters as there are elements of the list.
- raises SqliteError
if the statement is invalid.
val bind_name : stmt -> string -> Data.t -> Rc.t
bind_name stmt name data
binds the valuedata
to the named parametername
of statementstmt
.- returns
the return code of this operation.
- raises Not_found
if
name
does not exist.
- raises SqliteError
if the statement is invalid.
val bind_names : stmt -> (string * Data.t) list -> Rc.t
bind_names stmt lst
binds the(name, data)
pairs inlst
to the parameters of statementstmt
.- returns
the return code of the first binding that fails, or
Rc.OK
.
- raises Not_found
if a
name
does not exist.
- raises SqliteError
if the statement is invalid.
val bind_parameter_count : stmt -> int
bind_parameter_count stmt
- returns
the number of free variables in statement
stmt
.
- raises SqliteError
if the statement is invalid.
val bind_parameter_name : stmt -> int -> string option
bind_parameter_name stmt pos
- returns
Some parameter_name
of the free variable at positionpos
of statementstmt
, orNone
if it is ordinary ("?").
- raises RangeError
if
pos
is out of range.
- raises SqliteError
if the statement is invalid.
val bind_parameter_index : stmt -> string -> int
bind_parameter_index stmt name
- returns
the position of the free variable with name
name
in statementstmt
.
- raises Not_found
if
name
was not found.
- raises SqliteError
if the statement is invalid.
Executing statements
val step : stmt -> Rc.t
step stmt
performs one step of the query associated with SQL-statementstmt
.- returns
the return code of this operation.
- raises SqliteError
if the step could not be executed.
val reset : stmt -> Rc.t
reset stmt
resets the statementstmt
, e.g. to restart the query, perhaps with different bindings.- returns
the return code of this operation.
- raises SqliteError
if the statement could not be reset.
val iter : stmt -> f:(Data.t array -> unit) -> Rc.t
iter stmt ~f
will callf
once per row returned by stepping throughstmt
. The statement is automatically reset afterwards.- returns
Rc.DONE
on success or another return code on error.
- raises SqliteError
if the statement is invalid.
val fold : stmt -> f:('a -> Data.t array -> 'a) -> init:'a -> Rc.t * 'a
fold stmt ~f ~init
folds over the rows returned bystmt
with functionf
and initial valueinit
. The statement is automatically reset afterwards.- returns
(rc, acc)
whereacc
is the last accumulated value returned byf
after being called on a row.rc
isRc.DONE
if all rows were processed and if the statement could be reset, otherwise an error code.
- raises SqliteError
if the statement is invalid.
Stepwise query convenience functions
val row_blobs : stmt -> string array
row_blobs stmt
- returns
the blobs returned by the last query step performed with statement
stmt
(array of blobs).
- raises SqliteError
if the statement is invalid.
val row_data : stmt -> Data.t array
row_data stmt
- returns
all data values in the row returned by the last query step performed with statement
stmt
.
- raises SqliteError
if the statement is invalid.
val row_names : stmt -> headers
row_names stmt
- returns
all column headers of the row returned by the last query step performed with statement
stmt
.
- raises SqliteError
if the statement is invalid.
val row_decltypes : stmt -> string option array
row_decltypes stmt
- returns
all column type declarations of the row returned by the last query step performed with statement
stmt
.
- raises SqliteError
if the statement is invalid.
User-defined functions
val create_funN : db -> string -> (Data.t array -> Data.t) -> unit
create_funN db name f
registers functionf
under namename
with database handledb
. The function has arityN
.- raises SqliteError
if an invalid database handle is passed.
val create_fun0 : db -> string -> (unit -> Data.t) -> unit
create_funN db name f
registers functionf
under namename
with database handledb
. The function has arity0
.- raises SqliteError
if an invalid database handle is passed.
val create_fun1 : db -> string -> (Data.t -> Data.t) -> unit
create_fun1 db name f
registers functionf
under namename
with database handledb
. The function has arity1
.- raises SqliteError
if an invalid database handle is passed.
val create_fun2 : db -> string -> (Data.t -> Data.t -> Data.t) -> unit
create_fun2 db name f
registers functionf
under namename
with database handledb
. The function has arity2
.- raises SqliteError
if an invalid database handle is passed.
val create_fun3 : db -> string -> (Data.t -> Data.t -> Data.t -> Data.t) -> unit
create_fun3 db name f
registers functionf
under namename
with database handledb
. The function has arity3
.- raises SqliteError
if an invalid database handle is passed.
val delete_function : db -> string -> unit
delete_function db name
deletes function with namename
from database handledb
.- raises SqliteError
if an invalid database handle is passed.
module Aggregate : sig ... end
module Backup : sig ... end
Utility functions
val busy_timeout : db -> int -> unit
busy_timeout db ms
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 leastms
milliseconds of sleeping have accumulated.- raises SqliteError
if an invalid database handle is passed.