repodb — the data layer

Model and query data in OCaml with repodb using typed schemas, validated changesets and SQLite, PostgreSQL or MariaDB.

API reference

repodb is araara's database layer. Tables are described as OCaml types. Queries built from those types are checked by the compiler, and values are passed to the database as bound parameters. The same code runs against SQLite, PostgreSQL and MySQL/MariaDB. SQL strings are generated by repodb from the typed definitions. This page describes each part of the layer in turn.

The shape of the data layer

repodb keeps four jobs separate. A schema describes a table's columns as typed fields. A changeset checks and tracks changes before they reach the database. The query DSL is a set of OCaml functions for building statements as values. A Repo runs those statements against a chosen database. The section below describes how to create a Repo.

A write follows three steps: the input is turned into a changeset, the changeset is validated, and then a query runs. Input is checked before the query runs. A write proceeds when the changeset is valid. Reads use the query DSL directly.

A database is selected by passing a driver module to Repodb.Repo.Make. This is a functor application, and it returns a Repo bound to that driver. The examples below use Repodb_sqlite. A production application can use Repodb_postgresql or Repodb_mariadb instead. Field, changeset and query code stays the same across databases. The generated SQL differs, and repodb generates it from the typed definitions. For queries the DSL does not express, repodb provides functions that run raw SQL. These are described near the end of this page.

Drivers and connecting

repodb provides three drivers: Repodb_sqlite, Repodb_postgresql and Repodb_mariadb. One is selected by applying Repodb.Repo.Make to it. The drivers share the same Repo interface, and schema, changeset and query code is the same for each. Connection details and some rendered SQL differ between drivers. Each driver exposes connect : string -> (conn, error) result and error_message, and connection handling has the same form for all three.

SQLite

examples/repodb_connect/main.ml
(* SQLite is embedded: the connection string is a file path, or
   ":memory:" for a database held in memory. It uses no server or
   network connection. *)
let connect_sqlite () =
  match Repodb_sqlite.connect ":memory:" with
  | Ok conn ->
      print_endline "sqlite: connected to :memory:";
      Repodb_sqlite.close conn
  | Error e -> Printf.printf "sqlite: %s\n" (Repodb_sqlite.error_message e)

SQLite runs in-process against a file. The connection string is a path, or ":memory:" for an in-memory database, as this site's tests use. The connection does not use a network, and TLS does not apply. SQLite is used for development, tests, single-node deployments and desktop applications, where the database is stored in one file. SQLite allows one writer at a time, and it does not provide a separate server process.

PostgreSQL and TLS

examples/repodb_connect/main.ml
(* PostgreSQL takes a libpq connection string, passed through as given,
   so libpq parameters apply, including the TLS ones. sslmode=require encrypts
   the connection; sslmode=verify-full plus sslrootcert also authenticates
   the server against a CA. connect_timeout bounds the attempt. *)
let connect_postgres () =
  let conninfo =
    "host=db.example.invalid port=5432 dbname=app user=app password=secret \
     sslmode=verify-full sslrootcert=/etc/ssl/certs/ca.pem connect_timeout=2"
  in
  match Repodb_postgresql.connect conninfo with
  | Ok conn ->
      print_endline "postgres: connected over TLS";
      Repodb_postgresql.close conn
  | Error e ->
      Printf.printf "postgres: no server in this demo (%s)\n"
        (Repodb_postgresql.error_message e)

The PostgreSQL driver takes a libpq connection string and passes it through unchanged. Libpq parameters are available in the string, including parameters for transport security. sslmode=require encrypts the connection. sslmode=verify-full, used with sslrootcert (and sslcert / sslkey for client certificates), also authenticates the server against a CA. Server authentication is appropriate when the connection crosses an untrusted network. PostgreSQL supports concurrent writers and read replicas.

$ dune exec examples/repodb_connect/main.exe

MariaDB / MySQL

examples/repodb_connect/main.ml
(* MariaDB/MySQL takes a key=value string parsed by the driver: host,
   port, user, password, db, socket, charset. A unix socket avoids TCP
   altogether; the driver does not forward SSL options, so for TLS over
   TCP terminate it at a proxy in front of the database. *)
let connect_mariadb () =
  let conninfo =
    "host=127.0.0.1 port=3307 user=app password=secret db=app \
     charset=utf8mb4"
  in
  match Repodb_mariadb.connect conninfo with
  | Ok conn ->
      print_endline "mariadb: connected";
      Repodb_mariadb.close conn
  | Error e ->
      Printf.printf "mariadb: no server in this demo (%s)\n"
        (Repodb_mariadb.error_message e)

The MariaDB driver parses a key=value string with the keys host, port, user, password, db, socket and charset. It connects over TCP or, with socket=, over a local unix socket. This driver does not forward TLS options. For an encrypted connection over an untrusted network, a TLS-terminating proxy can be placed in front of the database. When the application and the database run on the same host, the unix socket can be used instead.

