package fun-sql

  1. Overview
  2. Docs

Module type Fun_sql.SqlSource

Sourcetype db

The database connection or file, etc.

Sourcetype arg

A value sent to the database in the place of a query parameter.

Sourcetype _ ret

A decoder of a single row of the resultset from running a query.

Sourceval placeholder : Format.formatter -> int -> unit

A generic way to write placeholders for different database drivers' prepared statement parameters.

ℹ️ Placeholders are 0-indexed.

Query runners

Sourceval query : db -> string -> ?args:arg list -> 'r ret -> 'r

The main function through which queries are run is the query function. This function always creates a prepared statement for each partial call to query db sql. This prepared statement can then be called with the actual arguments (if any) and the resultset row decoder:

let add_person =
    query db (sql "insert into people (name, age) values (%a, %a)" placeholder 0 placeholder 1)
  let add_person name age = add_person ~args:Arg.[text name; int age] unit
  • raises Invalid_argument

    if trying to create multiple prepared statements for the same SQL query in PostgreSQL. To avoid this, just create the prepared statement once only and call it whenever needed, as shown above.

Sourceval exec_script : db -> string -> unit

exec_script db sql executes the sql script (possibly made up of multiple statements) in the database db. Note that it ignores any rows returned by any of the statements.

The script must not have a trailing semicolon.

Binding arguments

These encode OCaml data as data to be bound to the query statement.

Sourcemodule Arg : sig ... end

Return types

Sourcetype row
Sourceval unit : unit ret

unit indicates that the query doesn't return any meaningful output.

Sourceval ret : (row -> 'a) -> 'a Seq.t ret

ret decode is a custom return type encoding for a resultset into a sequence of values of the type decoded by decode.

decode constructs a value of the custom type if possible, else raises Failure.

Note that the sequence rows of the resultset is unfolded as it is read from the database. It can only be traversed once, with e.g. List.of_seq or Seq.iter. If traversed multiple times, it will raise Failure.

  • raises Failure

    if an unexpected result code is encountered.

Helpers to get typed values from columns

Sourceval int : int -> row -> int
Sourceval bool : int -> row -> bool
Sourceval int64 : int -> row -> int64
Sourceval float : int -> row -> float
Sourceval text : int -> row -> string

Also handles values of all other types. Use this when SQLite can change the exact type of value it returns at runtime, e.g. for very large numbers it can return text.

Sourceval opt : (int -> row -> 'a) -> int -> row -> 'a option

opt dec col row is the optional value NULL turns to None at column col of the result row.

OCaml

Innovation. Community. Security.