Skip to content
Hypha Stack

Rowtype

Typed Postgres queries and migrations for OCaml 5.

Source on GitHubLatest: 0.8.1

About

You write the SQL. You declare its parameters and rows once, and that one declaration binds the values going in and decodes the rows coming out. No ORM, no query DSL, no ppx.

Every statement can be checked against your database from a test, without running it, and migrations are in the box.

Data and persistence

Install

From Hypha's opam repository, on OCaml 5.5 or later:

opam repo add hypha https://github.com/hyphatech/opam-repository.git
opam install rowtype rowtype-postgres rowtype-migrate

Then in your dune file:

(libraries rowtype rowtype-postgres eio_main)

In code

  1. Statements: the SQL as written, with typed parameters and rows, and how many rows each answers.

    module S = Rowtype
    module Pg = Rowtype_postgres
    
    type user = { id : int; name : string }
    
    let user =
      S.map (S.t2 S.int S.text)
        ~parse:(fun (id, name) -> { id; name })
        ~print:(fun u -> (u.id, u.name))
    
    let add_user =
      S.find ~params:S.text ~row:S.int
        "insert into users (name) values ($1) returning id"
    
    let find_user =
      S.find_opt ~params:S.int ~row:user "select id, name from users where id = $1"
  2. Run on a connection; every failure is a value.

    let* db =
      Pg.connect ~sw ~net:(Eio.Stdenv.net env)
        ~mono_clock:(Eio.Stdenv.mono_clock env) target
    in
    let* id = Pg.run db add_user "Ada" in
    Pg.run db find_user id

Ontology

Build with Hypha.