Choosing a driver

SQLite is often used in development and tests, with PostgreSQL used in production. Changing between them changes the driver and the connection string, and the models are used unchanged. The connection (or the pool) is opened once in the application's supervision tree and passed to contexts. Controllers do not open connections.

Schemas and typed fields

examples/repodb_quickstart/main.ml
(* The record rows map to, and typed fields tying accessors to columns. *)
type user = { id : int; name : string; email : string; age : int }

let users_table = Repodb.Schema.table "users"

let field name ty get set =
  Field.make ~table_name:"users" ~name ~ty ~get ~set ()

let name_field =
  field "name" Types.string (fun u -> u.name) (fun v u -> { u with name = v })

let email_field =
  field "email" Types.string
    (fun u -> u.email)
    (fun v u -> { u with email = v })

let age_field =
  field "age" Types.int (fun u -> u.age) (fun v u -> { u with age = v })

A Field.make value holds the information for one column: its table, name, repodb type, and the getter and setter for the record. Changesets, query expressions and inserts use these field values. The field types let the compiler check, for example, that age is compared with an int and that email is cast from a string. In an araara application the fields are defined in the model file, with one model per table.

Migrations

examples/repodb_quickstart/main.ml
(* A migration describes the table with portable typed columns. *)
let create_users =
  let open Repodb.Migration in
  migration ~version:1L ~name:"create_users" ~down:[ drop_table "users" ]
    ~up:
      [
        create_table "users"
          [
            typed_column "id" Types.int ~primary_key:true;
            typed_column "name" Types.string ~nullable:false;
            typed_column "email" Types.string ~nullable:false ~unique:true;
            typed_column "age" Types.int ~nullable:false;
          ];
      ]

A migration carries a monotonic version, a name, and up/down operations built from typed column definitions. The definitions cover primary keys, nullability, uniqueness, defaults and foreign keys. Repo.Ddl renders dialect-specific SQL from these definitions, including CREATE TABLE statements. The down operations make a migration reversible, and the migration runner uses the version to record which migrations have been applied.

DDL and queries are built through migrations and the query DSL. The driver renders the SQL for its database, and values are passed as bound parameters. Repodb also provides functions that run raw SQL for cases the DSL does not cover. The raw SQL section below describes how parameters are bound in those calls.

Validating input with changesets

A changeset takes untrusted input, such as form parameters or a decoded JSON body. It casts the fields named in the cast call through their types, and validations are then applied to the cast values. If a changeset is invalid, it carries structured errors that a controller can render next to the corresponding fields. A write proceeds when the changeset is valid. Validation runs when the input is received, before the data is used in a query.

Cast

examples/repodb_changesets/main.ml
(* [create] seeds a changeset with a base record; [cast] copies only the
   whitelisted fields out of untrusted params (extra keys are dropped). *)
let cast_params params =
  Changeset.create empty
  |> Changeset.cast params
       ~fields:
         [
           name_field;
           email_field;
           age_field;
           role_field;
           password_field;
           password_confirmation_field;
         ]

create starts from a record. cast reads the named parameters through their fields, and parameters that are not named are ignored. Fields that are not named in the cast call are not assigned from the input. get_change and changes return the values that were set.

The validators

examples/repodb_changesets/main.ml
(* A pipeline of validators. Each only fires when its field was cast, so
   missing optional fields stay silent while required ones are enforced. *)
let validate cs =
  cs
  |> Changeset.validate_required [ name_field; email_field; age_field ]
  |> Changeset.validate_format email_field ~pattern:"^[^@]+@[^@]+$"
  |> Changeset.validate_length name_field ~min:2 ~max:40
  |> Changeset.validate_number age_field ~greater_than_or_equal:18
       ~less_than_or_equal:120
  |> Changeset.validate_inclusion role_field ~values:[ "admin"; "member" ]
  |> Changeset.validate_confirmation password_field
       ~confirmation_field:password_confirmation_field

repodb provides these validators. Each appends to the changeset's error list, and validators compose with |>: validate_required, validate_format, validate_length (min / max / is), validate_number (greater_than, less_than, and the _or_equal bounds), validate_inclusion, validate_exclusion, validate_acceptance, validate_confirmation (a field against its confirmation), and validate_change for an arbitrary predicate. unique_constraint, foreign_key_constraint and check_constraint declare database constraints. When an insert fails because of one of these constraints, the changeset records a field error for it.

Errors

examples/repodb_changesets/main.ml
(* A bad submission accumulates every failure; nothing is persisted.
   [is_valid] gates the write, [error_messages] reports field + reason. *)
