Skip to content

Rowtype

SQL queries and migrations for modern OCaml.

Source on GitHubDocumentation

About

Write your queries in plain SQL, with no ORM, no query DSL and no ppx, and run them typed. Every statement is described by your database from a test, without running it, so a renamed column fails a test instead of a request.

The same statements run on Postgres and SQLite. Migrations come in the box as plain SQL files and one command, a library's own included. A refused write names its constraint and a lost write is told from one never sent, and rows of any size are read in the memory of one, with loads through COPY.

Data and persistence

Install

From open-opam, on OCaml 5.5 or later:

opam repo add open-opam https://github.com/open-opam/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 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

Build with Hypha.

  • Talk to us

    Bring an idea, a product or a system. Questions and feedback are just as welcome.

  • Services

    A new product built to last, or the system your business runs on rebuilt. Hypha's expertise and its foundation, end to end.

  • The Factory

    Make the decisions and let Hypha Autonomous Factory do the rest, turning them into a tested release, ready to ship.