repodb-ppx — derived models

Derive repodb models in OCaml with repodb-ppx: typed fields, table schemas and checked row codecs from one record.

API reference

Handwritten repodb bindings define a model in three parts: the record, the typed fields, and the row decoder. repodb-ppx generates the other definitions from an annotated record. A record is annotated with table and column attributes. From the annotation, the deriver generates fields with getters and functional setters, ordered column lists, and a table schema with keys and constraints. It also generates row encoders and decoders that return errors with the table and column when a conversion fails. The generated code calls the repodb APIs that handwritten bindings call. Derived models can be used with the query DSL, changesets, migrations and the repodb drivers. This page describes one derived model, with a runnable example.

Setup

Install the deriver next to repodb and your driver:

$ opam install repodb repodb-sqlite repodb-ppx

Enable it in the executable or library that holds your models:

examples/repodb_ppx/dune
(executable
 (name main)
 (libraries repodb repodb-sqlite)
 (preprocess (pps repodb-ppx)))

; Executed by `dune runtest`: the example must run to completion.
(rule
 (alias runtest)
 (action
  (run ./main.exe)))

Dune adds the repodb-ppx.runtime support library to the dependencies of the generated code. ppxlib runs during preprocessing. The core repodb package does not depend on ppxlib.

A derived model

Domain types are mapped to columns through custom witnesses supplied by the application. When encoding a value fails, the codec returns an error that includes context for the failure. The value is not converted to NULL:

examples/repodb_ppx/main.ml
(* Domain types map to columns through a small custom codec. A failed
   encode is returned as an error with table and column context. *)
type status = Draft | Published | Archived

let status_type =
  Repodb.Types.custom ~sql_type:"TEXT"
    ~encode:(function
      | Draft -> Ok "draft"
      | Published -> Ok "published"
      | Archived -> Error "archived users are read-only")
    ~decode:(function
      | "draft" -> Ok Draft
      | "published" -> Ok Published
      | value -> Error ("Unknown status: " ^ value))

A record annotation derives the T_repodb module. The module contains the table, the typed Fields, column lists, the schema, and the checked codecs:

examples/repodb_ppx/main.ml
(* One annotation derives the `T_repodb` module: table, typed Fields,
   column lists, schema, and checked row encoders and decoders. *)
type t = {
  id : int; [@repodb.primary_key]
  name : string;
    [@repodb.column "display_name"]
    [@repodb.unique]
  email : string option;
  age : int option;
  active : bool; [@repodb.default_expr Repodb.Schema.Bool true]
  status : status; [@repodb.type status_type]
}
[@@repodb.table "users"] [@@deriving repodb]

module Db = T_repodb

A primary key is marked in the annotation. A field named id is treated as a primary key when it is marked as one. The names inside Fields are the OCaml record labels, including for fields whose database column has a different name. The type named t generates T_repodb, and a model module can expose the generated bindings as User.Db. The deriver can be used in the .mli file as well as the .ml file when other modules use the generated API.

Migrate and write

The generated schema is used to render DDL for the database in use, through the application's repo:

examples/repodb_ppx/main.ml
(* The generated schema renders dialect-aware DDL; here SQLite. *)
let conn =
  match Repodb_sqlite.connect ":memory:" with
  | Ok conn -> conn
  | Error error -> die ("connect: " ^ Repodb_sqlite.error_message error)
in
Printf.printf "columns: %s\n" (String.concat ", " Db.columns);
get "migrate"
  (Repo.exec_sql conn (Repo.Ddl.schema_to_sql Db.schema) ~params:[||]);
print_endline "migrated: users";

Inserts pair the table with the generated column list and the checked insert values:

examples/repodb_ppx/main.ml
(* Inserts pair the table with the generated column list and the
   checked insert values. *)
let ada =
  {
    id = 1;
    name = "Ada";
    email = Some "ada@example.com";
    age = None;
    active = true;
    status = Draft;
  }
in
let grace =
  {
    id = 2;
    name = "Grace";
    email = None;
    age = Some 85;
    active = false;
    status = Published;
  }