let bad =
  cast_params
    [
      ("name", "A");
      ("email", "not-an-email");
      ("age", "9");
      ("role", "superuser");
      ("password", "s3cret");
      ("password_confirmation", "typo");
    ]
  |> validate
in
if Changeset.is_valid bad then die "expected the bad changeset to be invalid"
else begin
  Printf.printf "rejected (%d errors):\n" (List.length (Changeset.errors bad));
  List.iter (fun m -> Printf.printf "  - %s\n" m) (Changeset.error_messages bad)
end;

is_valid reports whether the changeset can proceed to a write. errors and error_messages return the structured errors and their messages. A controller can return a 422 response with the messages beside the form fields. The same changeset is used for the HTML and JSON responses.

$ dune exec examples/repodb_changesets/main.exe

Inserts

examples/repodb_quickstart/main.ml
(* Insert: the compiler checks each column's type against its value. *)
let insert name email age =
  Query.insert_into users_table
  |> Repodb.Query_values.values3
       (name_field, email_field, age_field)
       (Expr.string name, Expr.string email, Expr.int age)
in
List.iter
  (fun (name, email, age) ->
    match Repo.insert_query conn (insert name email age) with
    | Ok () -> Printf.printf "inserted: %s, age %d\n" name age
    | Error e -> die ("insert: " ^ Repodb.Error.show_db_error e))
  [
    (change name_field, change email_field, 34);
    ("Bob", "bob@example.com", 17);
    ("Carol", "carol@example.com", 41);
  ];

Query_values.valuesN pairs N fields with N expressions. The compiler checks each column's type against its value, for example Expr.string for a string column and Expr.int for an int column. A mismatch is reported as a build error. insert_query runs the insert. insert_returning_query also returns generated columns, such as the new id.

The query DSL

Queries are values, so fragments compose like any other values and nothing executes until you hand the query to the repo. Expressions (module Expr) reference the typed fields, so a comparison is checked the same way an insert is.

Filtering

examples/repodb_queries/main.ml
(* [where] starts the predicate; [and_where] conjoins, [or_where]
   disjoins. Operators live in Expr and are used under a local open. *)
let adults_in_paris =
  Query.from users_table
  |> Query.where Expr.(column city_field = string "Paris")
  |> Query.and_where Expr.(column age_field >= int 18)
in
run "adults in Paris" (Repo.all_query conn adults_in_paris ~decode:decode_user);

from opens a query; where adds a predicate; and_where / or_where combine them. Expr provides the comparison and logical operators over column / int / string literals.

Ordering, limit and offset

examples/repodb_queries/main.ml
(* [order_by] (or the [asc]/[desc] shorthands) plus [limit]/[offset]
   give deterministic paging - here the second page of one, by age. *)
let oldest_page2 =
  Query.from users_table
  |> Query.desc (Expr.column age_field)
  |> Query.limit 1 |> Query.offset 1
in
run "by age desc, page 2 (limit 1 offset 1)"
  (Repo.all_query conn oldest_page2 ~decode:decode_user);

order_by with asc / desc sorts the results. limit and offset select a range of rows. distinct removes duplicate rows. The join functions (left_join, inner_join, …) take an ~on expression for queries that use more than one table.

Grouping and aggregates

examples/repodb_queries/main.ml
(* [group_by] with an aggregate from Expr ([count] here, typed int64).
   [distinct] dedupes a projection. Decode the aggregate columns by hand. *)
let by_city =
  Query.from users_table
  |> Query.select Expr.[ column city_field; count (column age_field) ]
  |> Query.group_by Expr.[ column city_field ]
  |> Query.desc (Expr.count (Expr.column age_field))
in
(match
   Repo.all_query conn by_city ~decode:(fun row ->
       (Repodb.Driver.row_text row 0, Repodb.Driver.row_int64 row 1))
 with
| Ok rows ->
    Printf.printf "users per city:\n";
    List.iter
      (fun (city, n) -> Printf.printf "  %s: %Ld\n" city n)
      rows
| Error e -> die ("aggregate: " ^ Repodb.Error.show_db_error e));

let distinct_cities =
  Query.from users_table
  |> Query.select Expr.[ column city_field ]
  |> Query.distinct
  |> Query.asc (Expr.column city_field)
in
(match
   Repo.all_query conn distinct_cities ~decode:(fun row ->
       Repodb.Driver.row_text row 0)
 with
| Ok cities -> Printf.printf "distinct cities: %s\n" (String.concat ", " cities)
| Error e -> die ("distinct: " ^ Repodb.Error.show_db_error e));

group_by plus the aggregate expressions (count, sum, avg, min, max) and having build summary queries. count is typed int64, so its column decodes with Driver.row_int64.

Updates and deletes

examples/repodb_queries/main.ml
(* [update] with [set] (typed column := expr) and a [where]; [delete_from]
   with a predicate. Both return [unit result] via the Repo. *)
let promote_bob =
  Query.update users_table
  |> Query.set age_field (Expr.int 18)
  |> Query.where Expr.(column name_field = string "Bob")
in
(match Repo.update_query conn promote_bob with
| Ok () -> print_endline "updated: Bob's age set to 18"
| Error e -> die ("update: " ^ Repodb.Error.show_db_error e));

let drop_minors =
  Query.delete_from users_table
  |> Query.where Expr.(column age_field < int 18)
in
(match Repo.delete_query conn drop_minors with
| Ok () -> print_endline "deleted: rows with age < 18"
| Error e -> die ("delete: " ^ Repodb.Error.show_db_error e));

update / delete_from with set and where build mutations the same composable way; update_query and Repo.update / Repo.delete run them. on_conflict_do_nothing and on_conflict_do_update express upserts.

$ dune exec examples/repodb_queries/main.exe

Reading rows

examples/repodb_quickstart/main.ml
(* Decode one row of [SELECT *] (column order: id, name, email, age). *)
let decode_user row =
  let open Repodb.Driver in
  {
    id = row_int row 0;
    name = row_text row 1;
    email = row_text row 2;
    age = row_int row 3;
  }

A decode function converts a driver row into a record by column position. It uses Driver.row_int / row_text / row_int64 / row_float and their nullable variants. all_query runs a query and decodes each row. one_query and one_query_opt expect a single row. Repo.get reads a row by primary key, and Repo.all reads rows from a table. Neither function requires a query built with the DSL. Large result sets can be processed with the streaming functions in repodb's Stream module.

$ dune exec examples/repodb_quickstart/main.exe

Transactions

Repo.transaction conn f runs f inside a database transaction. It commits when f returns Ok, and it rolls back when f returns Error or raises an exception. The writes made by f are committed together, or rolled back together.

Commit

examples/repodb_transactions/main.ml
(* A transaction with two writes: both land atomically on COMMIT. *)
let committed =
  Repo.transaction conn (fun conn ->
      match insert conn "Alice" 100 with
      | Error e -> Error e
      | Ok () -> insert conn "Bob" 250)
in
(match committed with
| Ok () -> Printf.printf "commit: ok, rows=%d (expect 2)\n" (count conn)
| Error e -> die ("commit: " ^ Repodb.Error.show_db_error e));

Rollback

examples/repodb_transactions/main.ml
(* This transaction writes a row, then returns [Error]; repodb rolls the
   whole unit back, so the write is NOT visible afterwards. *)
let before = count conn in
let rolled_back =
  Repo.transaction conn (fun conn ->
      match insert conn "Carol" 999 with
      | Error e -> Error e
      | Ok () -> Error (Repodb.Error.Query_failed "deliberate abort"))
in
(match rolled_back with
| Ok () -> die "rollback: transaction unexpectedly committed"
| Error e ->
    Printf.printf "rollback: aborted (%s)\n" (Repodb.Error.show_db_error e);
    let after = count conn in
    Printf.printf "rollback: rows before=%d after=%d (expect equal)\n" before
      after;
    if before <> after then die "rollback: row leaked past abort");

When a transaction is aborted, its writes are rolled back. The example compares row counts before and after the aborted transaction. In araara, a context function is a public function in the business-logic layer that performs a write. Each such function uses one transaction: it opens the transaction, performs its writes, and commits. Work that depends on the data being committed, such as publishing a pubsub event or enqueuing a background job, runs after the function returns. Such work is described as a post-commit effect.

$ dune exec examples/repodb_transactions/main.exe

Multi: composing operations

Multi composes several writes into a sequence of named steps. The steps run in a single transaction, and each step's result can be read by name.

Building the pipeline

examples/repodb_multi/main.ml
(* Compose three named steps; nothing runs until [execute]. The first
   step keeps its inserted row (RETURNING) so we can read it back. *)
let pipeline =
  Multi.empty
  |> Multi.insert_returning "alice" ~table:accounts_table
       ~columns:[ "owner"; "balance" ]
       ~values:Driver.Value.[ text "Alice"; int 100 ]
  |> Multi.insert "bob" ~table:accounts_table
       ~columns:[ "owner"; "balance" ]
       ~values:Driver.Value.[ text "Bob"; int 250 ]
  |> Multi.update "raise_alice" ~table:accounts_table ~columns:[ "balance" ]
       ~values:Driver.Value.[ int 175 ]
       ~where_column:"owner" ~where_value:(Driver.Value.text "Alice")
in

Repodb.Multi provides the builder functions empty, insert, insert_returning, update and delete. It also provides run / run_unit / run_row for a step defined by a function. Builders are chained with |>, and each step is given a name so that its result can be read later.

Executing it

examples/repodb_multi/main.ml
(* Run the whole pipeline atomically. On failure [multi_error] names the
   offending step and carries the results completed before it. *)
let results =
  match Multi_run.execute conn pipeline with
  | Ok results ->
      Printf.printf "exec: committed %d steps\n"
        (List.length (Multi.names pipeline));
      results
  | Error { failed_operation; error; _ } ->
      die
        (Printf.sprintf "exec: step %S failed: %s" failed_operation
           (Repodb.Error.show_db_error error))
in

The runner is provided by the functor Repodb.Multi.Make (Repodb_sqlite). execute conn pipeline runs the steps in one transaction. It returns the collected results, or the step that failed. The builder functions are top-level functions in Repodb.Multi, and execute is provided by the functor.

Reading results back

examples/repodb_multi/main.ml
(* Read named outputs back from the map: a decoded RETURNING row, and a
   unit step that confirms it ran. The update is visible too. *)
let alice = Multi.get_row_exn results "alice" ~decode:decode_account in
Multi.get_unit_exn results "bob";
Printf.printf "results: alice #%d inserted as %s with balance %d\n" alice.id
  alice.owner alice.balance;
(match Repo.get conn ~table:accounts_table ~id:alice.id ~decode:decode_account
 with
| Ok a -> Printf.printf "results: alice balance now %d (expect 175)\n" a.balance
| Error e -> die ("reload: " ^ Repodb.Error.show_db_error e));

get_row / get_rows / get_unit (and their _exn and _raw variants) return the result of a named step. A RETURNING row is decoded with a decoder supplied by the caller.

$ dune exec examples/repodb_multi/main.exe

Associations and preloading

Associations describe how tables are related. Preloading loads the related rows for a set of owners in one batched query. Owners are loaded together, so related rows are not fetched with a separate query for each owner.

Declaring associations

examples/repodb_assoc/main.ml
(* An author has_many books; the foreign key lives on the books table.
   The inverse: a book belongs_to one author via that same column. *)
let books_assoc =
  Assoc.has_many "books" ~related_table:"books" ~foreign_key:"author_id" ()

let _author_assoc =
  Assoc.belongs_to "author" ~related_table:"authors" ~foreign_key:"author_id" ()

belongs_to, has_one, has_many and many_to_many name the relationship, the related table, and the foreign key (plus the join table and keys for many-to-many).

Preloading in one query

examples/repodb_assoc/main.ml
(* Load the owners, then preload all their books in a single batched
   query (SELECT * FROM books WHERE author_id IN (...)). *)
let authors =
  match Repo.all_query conn (Query.from authors_table) ~decode:decode_author with
  | Ok authors -> authors
  | Error e -> die ("load authors: " ^ Repodb.Error.show_db_error e)
in
let authors =
  match
    Repo.preload_has_many conn authors ~assoc:books_assoc
      ~get_owner_id:(fun a -> a.id)
      ~decode_related:decode_book
      ~get_fk:(fun b -> b.author_id)
      ~set_assoc:(fun books a -> { a with books = Assoc.Loaded books })
  with
  | Ok authors -> authors
  | Error e -> die ("preload books: " ^ Repodb.Error.show_db_error e)
in

Repo.preload_has_many (and preload_has_one, preload_belongs_to, preload_many_to_many) takes the owners, the association, and functions to read the owner id, decode a related row and attach the result. It issues a single SELECT … WHERE fk IN (…) for all owners at once.

Using the result

examples/repodb_assoc/main.ml
(* Each owner now carries its preloaded children. *)
List.iter
  (fun a ->
    let books =
      match a.books with Assoc.Loaded bs -> bs | Assoc.NotLoaded -> []
    in
    Printf.printf "%s (%d books)\n" a.name (List.length books);
    List.iter (fun b -> Printf.printf "  - %s\n" b.title) books)
  authors;

Each owner is returned with its related rows attached. A list of authors with their books can be rendered after one preload, by folding over the returned values. The rendering loop does not run queries. preload_chunked loads owner sets that are too large for a single IN clause in smaller groups.

$ dune exec examples/repodb_assoc/main.exe

The connection pool

A pool gives connections to fibers from a set of open connections. Requests reuse pooled connections. The pool is lock-free and does not depend on a particular scheduler, and it can be used with Eio's structured concurrency.

Creating a pool

examples/repodb_pool/main.ml
(* A temp-file DB so every pooled connection sees the same data
   (a pool over ":memory:" would give each connection its own DB). *)
let db_path = Filename.temp_file "repodb_pool" ".sqlite3" in
let pool = Pool.create ~max_size:4 ~conninfo:db_path () in

Pool.Make (Repodb_sqlite).create ~max_size ~conninfo () opens the pool against a connection string. (A pooled SQLite demo uses a file path rather than :memory:, so the connections share data.)

Borrowing a connection

examples/repodb_pool/main.ml
(* Borrow a connection to write, and another to read. with_connection
   returns the connection to the pool automatically. *)
let insert name =
  Query.insert_into widgets_table
  |> Repodb.Query_values.values1 widget_name (Expr.string name)
in
let write_result =
  Pool.with_connection pool (fun conn ->
      List.fold_left
        (fun acc name ->
          match acc with
          | Error _ -> acc
          | Ok () -> Repo.insert_query conn (insert name))
        (Ok ()) [ "sprocket"; "flange"; "grommet" ])
in
(match write_result with
| Ok (Ok ()) -> print_endline "inserted: 3 widgets"
| Ok (Error e) -> die ("insert: " ^ Repodb.Error.show_db_error e)
| Error e -> die ("pool: " ^ pool_error e));
let read_result =
  Pool.with_connection pool (fun conn ->
      Repo.all_query conn (Query.from widgets_table) ~decode:decode_widget)
in
(match read_result with
| Ok (Ok widgets) ->
    Printf.printf "read back %d widgets:\n" (List.length widgets);
    List.iter (fun w -> Printf.printf "  #%d %s\n" w.id w.name) widgets
| Ok (Error e) -> die ("query: " ^ Repodb.Error.show_db_error e)
| Error e -> die ("pool: " ^ pool_error e));

with_connection borrows a connection for the duration of the callback and returns it to the pool afterwards, even on error; with_connection_blocking waits with an optional timeout when the pool is exhausted.

Stats and shutdown

examples/repodb_pool/main.ml
(* Both borrowed connections were returned, so they sit idle and
   available; nothing is in use between calls. *)
let s = Pool.stats pool in
Printf.printf "pool stats: total=%d available=%d in_use=%d closed=%b\n"
  s.total s.available s.in_use s.closed;
Printf.printf "  size=%d available=%d in_use=%d\n" (Pool.size pool)
  (Pool.available pool) (Pool.in_use pool);
(* Gracefully close the pool and all its connections. *)
Pool.shutdown pool;
Printf.printf "after shutdown: closed=%b\n" (Pool.is_closed pool);

stats, size, available and in_use report the pool's state for health checks; shutdown drains and closes it. In a full application the pool is opened once in the supervision tree and every context borrows from it.

$ dune exec examples/repodb_pool/main.exe

Raw SQL

Queries are normally built with the query DSL, which is type-checked and renders SQL for each database dialect. Some SQL is not expressed by the DSL, such as a window function, a recursive CTE, a database-specific operator, or a query written in a specific form. For these cases, the Repo provides three functions that run a SQL string: exec_sql for statements that return no rows, query_sql for statements that return rows, and query_one_sql for statements that return at most one row. Parameters are bound by position through Driver.Value. Values from users are passed as parameters, separate from the SQL string.

Running a statement

examples/repodb_raw/main.ml
(* exec_sql runs a statement that returns no rows. Parameters are
   Driver.Value.t, bound positionally; SQLite uses ? placeholders
   (the placeholder syntax is dialect-specific, so raw SQL can depend
   on the backend in use). *)
let exec sql params =
  match Repo.exec_sql conn sql ~params with
  | Ok () -> ()
  | Error e -> die (Repodb.Error.show_db_error e)
in
exec "CREATE TABLE metrics (name TEXT NOT NULL, hits INTEGER NOT NULL)" [||];
exec "INSERT INTO metrics (name, hits) VALUES (?, ?)"
  [| Value.text "home"; Value.int 10 |];
exec "INSERT INTO metrics (name, hits) VALUES (?, ?)"
  [| Value.text "docs"; Value.int 25 |];

exec_sql takes the SQL and a Driver.Value.t array. The values in the array are bound to the statement's placeholders, using constructors such as Value.text and Value.int. The placeholder syntax belongs to the database in use (? for SQLite and MariaDB, $1 for PostgreSQL). A raw query is written for one dialect. A query built with the typed DSL is rendered by the driver for the database in use.

Reading rows back

examples/repodb_raw/main.ml
(* query_sql returns raw rows; decode them by position with the
   Driver.row_* accessors, as a query-DSL decoder does. *)
let sql = "SELECT name, hits FROM metrics WHERE hits > ? ORDER BY hits DESC" in
(match Repo.query_sql conn sql ~params:[| Value.int 5 |] with
| Ok rows ->
    Printf.printf "%d busy page(s):\n" (List.length rows);
    List.iter
      (fun row ->
        Printf.printf "  %s: %d hits\n"
          (Repodb.Driver.row_text row 0)
          (Repodb.Driver.row_int row 1))
      rows
| Error e -> die (Repodb.Error.show_db_error e));

query_sql returns rows from the driver. Rows are decoded by column position with the Driver.row_* accessors, as in a decoder for a DSL query. The decoding code is the same for rows returned from a DSL query and rows returned from a SQL string. Raw SQL is kept in the model with the typed queries for the same table, and values are passed as parameters.

$ dune exec examples/repodb_raw/main.exe

Rendering SQL for different databases

A migration and its queries are rendered as SQL for a specific database by the driver. Application code does not contain dialect-specific SQL for these definitions. Repo.Ddl.generate_up_sql is a function of a migration and does not use a connection. It returns the SQL for a database, so the rendered SQL can be read before it is run.

One migration

examples/repodb_dialects/main.ml
let create_users =
  let open Repodb.Migration in
  migration ~version:1L ~name:"create_users" ~down:[ drop_table "users" ]
    ~up:
      [
        create_table "users"
          [
            typed_column "id" Types.int ~primary_key:true;
            typed_column "email" Types.string ~nullable:false ~unique:true;
            typed_column "active" Types.bool ~nullable:false;
            typed_column "score" Types.float ~nullable:false;
            typed_column "created_at" Types.ptime ~nullable:false;
            typed_column "metadata" Types.json ~nullable:true;
          ];
      ]

The migration is written with typed column definitions. The definitions do not name SQL column types or a database dialect.

Three renderings

examples/repodb_dialects/main.ml
(* generate_up_sql is a pure function of the migration; each driver's Ddl
   renders its own dialect. Note how the portable column types map to
   different SQL: bool is INTEGER on SQLite but BOOLEAN elsewhere, float
   is REAL / DOUBLE PRECISION / DOUBLE, a timestamp is TEXT / TIMESTAMPTZ /
   DATETIME, and json is TEXT / JSONB / JSON. *)
let show label sqls =
  Printf.printf "-- %s --\n" label;
  List.iter (fun s -> Printf.printf "%s\n" s) sqls;
  print_newline ()

let () =
  show "sqlite" (Sqlite.Ddl.generate_up_sql create_users);
  show "postgresql" (Postgres.Ddl.generate_up_sql create_users);
  show "mariadb" (Mariadb.Ddl.generate_up_sql create_users)

Each driver's Ddl module maps the typed column definitions to SQL types for its database. A bool column is INTEGER in SQLite and BOOLEAN in PostgreSQL and MariaDB. A float column is REAL, DOUBLE PRECISION and DOUBLE in the three databases, in that order. A timestamp column is TEXT, TIMESTAMPTZ and DATETIME, and a json column is TEXT, JSONB and JSON. An application declares Types.bool, and the driver selects the column type for its database. generate_up_sql returns the rendered SQL for inspection. The query DSL is rendered by the driver at runtime in the same way. A model used with SQLite in development can be used with PostgreSQL in production without changes to the model.

$ dune exec examples/repodb_dialects/main.exe

Error handling

Expected database failures are returned as values. An operation returns a result, and the error case holds a Repodb.Error.db_error value. The variants include Constraint_violation, Not_found, Query_failed, Transaction_failed, Validation_failed, Timeout and Pool_exhausted. Calling code matches on the variant to handle a missing row, a violated constraint, a failed connection, or another reported failure.

A violated constraint

examples/repodb_errors/main.ml
(* Inserting a duplicate email violates the UNIQUE constraint. The error
   comes back as a typed db_error variant to match on. How precise the
   variant is depends on the driver: PostgreSQL surfaces a detailed
   message that repodb parses into Constraint_violation; SQLite
   reports only "CONSTRAINT", so it arrives as Query_failed. Matching
   both arms keeps the code portable. *)
let insert email =
  Repo.exec_sql conn "INSERT INTO users (email) VALUES (?)"
    ~params:[| Value.text email |]
in
(match insert "ada@example.com" with
| Ok () -> die "expected the duplicate to be rejected"
| Error (Repodb.Error.Constraint_violation { constraint_name; _ }) ->
    Printf.printf "rejected duplicate (Constraint_violation: %s)\n"
      constraint_name
| Error (Repodb.Error.Query_failed msg) ->
    Printf.printf "rejected duplicate (Query_failed: %s)\n" msg
| Error e -> die ("unexpected: " ^ Repodb.Error.show_db_error e));

The variant returned for a failure depends on the information reported by the driver. PostgreSQL reports a detailed message, and repodb reads the constraint name from it and returns Constraint_violation. SQLite reports "CONSTRAINT" for this failure, and the failure is returned as Query_failed. Code that matches both variants handles the failure on either database. A changeset's unique_constraint and foreign_key_constraint declarations use this result to record a field error when an insert fails.

A missing row

examples/repodb_errors/main.ml
(* A read for a row that does not exist is Error Not_found, distinct
   from a row that decodes to None. *)
let users = Repodb.Schema.table "users" in
let decode row = Repodb.Driver.row_text row 1 in
(match Repo.get conn ~table:users ~id:999 ~decode with
| Ok email -> Printf.printf "found %s\n" email
| Error Repodb.Error.Not_found -> print_endline "no user #999 (Not_found)"
| Error e -> die (Repodb.Error.show_db_error e));

Repo.get returns Error Not_found when no row has the given id. This case is separate from a row that decodes to None. A controller can map Not_found to a 404 response by matching on the variant. Repo.get_opt returns Ok None when no row is found, for callers that treat a missing row as a regular result.

$ dune exec examples/repodb_errors/main.exe

Read/write splitting (CQRS)

The Cqrs module routes database traffic between a primary database and read replicas. CQRS stands for Command Query Responsibility Segregation. In this module, writes are sent to the primary database and reads are sent to read replicas. A replica is selected by round-robin, random or least-connections selection, and the health of each replica is tracked. A Cqrs pool is used in place of a Repo. Query code and model code stay the same, and the pool that provides the connection changes.

Describing the topology

examples/repodb_cqrs/main.ml
(* A CQRS pool is described by one config: where the primary lives, where the
   replicas live, and how reads pick a replica. In production these are
   distinct servers kept in sync by the database's own replication; here a
   single temp file stands in for all of them so the demo can run. This
   example concerns the routing between pools. *)
let () =
  let db = Filename.temp_file "repodb_cqrs" ".sqlite3" in
  let cqrs =
    C.create
      {
        primary_conninfo = db;
        primary_max_size = 2;
        replica_conninfos = [ db; db ];
        (* two replicas *)
        replica_max_size_each = 2;
        replica_selection = Repodb.Cqrs.RoundRobin;
        validate = None;
      }
  in

A config value names the primary, the replicas, the pool sizes and the replica-selection strategy. Repodb.Cqrs.Make (Driver) creates a pool bound to that driver, in the same way as Repo.Make.

Routing reads and writes

examples/repodb_cqrs/main.ml
(* with_write borrows from the primary pool. *)
run_write "create" (fun conn ->
    Repo.exec_sql conn
      "CREATE TABLE pages (slug TEXT PRIMARY KEY, hits INTEGER NOT NULL)"
      ~params:[||]);
let bump slug hits conn =
  Repo.exec_sql conn "INSERT INTO pages (slug, hits) VALUES (?, ?)"
    ~params:Repodb.Driver.Value.[| text slug; int hits |]
in
run_write "insert docs" (bump "docs" 25);
run_write "insert home" (bump "home" 10);

(* with_read routes to a healthy replica, round-robin; with no replicas it
   falls back to the primary, so read code is identical either way. *)
let total =
  run_read "sum hits" (fun conn ->
      match Repo.query_one_sql conn "SELECT SUM(hits) FROM pages" ~params:[||] with
      | Ok (Some row) -> Ok (Repodb.Driver.row_int row 0)
      | Ok None -> Ok 0
      | Error e -> Error e)
in
Printf.printf "total hits (read from a replica): %d\n" total;

with_write borrows a connection from the primary pool. with_read borrows a connection from a healthy replica, and it uses the primary pool when no healthy replica is available. Read code has the same form whether replicas are configured or not. Each function returns the connection to its pool when the callback finishes, including when the callback returns an error.

Health and stats

examples/repodb_cqrs/main.ml
(* stats reports the primary and every replica pool, plus how many
   replicas are currently healthy. A health-check endpoint can report
   these values. *)
let s = C.stats cqrs in
Printf.printf "primary in_use=%d  healthy replicas=%d\n" s.primary.in_use
  s.healthy_replica_count;
(* mark_replica_unhealthy pulls a replica out of rotation (e.g. after a
   failed health probe); reads then skip it until it is marked healthy. *)
C.mark_replica_unhealthy cqrs 0;
Printf.printf "after marking replica 0 unhealthy: healthy replicas=%d\n"
  (C.count_healthy_replicas cqrs);

stats reports the state of the primary pool and each replica pool, and the count of healthy replicas. A health-check endpoint can report these values. mark_replica_unhealthy marks a replica as unavailable for reads after a failed probe. Reads use other replicas until the replica is marked healthy again.

$ dune exec examples/repodb_cqrs/main.exe

Deriving bindings with repodb-ppx

The models on this page are handwritten. Each model defines a record, typed fields and a row decoder. The repodb-ppx reference describes a deriver that generates a table definition, fields, a schema and checked row codecs from an annotated record. Derived models are used with the query DSL, changesets and migrations described above.

In a full application, repodb calls are made from models and contexts. Controllers and views do not call the database. The conventions page describes this layering, and the API reference linked above documents the modules and functions.