Skip to content
Hypha Stack

Rowtype

Typed Postgres queries and migrations for OCaml 5.

Source on GitHubDocumentationLatest: 0.8.1

About

Write your queries in plain SQL and run them typed. Every query is checked against your database's schema before you deploy, so your app never sends one that no longer matches it.

Runs on postgres-eio, a native driver with TLS, pooling and failover.

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.