in
List.iter
  (fun user ->
    let values = get_codec "encode" (Db.encode_insert user) in
    get "insert"
      (Repo.insert conn ~table:Db.table ~columns:Db.insert_columns ~values);
    Printf.printf "inserted: %s\n" user.name)
  [ ada; grace ];

Read and update

Reads use the query DSL, as with handwritten bindings. The generated decoder looks up columns by name. Results with columns in a different order are decoded, and columns that are not part of the model are ignored. Each column of the model must be present in the result:

examples/repodb_ppx/main.ml
(* Reads go through the same query DSL as handwritten bindings; the
   generated decoder looks columns up by name. *)
let users =
  get "query" (Repo.all_query conn Query.(from Db.table) ~decode:Db.decode_exn)
in
Printf.printf "all users: %d rows\n" (List.length users);
List.iter print_user users;
let actives =
  get "query"
    (Repo.all_query conn
       Query.(from Db.table |> where Expr.(column Db.Fields.active = bool true))
       ~decode:Db.decode_exn)
in
Printf.printf "active users: %d rows\n" (List.length actives);
if List.length users <> 2 || List.length actives <> 1 then
  die "unexpected row counts";

Changesets and functional updates can be used with the generated fields. Cast keys are database column names. A field whose column is renamed is cast with the column name as the key, for example "display_name". The column name for a field is returned by Field.name. Cast takes fields of the same type, and option fields are updated with Field.set:

examples/repodb_ppx/main.ml
(* Changesets and functional updates compose with generated fields.
   Cast keys are database column names (see Field.name), so a renamed
   field casts under its column name, "display_name". Cast takes
   same-type fields; option fields update through Field.set. *)
let params = [ (Field.name Db.Fields.name, "Augusta Ada King") ] in
let changeset =
  Changeset.create ada
  |> Changeset.cast params ~fields:[ Db.Fields.name ]
  |> Changeset.validate_required [ Db.Fields.name ]
  |> Changeset.validate_length Db.Fields.name ~min:2
in
(match Changeset.errors changeset with
| [] ->
    let name =
      Option.value (Changeset.get_change changeset Db.Fields.name) ~default:"?"
    in
    Printf.printf "changeset: valid (name=%s)\n" name
| _ -> die (String.concat "; " (Changeset.error_messages changeset)));
let older =
  ada
  |> Field.set Db.Fields.email (Some "augusta@example.com")
  |> Field.set Db.Fields.age (Some 36)
in
Printf.printf "updated: %s <%s> is now %d\n" (Field.get Db.Fields.name older)
  (Option.value (Field.get Db.Fields.email older) ~default:"?")
  (Option.value (Field.get Db.Fields.age older) ~default:0);

Conversion errors

The codecs that return results report a failed conversion in the error case of the result. The error includes the table and the column:

examples/repodb_ppx/main.ml
(* The result-returning codecs keep conversion failures as values,
   with the table and column attached. *)
(match Db.encode_insert { ada with status = Archived } with
| Ok _ -> die "expected the archived encode to fail"
| Error message -> Printf.printf "checked: %s\n" message);
Repodb_sqlite.close conn
$ dune exec examples/repodb_ppx/main.exe

Attributes and types

The deriver infers a column type for int, int32, int64, float, string, bool, Ptime.t, Ptime.date and Uuidm.t, and for the optional forms of these types. Other types (variants, collections, aliases and domain types) take an explicit [@repodb.type witness]. The witness includes option when the field is nullable. Table and column names, schema prefixes, composite primary keys, unique constraints, raw SQL, semantic defaults, checks and foreign-key references are given as attributes. [@repodb.skip_insert] omits a field from inserts when the database supplies the value. Semantic defaults, such as Schema.Bool true, are rendered by each driver for its database. When a type changes, the change is applied with a migration. A generated schema describes the current form of the table.

In a full application, derived models are defined in the model files where handwritten fields would otherwise be defined, with one model per table. Code that uses the models, in contexts, controllers and views, is unchanged. The API reference linked above documents the deriver and its attributes.