I am happy to announce the initial release of fun-sql, a simple functional-style query library for SQLite and PostgreSQL.
To use it with SQLite: https://ocaml.org/p/fun-sqlite
To use it with PostgreSQL: fun-postgresql 0.2.3 (latest) · OCaml Package
Fun-sql is not an ORM, it’s a query execution and data mapping library (sometimes called a micro-ORM). It does three things:
- Create the prepared statement and encode the parameters
- Execute the query
- Decode the resultset into OCaml types using a set of combinators.
Here’s an example:
open Fun_postgresql
module Note(Db : sig val db : Postgresql.connection end) = struct
open Db
type t = { id : int; txt : string }
let ret = ret (fun row -> { id = int 0 row; txt = text 1 row })
(* Prepared statement: *)
let edit = query db "update note set txt = $1 where id = $2"
(* Use by simply calling it: *)
let edit id txt = edit ~args:Arg.[text txt; int id] unit
(* val edit : int -> string -> unit *)
(* Prepared statement: *)
let by_id = query db "select id, txt from note where id = $1"
let by_id id = only (by_id ~args:Arg.[int id] ret)
(* val by_id : int -> t *)
end
The design enforces the use of prepared statements–indeed, with PostgreSQL, a prepared statement corresponding to a query can be created only once, so you have to ensure that you use a pattern like the above.
MySQL support is also desired and I will get to it at some point unless someone beats me to it!