From 0e6dac57bf620cea50655e7d85b6c500c78cd6b3 Mon Sep 17 00:00:00 2001 From: Roman Zaiev Date: Sat, 21 Nov 2026 23:17:10 +0000 Subject: [PATCH] Install the documentation for agents with the package An agent writing code with rowtype should read the docs of the release it builds against, but the packages installed only their README, CHANGES and LICENSE. starlight-hypha-agents writes each page as Markdown and llms.txt into agents/ as the docs build, and the rowtype package, which every other one depends on, installs it into its doc directory. An agent reads it when told to, so the README gives the one line for a project's AGENTS.md that sends it there. The docs take starlight-theme-hypha 0.8.0, a look alone, beside it. The docs workflow now builds every pull request, so a page changed without agents/ fails before it lands, and deploys only from main. `make docs` writes agents/, so it has no target of its own. --- .github/workflows/docs.yml | 35 ++- AGENTS.md | 16 +- CHANGES.md | 6 + README.md | 12 + agents/llms.txt | 28 +++ agents/pages/guide/bulk-writes.md | 75 +++++++ agents/pages/guide/checking-statements.md | 65 ++++++ agents/pages/guide/columns.md | 157 +++++++++++++ agents/pages/guide/errors.md | 83 +++++++ agents/pages/guide/library-migrations.md | 58 +++++ agents/pages/guide/migrating-from-a-test.md | 71 ++++++ agents/pages/guide/migrations.md | 99 ++++++++ agents/pages/guide/pools.md | 163 ++++++++++++++ agents/pages/guide/sqlite.md | 237 ++++++++++++++++++++ agents/pages/guide/statements.md | 132 +++++++++++ agents/pages/guide/test-databases.md | 93 ++++++++ agents/pages/guide/transactions.md | 108 +++++++++ agents/pages/index.md | 69 ++++++ agents/pages/quick-start.md | 103 +++++++++ agents/pages/reference.md | 47 ++++ agents/pages/why-not-caqti.md | 12 + docs/astro.config.mjs | 5 + docs/bun.lock | 37 ++- docs/package.json | 3 +- dune | 10 + 25 files changed, 1709 insertions(+), 15 deletions(-) create mode 100644 agents/llms.txt create mode 100644 agents/pages/guide/bulk-writes.md create mode 100644 agents/pages/guide/checking-statements.md create mode 100644 agents/pages/guide/columns.md create mode 100644 agents/pages/guide/errors.md create mode 100644 agents/pages/guide/library-migrations.md create mode 100644 agents/pages/guide/migrating-from-a-test.md create mode 100644 agents/pages/guide/migrations.md create mode 100644 agents/pages/guide/pools.md create mode 100644 agents/pages/guide/sqlite.md create mode 100644 agents/pages/guide/statements.md create mode 100644 agents/pages/guide/test-databases.md create mode 100644 agents/pages/guide/transactions.md create mode 100644 agents/pages/index.md create mode 100644 agents/pages/quick-start.md create mode 100644 agents/pages/reference.md create mode 100644 agents/pages/why-not-caqti.md diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 63181ca..ca452a6 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,28 +1,28 @@ -# The documentation site on GitHub Pages, rebuilt on every push to main: +# The documentation site on GitHub Pages: built on every pull request, which +# fails if agents/ is not what the pages write, and deployed from main. # odoc's reference from the .mli files, then Starlight's pages around it. name: docs on: push: branches: [main] + pull_request: +# A build reads the repository and nothing more; the deploy job alone is +# given the rights to publish. permissions: contents: read - pages: write - id-token: write +# A newer push to a pull request replaces its build; main's deploys queue +# and always finish. concurrency: - group: pages - cancel-in-progress: true + group: pages-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - deploy: + build: runs-on: ubuntu-24.04 - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/configure-pages@v6 - uses: actions/checkout@v5 - uses: ocaml/setup-ocaml@v3 with: @@ -38,8 +38,23 @@ jobs: # the token, past its limit for a runner's shared address. env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # The build writes agents/ from the pages: a page changed without it + # differs here. + - run: git add --intent-to-add agents/ && git diff --exit-code agents/ - uses: actions/upload-pages-artifact@v5 with: path: _build/docs + deploy: + needs: build + if: github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/configure-pages@v6 - uses: actions/deploy-pages@v5 id: deployment diff --git a/AGENTS.md b/AGENTS.md index ea8909d..a00f1db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,8 @@ make test # starts the test Postgres in Podman, runs every test; # RUNTIME=docker for Docker make lint # formatting, odoc, and the release build make fmt # format in place -make docs # the documentation site into _build/docs, as Pages publishes it +make docs # the documentation site into _build/docs, as Pages publishes it, and + # agents/ from its pages make docs-serve # the built site, served locally, search included make release VERSION=1.2.3 # once CHANGES.md names it: tag and release with open-opam ``` @@ -25,7 +26,8 @@ Bun. It runs every suite under `rowtype-test run`, one Postgres for the whole run, removed at its end; each suite on Postgres makes a template and a copy per case in it, and `test_sqlite` needs none. CI runs `make lint` and `make test` on OCaml 5.5, and `make test` again in Docker, and -`docs.yml` publishes the site to GitHub Pages on every push to `main`. +`docs.yml` builds the site on every pull request and publishes it to GitHub +Pages from `main`. ## Layout @@ -61,6 +63,10 @@ docs/ the documentation site, a Starlight site in Hypha's look, , odoc's reference copied into public/reference/ by make docs, and the site built into _build/docs, which dune clean removes +agents/ the documentation for a user's agent, generated by + starlight-hypha-agents from the pages, `make docs`: + llms.txt, the catalogue; pages/, each page as + Markdown; installed by the rowtype package examples/ the programs the site shows, each built, the SQLite ones run with the tests, and beside them each piece a page shows that is no program of its own, a plain module @@ -191,6 +197,12 @@ Each rule comes with why it exists and the test that catches a break. starts leaves the transaction, and its lock, on a connection its caller believes is free. Test: `transactions` in `test_rowtype` and in `test_sqlite`, `cancelled while waiting` among them. +- **`agents/` is generated, never edited.** starlight-hypha-agents writes + it from the documentation's pages and its options in + `docs/astro.config.mjs`: a page changed is `make docs` run in the same + commit. Why: a user's agent reads what the release installs, offline, + and a page it reads must be the release's. Test: the docs workflow builds + the pages on every pull request and fails if `agents/` then differs. - **The one module `open` is `open Shape` in `src/rowtype.ml`, and a local open is a span's alone**, `Mtime.Span.(10 * s)`. Why: the walk exists to pattern-match that GADT, and every constructor qualified would bury the diff --git a/CHANGES.md b/CHANGES.md index 47282b2..de65bb1 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,5 +1,11 @@ # Changes +## Unreleased + +- The rowtype package installs its documentation for agents: each page as + Markdown and `llms.txt`, at `$(opam var rowtype:doc)`. The README's *With an + agent* gives the line for a project's `AGENTS.md` that sends an agent there. + ## 0.10.2 (2026-11-10) - rowtype is published to open-opam, `opam repo add open-opam diff --git a/README.md b/README.md index fc2ea86..87dfd9a 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,18 @@ let () = The same statements run on SQLite unchanged: [SQLite](https://hyphatech.github.io/rowtype/guide/sqlite/). +## With an agent + +Each release installs its documentation for an agent with it, at +`$(opam var rowtype:doc)`: `llms.txt`, and every page in Markdown. An agent +reads it when your project's `AGENTS.md` tells it to: + +```md +Before writing code with rowtype, read `$(opam var rowtype:doc)/llms.txt` and +the pages it lists for the parts you need, and use those parts rather than +writing your own. +``` + ## Contributing See [AGENTS.md](AGENTS.md). diff --git a/agents/llms.txt b/agents/llms.txt new file mode 100644 index 0000000..42c74b7 --- /dev/null +++ b/agents/llms.txt @@ -0,0 +1,28 @@ +# rowtype + +> SQL queries and migrations for modern OCaml. + +## Start here + +- [Getting Started](pages/index.md): SQL queries and migrations for modern OCaml. +- [Quick start](pages/quick-start.md) +- [Why not Caqti?](pages/why-not-caqti.md) + +## Guides + +- [Statements](pages/guide/statements.md) +- [Columns and types](pages/guide/columns.md) +- [Bulk writes](pages/guide/bulk-writes.md) +- [Errors](pages/guide/errors.md) +- [Transactions](pages/guide/transactions.md) +- [Pools](pages/guide/pools.md) +- [Checking statements](pages/guide/checking-statements.md) +- [SQLite](pages/guide/sqlite.md) +- [Migrations](pages/guide/migrations.md) +- [Migrating from a test](pages/guide/migrating-from-a-test.md) +- [A database for a test run](pages/guide/test-databases.md) +- [A library's migrations](pages/guide/library-migrations.md) + +## Reference + +- [Reference](pages/reference.md) diff --git a/agents/pages/guide/bulk-writes.md b/agents/pages/guide/bulk-writes.md new file mode 100644 index 0000000..74d4a7b --- /dev/null +++ b/agents/pages/guide/bulk-writes.md @@ -0,0 +1,75 @@ +# Bulk writes + +Three ways write many rows, each in one round trip: a list bound as an +array, one statement run for each value, and a load through `COPY`. + +## A list bound as an array + +A list bound as an array writes many rows in one statement and one round +trip: + +```ocaml title="add_all.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let add_users = + S.exec + ~params:S.(t2 (array text) (array text)) + "insert into users (name, email) select * from unnest($1::text[], \ + $2::text[])" + +let add_all db users = Pg.run db add_users (List.split users) +``` + +For a few rows, this is the simplest: one statement, which +[`verify`](checking-statements.md) checks as any other. + +## One statement for each value + +`Pg.run_many db statement values` runs an `exec` statement once for each +value in one round trip, all or nothing: if any run fails, none applies. + +```ocaml title="add_each.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let add_user = + S.exec + ~params:S.(t2 text text) + "insert into users (name, email) values ($1, $2)" + +let add_each db users = Pg.run_many db add_user users +``` + +A statement that answers a row is refused before anything is sent, since a +batch reads no rows. + +## A load through COPY + +`Pg.copy_in` loads rows of any number with one `COPY`, each bound by its +shape as a statement's parameters are, and read from a `Seq.t` as they are +sent, so a load is held a row at a time: + +```ocaml title="load.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let load db users = + Pg.copy_in db ~table:"users" ~columns:[ "name"; "email" ] + S.(t2 text text) + (List.to_seq users) +``` + +It answers how many rows it wrote. `~columns` are in the row's order, every +column in table order where empty, and quoted as given, so `"Jobs"` is not +`jobs`; a number of them that is not the row's is refused before anything +is sent. `?schema` names the table's schema. + +A row that cannot be bound, a constraint, and a raise from the sequence each +fail the whole `COPY`, with nothing written and the connection usable; the +raise passes. A cancelled load closes the connection and cancels the `COPY`, +as for any statement. + +On SQLite, `Sq.copy_in` loads rows of any number from a `Seq.t` with one +prepared `insert`, all or none, as `Pg.copy_in` does with `COPY`. Inside a +transaction, the load is the transaction's, and goes with it. diff --git a/agents/pages/guide/checking-statements.md b/agents/pages/guide/checking-statements.md new file mode 100644 index 0000000..417c646 --- /dev/null +++ b/agents/pages/guide/checking-statements.md @@ -0,0 +1,65 @@ +# Checking statements + +`Pg.verify db statements` has Postgres describe every statement without +running it, and compares the parameters and columns with what you declared. +Run it in a test against a migrated database, and a renamed column fails the +test instead of a request. + +```ocaml title="check.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let statements = + [ + S.Any Orders.ship; + S.Any Orders.count; + S.Any Orders.find; + S.Any Orders.of_customer; + S.Any Orders.claim; + ] + +let check db = Pg.verify db statements +``` + +`S.Any` wraps a statement whatever it takes and answers, so every statement +of a program goes in one list. Here they are the +[statements page's](statements.md) `Orders`. + +## What it compares + +For each statement, how many parameters and, for a statement that reads +rows, how many columns, and each one's type: an `int` an integer or an +`oid`, a `float` a float, a `text` text, a name, a uuid or JSON, and the +rest their own, a domain as the type it is made from. A parameter the +database could not type is left to it. A statement it accepts is one +`Pg.run` reads. + +An enum is read and written by an `S.enum` each of whose labels is one of +the enum's. A label only the database has is no disagreement, since a +migration adds one ahead of the code that reads it, and a row holding it is +refused where it is read. An enum is also written from a `text`, and read as +one through a cast, `::text`. + +Whether a column may be NULL is not checked: the database says so only of a +column read as it is stored, and a query may promise more, so a check would +refuse what is right. A NULL a shape does not allow fails where it is read, +naming its column. + +## What it answers + +`` `Disagreements `` names every problem, in words for a person, each naming +its statement's first line and where in it. A check that could not ask -- a +lost connection -- is that failure, as a statement's is, and no statement is +said to disagree. `Pg.error_to_string` tells either. + +## On SQLite + +`Sq.verify db statements` prepares every statement without running it and +holds its parameters and columns to what you declared, a column of a table +to its declared type: an `integer` column as one an `int`, an `int64` or a +`bool` reads, a `real` one as a `float`'s, a `text` one as text's, an +instant's or any other kept as text, and a `blob` one as `bytes` or a +`uuid`. A column made by an expression, or declared with no type, holds any +kind of value, and is checked where it is read. Its placeholders are held to +the rule a statement runs by, so a statement it passes is not refused for +them when it runs. diff --git a/agents/pages/guide/columns.md b/agents/pages/guide/columns.md new file mode 100644 index 0000000..e985783 --- /dev/null +++ b/agents/pages/guide/columns.md @@ -0,0 +1,157 @@ +# Columns and types + +One shape describes a statement's parameters or its rows, and drives both +directions: binding the values going in and decoding the rows coming out. +A shape is built from the scalars below and the tuples over them. + +## The scalars + +| Column | Postgres | OCaml | +|---|---|---| +| `S.int` | `int2`, `int4`, `int8`, `oid` | `int`; an `int8` past 63 bits is refused | +| `S.int64` | `int2`, `int4`, `int8`, `oid` | `int64`, the whole of an `int8` | +| `S.float` | `float4`, `float8` | `float` | +| `S.text` | `text`, `varchar`, `char`, `name`, `uuid`, `json`, `jsonb` | `string` | +| `S.bytes` | `bytea` | `string` | +| `S.bool` | `bool` | `bool` | +| `S.instant` | `timestamptz` | `Ptime.t`, kept to the microsecond; years 1 to 9999, and infinity is refused | +| `S.date` | `date` | `Ptime.date`; years 1 to 9999, and infinity is refused | +| `S.timestamp` | `timestamp` | `Ptime.t`, the instant whose reading in UTC it is; years 1 to 9999, and infinity is refused | +| `S.interval` | `interval` | `S.interval`: months, days and microseconds, each apart; infinity is refused | +| `S.uuid` | `uuid` | `Uuidm.t` | +| `S.json` | `json`, `jsonb` | `string`, the document | +| `S.enum label values` | an enum | each of `values`, written as its `label` | + +Every scalar refuses a NULL; a column that may hold one is `S.opt`. An +instant is sent as ISO 8601 in UTC and read back whatever the session's +time zone. A value its scalar cannot hold is refused as what it is, saying +what reads it instead. SQLite keeps each scalar its own way, in +[its own table](sqlite.md#how-each-column-is-kept). + +An interval is months, days and microseconds apart, each signed on its own, +since a month is no fixed number of days and a day, across a change of +clocks, no fixed number of hours. A JSON document is its text; parsing it +is yours. + +## Tuples + +`S.t2` to `S.t11` combine shapes into a row or a list of parameters. They +are flat, so a call site never sees the nesting: `S.t3 S.int S.text S.bool` +is an `int * string * bool`. + +## Your own types + +`S.map` or `S.parse` read a column as your own type: `~parse` from the +column's, and `~print` back. + +```ocaml title="user.ml" +module S = Rowtype + +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)) +``` + +`S.parse`'s `~parse` may refuse a value, answering `Error` with a sentence +that says what it is not, which the row's error gives after the column's +name: + +```ocaml title="sku.ml" +module S = Rowtype + +type t = string + +let of_string s = + let upper_or_digit = function + | 'A' .. 'Z' | '0' .. '9' -> true + | _ -> false + in + if String.length s = 8 && String.for_all upper_or_digit s then Ok s + else Error "not a SKU, which is eight capitals or digits" + +let to_string s = s +let sku = S.parse S.text ~parse:of_string ~print:to_string +``` + +The sentence never holds the value, since a failure reaches a log. + +## Enums + +An enum is read and written through the labels of your own type: + +```ocaml title="colour.ml" +type t = Red | Green | Blue + +let all = [ Red; Green; Blue ] +let to_string = function Red -> "red" | Green -> "green" | Blue -> "blue" +let colour = Rowtype.enum to_string all +``` + +A row holding a label none of `values` has is refused, naming its column. +`Pg.verify` holds the column to an enum that has every one of the labels, so +a migration may add a label before the code that reads it ships. It refuses +an enum whose list is empty or gives two values one label. + +Shapes of your own types combine as any others: + +```ocaml title="products.ml" +module S = Rowtype + +let find = + S.find_opt ~params:Sku.sku + ~row:S.(t3 text Colour.colour (opt text)) + "select name, colour, note from products where sku = $1" +``` + +## NULL + +`S.opt` is a NULL. `None` binds NULL in every column the shape spans, and +decodes from a row where every one of them is NULL. A value that is itself +NULL in every column -- `Some None` of `S.opt (S.opt S.int)` -- reads back +as `None`, since a row cannot tell the two apart. + +## Arrays + +`S.array` is a Postgres array, a column holding a list, each value of the +element's shape: `S.array S.int` for a `smallint[]`, `S.array (S.opt +S.float)` for a `real[]` that holds NULLs, `S.array sku` for values read +through their own `S.parse`. + +```ocaml title="tagged.ml" +module S = Rowtype + +let tagged = + S.list ~params:S.text + ~row:S.(t2 Sku.sku (array text)) + "select sku, tags from products where $1 = any(tags) order by sku" +``` + +An element is one column and no array of its own: one dimension, as a list +has. A list has no first index, so an array is read in order from wherever +the database starts it. A list bound as an array also writes many rows in +one statement: see [bulk writes](bulk-writes.md). + +## Any other type + +Any other type -- `numeric`, `time`, a range, `inet` -- is read through a +cast in the SQL (`price::text`, `spans::text[]`) and `S.text`, and a read +without one is refused, saying so. It is written from `S.text` the same way, +cast to text and then to its type: `$1::text::numeric`, `$1::text::time`, +`$1::text::inet`. `$1::numeric` alone makes the parameter a `numeric`, which +`Pg.verify` refuses for a text. + +```ocaml title="prices.ml" +module S = Rowtype + +let price_of = + S.find ~params:Sku.sku ~row:S.text + "select price::text from products where sku = $1" + +let set_price = + S.exec + ~params:S.(t2 text Sku.sku) + "update products set price = $1::text::numeric where sku = $2" +``` diff --git a/agents/pages/guide/errors.md b/agents/pages/guide/errors.md new file mode 100644 index 0000000..093c686 --- /dev/null +++ b/agents/pages/guide/errors.md @@ -0,0 +1,83 @@ +# Errors + +Every failure is a value, and each says what a caller can do about it. + +## A statement's failures + +| Error | What it means | +|---|---| +| `` `Conflict (Some "users_email_key") `` | a unique, exclusion or foreign-key constraint refused the write, named | +| `` `Not_serializable `` | a transaction a concurrent one won: running it again may succeed | +| `` `Connection `Closed `` | the connection was closed before the statement was sent, so nothing it would have done was done | +| `` `Lost `` | the connection failed with the statement in flight -- a timeout, a broken socket, a server that ended the session -- so a write may have been applied | +| `` `Unsent `` | a connection that could not be made, or made again -- nothing answered -- so nothing was sent and trying again is safe | +| `` `Db `` | anything else | + +A NOT NULL or CHECK violation is the program's mistake, so it is `` `Db ``. +`` `Conflict `` is named because a table with two unique columns has two +different answers; an HTTP layer answers it 409, not 500. A lost write is +never run again blindly, only once what it did is known or doing it twice is +harmless. Inside a transaction, a statement lost before its `COMMIT` did +nothing, since an open transaction ends with its connection; only a lost +`COMMIT` may have committed. + +```ocaml title="sign_up.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let add_account = + S.find ~params:S.text ~row:S.int + "insert into accounts (email) values ($1) returning id" + +type answer = Created of int | Taken | Try_again | Unknown | Failed + +let sign_up db email = + match Pg.run db add_account email with + | Ok id -> Created id + | Error (`Conflict (Some "accounts_email_key")) -> Taken + | Error (`Unsent _ | `Not_serializable _) -> Try_again + | Error (`Lost _) -> Unknown + | Error e -> + Logs.err (fun m -> m "sign-up: %s" (S.error_to_string e)); + Failed +``` + +They are polymorphic variants, so they join your own errors in one result. +A match on them ends in a catch-all, as here, since a later release may add +one. + +## Words for a log + +`S.error_to_string` tells a statement's failure in words for a log, and +`Pg.error_to_string` every failure the Postgres backend answers. Neither +ever holds a parameter's value, since a code, a digest or a token is one: a +conflict is told by its constraint's name. + +## Every failure in one result + +Every failure the backend answers is a `Pg.error` -- a statement's, a +transaction's own, a pool's `` `Pool `Busy `` or `` `Pool `Closed ``, and +[`verify`'s](checking-statements.md) `` `Disagreements `` -- +so a transaction in a borrowed connection is one result, and +`Pg.error_to_string` tells all of it: + +```ocaml title="sign_up_in.ml" +module Pg = Rowtype_postgres + +let sign_up_in pool email = + match + Result.join + (Pg.Pool.use pool (fun db -> + Pg.Transaction.within db (fun db -> + Pg.run db Sign_up.add_account email))) + with + | Ok id -> Some id + | Error e -> + Logs.err (fun m -> m "sign-up: %s" (Pg.error_to_string e)); + None +``` + +A [transaction's](transactions.md) own failures are told +apart from its work's, and a [pool's](pools.md) from a +statement's. SQLite's are `Sq.error`, told by `Sq.error_to_string`, and +[its own page](sqlite.md#failures) says how each arises there. diff --git a/agents/pages/guide/library-migrations.md b/agents/pages/guide/library-migrations.md new file mode 100644 index 0000000..1006e14 --- /dev/null +++ b/agents/pages/guide/library-migrations.md @@ -0,0 +1,58 @@ +# A library's migrations + +A library that owns a table ships the migrations that make it, in its own +`migrations/`, installed with its package. Name it with `--source` and its +migrations run first, as a history of their own: + +```sh +rowtype-migrate up --source spool # the library's, then yours +rowtype-migrate up --source spool=vendor/sql # a library's folder, named +``` + +Each source is ordered and checked only among its own, so upgrading a +library whose migration is older than your last one applies it rather +than refusing it as late. The record says whose each migration is: yours +are `app`. `status`, `dump` and `squash` take `--source` too, and `squash` +leaves a library's tables out of your baseline, since its own migrations +make them. A squash is refused for a library that made what a baseline +could not tell from yours: on Postgres anything but tables -- a type, a +function, a view -- and on SQLite a view, or a trigger on what it did not +make. + +Repeat `--source` for each library, in the order they run. Libraries run +first, in the order given, and your migrations last, since they may stand +on the libraries' tables. + +## Shipping them + +A package installs its migrations in `share//migrations`, where +`--source ` finds them under the switch's prefix. In the library's +`dune`: + +```lisp +(install + (section share) + (package spool) + (files + (glob_files + (migrations/*.sql with_prefix migrations)))) +``` + +## From a test + +`Rowtype_migrate.of_package ~prefix package` reads a package's migrations, +and `Rowtype_migrate.source` names them, for `apply`'s `~libraries`: + +```ocaml title="migrate_with_libraries.ml" +let migrate env ~prefix target = + let ( let* ) = Result.bind in + let* spool = Rowtype_migrate.of_package ~prefix "spool" in + let* spool = Rowtype_migrate.source "spool" spool in + let* migrations = Rowtype_migrate.of_directory "migrations" in + Rowtype_migrate_postgres.run env target @@ fun db -> + Rowtype_migrate_postgres.apply ~libraries:[ spool ] db migrations +``` + +A source's name is lower-case letters, digits, hyphens and underscores, +starting with a letter, as a package's is; `app` is the application's, and +refused. diff --git a/agents/pages/guide/migrating-from-a-test.md b/agents/pages/guide/migrating-from-a-test.md new file mode 100644 index 0000000..c8203c1 --- /dev/null +++ b/agents/pages/guide/migrating-from-a-test.md @@ -0,0 +1,71 @@ +# Migrating from a test + +A test migrates its database through the library, which the +[command](migrations.md) is built on. `run` takes Eio's +environment and a target, and closes what it opened; `create`, `drop`, +`dump` and `squash` take the capabilities they use -- a switch, the network +and the clock, and for a dump the process manager -- so a test hands them +nothing more: + +```ocaml title="migrate_postgres.ml" +let migrate env target = + let ( let* ) = Result.bind in + let* migrations = Rowtype_migrate.of_directory "migrations" in + Rowtype_migrate_postgres.run env target @@ fun db -> + Rowtype_migrate_postgres.apply db migrations +``` + +On SQLite it is `Rowtype_migrate_sqlite`, with a file where Postgres has a +target: + +```ocaml title="migrate_sqlite.ml" +let migrate env file = + let ( let* ) = Result.bind in + let* migrations = Rowtype_migrate.of_directory "migrations" in + Rowtype_migrate_sqlite.run env file @@ fun db -> + Rowtype_migrate_sqlite.apply db migrations +``` + +`Rowtype_migrate.of_directory` reads every `.sql` file in a directory, in +version order, and refuses a file it cannot read as a migration, naming it. +`apply` applies every migration the database has not recorded, as the +command's `up` does, and `status` says what it would do, without doing it. + +## A database of the test's own + +`create` makes the database a target names, and `drop` drops it, refused +while anybody is connected to it: + +```ocaml title="test_database.ml" +module Pg = Rowtype_postgres + +let with_test_database env target test = + Eio.Switch.run @@ fun sw -> + let net = Eio.Stdenv.net env and mono_clock = Eio.Stdenv.mono_clock env in + let target = Pg.Conninfo.with_database target "shop_test" in + let ( let* ) = Result.bind in + let* () = Rowtype_migrate_postgres.create ~sw ~net ~mono_clock target in + let result = + let* () = Migrate_postgres.migrate env target in + test target + in + let* () = Rowtype_migrate_postgres.drop ~sw ~net ~mono_clock target in + result +``` + +`Pg.Conninfo.with_database` names another database on the same server. On +SQLite, `Rowtype_migrate_sqlite.create` makes an empty file, and `drop` +removes it with the files SQLite keeps beside it. + +## An application never migrates itself + +A migration is applied by the command, never by an application at start: a +dialect's `apply` is for a test and a tool. Every instance of an +application would race to migrate, its role would have to own the schema, +and no migration could run ahead of the code that needs it. + +A database the server does not have, or a SQLite file that is not there, is +`` `No_database ``, and `Rowtype_migrate.error_to_string` words every +failure for a person, naming the migration and what to do next. Once +migrated, the database is the one to [check statements +against](checking-statements.md). diff --git a/agents/pages/guide/migrations.md b/agents/pages/guide/migrations.md new file mode 100644 index 0000000..9e0ab5f --- /dev/null +++ b/agents/pages/guide/migrations.md @@ -0,0 +1,99 @@ +# Migrations + +Plain SQL files named `_.sql`, forward only, applied by a +command of their own before your application starts: + +```sh +rowtype-migrate create # make the database +rowtype-migrate new add_users # migrations/_add_users.sql +rowtype-migrate up # apply what is pending +rowtype-migrate status [--check] # applied and pending +rowtype-migrate dump [--check] # the schema they make, as db/schema.sql +rowtype-migrate squash VERSION # every migration through it, as one baseline +rowtype-migrate drop # drop the database, if nobody is connected +``` + +The command comes with `rowtype-migrate`, and migrates the dialects whose +backend is installed beside it. A command built without a dialect says what +to install for its URL. Every command has `--help`. + +## The database + +The database is `--url`, or `DATABASE_URL`: a Postgres URL or keyword list, +or `sqlite:PATH`, a file SQLite keeps. `--env` names another variable, and +`--env-file` reads it from a file of `NAME=value` lines, as a `.env` holds +them, rather than from the environment. + +The files are in `--dir`, `migrations` unless given. The record of what ran +is the table `--table`, `schema_migrations` unless given, so two +applications can keep two records in one database. + +## The files + +A migration's version is the UTC stamp in its name, fourteen digits, +`YYYYMMDDHHMMSS`: a timestamp rather than a counter, because two branches +that each add "migration 7" collide on merge where two timestamps do not. +`rowtype-migrate new` writes an empty one stamped with the time now, its +name lower-case letters, digits and underscores. Two files at one version +are refused, since two branches that each added a migration in the same +second are a merge somebody has to look at. + +## Applying them + +`up` applies each file in its own transaction and records a digest of it, +so two processes migrating at once take turns: Postgres's run holds an +advisory lock, `--lock N` naming another, and each of SQLite's transactions +takes the write lock as it begins and asks the record first. A flag only +Postgres reads -- `--lock`, `--pg-dump`, `--restrict-key` -- is refused for +a `sqlite:` URL, never ignored. + +A migration edited after it ran, or merged out of order, is refused, naming +it, and so is a database migrated from a newer checkout; nothing of its +source is applied. A file that ends its transaction itself with a `commit` +or a `rollback` is refused too, since what ran after that end ran outside +the transaction. A migration that fails leaves the database at the version +before it. The way back from a bad migration is the next one. + +Your application never migrates itself: the files are applied as a step of +their own before it starts, and `status --check` exits 1 while any migration +is pending, so a script can wait on it. Every instance of an application +migrating at start would race to apply the same files. + +## Outside a transaction + +A statement a database refuses inside a transaction -- Postgres's +`create index concurrently` or `vacuum`, SQLite's `vacuum` or the +`pragma foreign_keys = off` its table rebuild needs -- goes in a file of its +own whose first line is + +```sql +-- rowtype-migrate: no transaction +``` + +Such a file is one statement, and is recorded after it succeeds, so a run +cut off between the two runs it again: write it to run twice +(`create index concurrently if not exists`). + +## The schema, and a squash + +`dump` writes what the migrations add up to, migrated from nothing on a +scratch database, never what some database has drifted to: on Postgres, one +made on the server `--url` names and dropped after, written by `pg_dump`, +`--pg-dump` naming another command; on SQLite, one in memory. It is written +to `db/schema.sql`, `-o` naming another file, and changes only when the +schema does. `dump --check` writes nothing, and fails if the file is not +what the migrations make. + +A history grows, and a database made from nothing replays all of it. +`squash VERSION` replaces every file through that version with one +baseline, and proves the baseline makes the same schema as the history +before it changes a file. A database that recorded that version has the +baseline already, and what it recorded below it is history: accepted, and +compared with nothing. One whose record stops before it is refused, and is +migrated with a build from before the squash first. + +A SQLite dump and squash need no server and no `pg_dump`: each is migrated +in memory and written from SQLite's own schema. + +A test migrates its database through the library the command is built on: +see [migrating from a test](migrating-from-a-test.md). diff --git a/agents/pages/guide/pools.md b/agents/pages/guide/pools.md new file mode 100644 index 0000000..21f8c35 --- /dev/null +++ b/agents/pages/guide/pools.md @@ -0,0 +1,163 @@ +# Pools + +A connection is one fiber's at a time. A program serving requests makes a +pool once, where it starts, and lends its connections to each piece of +work. `rowtype-postgres` makes connections and pools as +[postgres-eio](https://hyphatech.github.io/postgres-eio/) makes them, +every option passed through. + +## A pool + +```ocaml title="pool.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let count_users = S.find ~params:S.unit ~row:S.int "select count(*) from users" + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + match Pg.Conninfo.of_string "postgres://app@localhost/shop" with + | Error m -> prerr_endline m + | Ok target -> ( + let ( let* ) = Result.bind in + match + let* pool = + Pg.Pool.create ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + ~size:16 ~observe:Counting.observe target + in + let users = + Result.join (Pg.Pool.use pool (fun db -> Pg.run db count_users ())) + in + Pg.Pool.close pool; + users + with + | Ok n -> + Printf.printf "%d users, in %d statements\n" n + (Atomic.get Counting.statements) + | Error e -> prerr_endline (Pg.error_to_string e)) +``` + +`Pg.Pool.create` opens every connection up front, and answers the first +that could not be made, closing those made before it. + +| Option | Default | | +|---|---|---| +| `~size` | 8 | connections, at least one | +| `~wait` | 5 s | how long a borrow waits for a connection | +| `~reset` | `true` | each connection's session reset before it is lent again | +| `~max_lifetime` | 30 min | a connection older than this is replaced | +| `~idle_check` | 60 s | a connection idle longer is pinged, and replaced if it fails | +| `~timeout` | 30 s | the longest a connection waits on the server for bytes to move | +| `~observe` | none | an [observer](#watching-statements) of every statement its connections run | + +The durations are `Mtime.Span.t`s, written `Mtime.Span.(2 * s)`. A +connection's reset ends what a borrower left in its session -- an open +transaction, a `LISTEN`, its settings -- and keeps the prepared statements +borrowers share; `~reset:false` keeps the settings. + +`Pg.Pool.use pool f` borrows a connection, runs `f` on the calling fiber, +and gives it back, even if `f` raises. It is `` `Pool `Busy `` if no +connection came free within the wait, and `` `Pool `Closed `` at once if the +pool is closed, or closes while the borrow waits. `Pg.Pool.stats` says how +many connections it keeps, how many are idle, how many borrows wait and how +many it replaced, for a health endpoint. `Pg.Pool.close` closes it. + +A transaction in a borrowed connection is one result: + +```ocaml +Result.join (Pg.Pool.use pool (fun db -> Pg.Transaction.within db work)) +``` + +## One connection + +`Pg.connect ~sw ~net ~mono_clock target` makes one connection, with the +same `?timeout` and `?observe`, `?parameters` for the session's settings, +sent as it starts (`("statement_timeout", "10s")`), and `?statement_cache` +for how many statements it keeps parsed, 256 unless given; `0` turns the +cache off, for a pooler without named statements. + +- `Pg.close db` closes it for good, telling the server; its next statement + says so. +- `Pg.revive db` makes again, in place, a connection a failure closed -- + the server restarted, say -- and is `Ok` at once for an open one. One + `close` closed stays closed. +- `Pg.timeout db` and `Pg.set_timeout db ~timeout` read and set the bound on + every read and write, lifted around work that runs longer, a migration, + and put back after it. + +A statement runs on the calling fiber. A fiber cancelled with a statement +in flight closes its connection and asks the server to cancel the +statement, so nothing runs on for nobody. A raise from `Pg.fold`'s function +passes, and closes the connection, whose answer was read only in part: its +next statement is `` `Connection `Closed `` until `Pg.revive`. + +## Watching statements + +An observer is handed each statement's text as it runs, and runs it -- a +span begun and ended around it, a count: + +```ocaml title="counting.ml" +module Pg = Rowtype_postgres + +let statements = Atomic.make 0 + +let observe : Pg.observer = + { + around = + (fun _sql run -> + Atomic.incr statements; + run ()); + } +``` + +The text has placeholders where the values are, and the values are never +handed over, since a code, a digest or a token is one. It watches a +transaction's `begin` and `commit` too. Each statement is also a `debug` +line on the `rowtype-postgres` log source, with how long it took: its first +line of text, never its parameters. + +## Notifications + +A session that ran `LISTEN` keeps what it hears, so a listener is a +connection of its own, never a pooled one: + +```ocaml title="listener.ml" +module Pg = Rowtype_postgres + +let ( let* ) = Result.bind + +let rec hear listener = + let* event = Pg.Listener.next listener in + (match (event : Pg.Listener.event) with + | Notification { channel; payload } -> + Printf.printf "%s: %s\n%!" channel payload + | Reconnected -> print_endline "reconnected: what was sent meanwhile is gone"); + hear listener + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + match Pg.Conninfo.of_string "postgres://app@localhost/shop" with + | Error m -> prerr_endline m + | Ok target -> ( + match + let* listener = + Pg.Listener.connect ~sw ~net:(Eio.Stdenv.net env) + ~mono_clock:(Eio.Stdenv.mono_clock env) + target + in + let* () = Pg.Listener.listen listener "orders" in + hear listener + with + | Ok () -> () + | Error e -> prerr_endline (Pg.error_to_string e)) +``` + +`Pg.Listener.next` answers the next notification, or waits for one. A lost +connection is made again, every channel listened to again, and said so: +`Reconnected`, since whatever was sent in between is gone. `~keep_alive` is +how long `next` waits in silence before it pings the server, 10 s unless +given. `Pg.Listener.unlisten` stops hearing a channel, and +`Pg.Listener.close` closes the listener for good. diff --git a/agents/pages/guide/sqlite.md b/agents/pages/guide/sqlite.md new file mode 100644 index 0000000..9ef19d6 --- /dev/null +++ b/agents/pages/guide/sqlite.md @@ -0,0 +1,237 @@ +# SQLite + +`rowtype-sqlite` runs the same statements on SQLite: the +[quick start's](../quick-start.md) `add_user` and `find_user` run on it +unchanged. Here they are in a module of their own: + +```ocaml title="users.ml" +module S = Rowtype + +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" +``` + +```ocaml title="sqlite.ml" +module Sq = Rowtype_sqlite + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let ( let* ) = Result.bind in + match + let* db = + Sq.connect ~sw ~mono_clock:(Eio.Stdenv.mono_clock env) "shop.db" + in + let* () = + Sq.exec_raw db + "create table if not exists users (id integer primary key, name text \ + not null) strict" + in + let* id = Sq.run db Users.add_user "Ada" in + Sq.run db Users.find_user id + with + | Ok (Some u) -> print_endline u.name + | Ok None -> print_endline "no such user" + | Error e -> + prerr_endline (Sq.error_to_string e); + exit 1 +``` + +`Sq.connect ~sw ~mono_clock file` opens the database in `file`, making it +where there is none. `":memory:"` is a database in memory, the connection's +alone. A file that cannot be opened is `` `Unsent ``, and the connection is +closed when `sw` finishes, unless `Sq.close` closed it first. + +## A C library + +Unlike every other package here, it binds C: SQLite is a library, not a +server, so there is no protocol to speak in OCaml, and it links your +system's SQLite through [sqlite3](https://github.com/mmottl/sqlite3-ocaml). +SQLite's calls wait on the disk and on other connections' locks, so each +statement runs on a system thread and the domain's other fibers go on +meanwhile; its rows are read 64 at a time. `connect`'s `~timeout` is how +long a statement waits for another connection's lock, 5 s unless given, +after which it is `` `Not_serializable ``. + +A fiber cancelled during a statement waits for the rows being read, then +the statement is ended and the cancellation passes. The connection is as +usable after it as before. + +## Placeholders + +A placeholder is `$1` as on Postgres, or SQLite's `?1` or `?`, each bound +by its number from the shape's values. One with a name, `:name`, is +refused, since a shape's values have none, and so are placeholders that do +not number the values from one, each at least once, before anything runs. +One statement runs at a time: a text holding several is `Sq.exec_raw`'s. + +## How each column is kept + +SQLite keeps four kinds of value, and each column is kept as one: + +| Column | SQLite | Kept as | +|---|---|---| +| `S.int`, `S.int64` | integer | an `int` past 63 bits is refused | +| `S.float` | real | an integer is read too where a float holds it exactly; a NaN is NULL | +| `S.text`, `S.json`, `S.enum` | text | | +| `S.bytes` | blob | | +| `S.bool` | integer | `0` or `1` | +| `S.instant` | text | UTC, `2026-10-20 09:24:46.621000`: what `datetime()` reads and writes, so it sorts as time and compares with `datetime('now')`; read with any zone the text gives | +| `S.timestamp` | text | the same, and one with a zone is refused | +| `S.date` | text | `2026-10-20` | +| `S.interval` | text | `P14M3DT-0.000005S` | +| `S.uuid` | text | `7c9e6679-7425-40de-944b-e07fc1f90ae7`; a blob of 16 bytes is read too | +| `S.array` | text | a JSON array, which `json_each($1)` reads and `json_group_array` writes; `bytes` in it as hex | + +Make tables `strict`, or declare each column `integer`, `real`, `text` or +`blob`. SQLite turns a value into its column's type where it can, and a +column of a type it does not know -- `uuid`, `json`, `timestamp` -- turns +text that looks like a number into one: a JSON document `123` comes back an +integer, which `S.json` refuses. A value of another kind than its scalar's +is refused, naming the kind and never the value. + +## Failures + +Each connection enforces foreign keys. A unique or primary key is +`` `Conflict (Some "users.email") ``, named by its columns as SQLite names +them, and a foreign key `` `Conflict None ``. A lock another connection still +holds once the wait is over -- 5 s unless `connect` is given `~timeout` -- +is `` `Not_serializable ``: nothing was done, and trying again may succeed. + +A statement SQLite cannot prepare fails in SQLite's words, which quote only +its text: `no such table: t`. One that fails as it runs is told by SQLite's +code alone, since a function quotes its argument in its message; a NOT NULL +or CHECK constraint keeps SQLite's words, which name the column or the +constraint and no value. + +## Transactions + +```ocaml title="sqlite_take.ml" +module S = Rowtype +module Sq = Rowtype_sqlite + +let balance_of = + S.find ~params:S.int ~row:S.int "select balance from accounts where id = $1" + +let withdraw = + S.exec + ~params:S.(t2 int int) + "update accounts set balance = balance - $2 where id = $1" + +let ( let* ) = Result.bind + +let take db account amount = + Sq.Transaction.within db ~behaviour:Immediate ~retries:3 (fun db -> + let* balance = Sq.run db balance_of account in + if balance < amount then Error `Insufficient + else Sq.run db withdraw (account, amount)) +``` + +SQLite's transactions are serializable; what you choose is when one takes +the write lock, `Deferred` (SQLite's own), `Immediate` or `Exclusive`. A +transaction that reads and then writes begins `Immediate`, or its write can +find another connection wrote since it read. A statement that fails inside +one undoes itself alone, as SQLite does, and the transaction goes on. A +`COMMIT` SQLite refuses is rolled back and said, as on Postgres: +`` `Conflict `` for a deferred foreign key, `` `Not_serializable `` for a +lock it could not take, and `` `Not_committed `` for anything else. + +`~retries` runs the whole transaction again when it meets +`` `Not_serializable ``, and `~keep` keeps what a refusal wrote, as on +[Postgres](transactions.md). Its `COMMIT` and each rollback +run to their end whatever cancels the fiber, so a cancellation never leaves +the transaction, or its lock, open. + +`Sq.Transaction.savepoint` and `Sq.Transaction.release` keep the work done +between them in the transaction, and say `` `Gone `` where that work ended +the transaction itself: for a script you did not write, run between the two. + +## A pool + +A connection is one fiber's at a time. `Sq.Pool.create ~sw ~mono_clock +"shop.db"` opens connections to one file up front and `Sq.Pool.use` lends +them, each given back with no transaction open; for readers alongside a +writer, turn on WAL once, `pragma journal_mode = wal`, which the file keeps. + +```ocaml title="sqlite_accounts.ml" +module S = Rowtype +module Sq = Rowtype_sqlite + +let add_account = + S.find + ~params:S.(t2 text int) + ~row:S.int + "insert into accounts (email, balance) values ($1, $2) returning id" + +let schema = + "drop table if exists accounts; create table accounts (id integer primary \ + key, email text not null unique, balance integer not null) strict" + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let ( let* ) = Result.bind in + match + let* pool = + Sq.Pool.create ~sw ~mono_clock:(Eio.Stdenv.mono_clock env) "accounts.db" + in + Result.join @@ Sq.Pool.use pool + @@ fun db -> + let* () = Sq.exec_raw db "pragma journal_mode = wal" in + let* () = Sq.exec_raw db schema in + let* () = + Sq.verify db + [ + S.Any add_account; + S.Any Sqlite_take.balance_of; + S.Any Sqlite_take.withdraw; + ] + in + let* ada = Sq.run db add_account ("ada@example.com", 100) in + (match Sq.run db add_account ("ada@example.com", 0) with + | Error (`Conflict (Some columns)) -> Printf.printf "taken: %s\n" columns + | Ok _ | Error _ -> + prerr_endline "a second account took the same email"; + exit 1); + let* () = Sqlite_take.take db ada 30 in + Sq.run db Sqlite_take.balance_of ada + with + | Ok balance -> Printf.printf "balance: %d\n" balance + | Error `Insufficient -> + prerr_endline "insufficient"; + exit 1 + | Error (#Sq.error as e) -> + prerr_endline (Sq.error_to_string e); + exit 1 +``` + +| Option | Default | | +|---|---|---| +| `~size` | 8 | connections, at least one | +| `~wait` | 5 s | how long a borrow waits for a connection, after which it is `` `Pool `Busy `` | +| `~timeout` | 5 s | each connection's wait for another's lock | + +A database in memory is refused, since each connection would have one of +its own: a pool is of a file. A connection a borrower left in a transaction +is rolled back before it is lent again. + +## Checking and loading + +`Sq.verify db statements` prepares every statement without running it, as +[checking statements](checking-statements.md#on-sqlite) says. +`Sq.copy_in` loads rows of any number from a `Seq.t` with one prepared +`insert`, all or none, as `Pg.copy_in` does with `COPY`. + +Each statement is a `debug` line on the `rowtype-sqlite` log source, with +how long it took: its first line of text, never its parameters. diff --git a/agents/pages/guide/statements.md b/agents/pages/guide/statements.md new file mode 100644 index 0000000..efeeb6f --- /dev/null +++ b/agents/pages/guide/statements.md @@ -0,0 +1,132 @@ +# Statements + +A statement is its SQL, the shape of its parameters and how many rows it +answers, in one value. It is declared once, beside the function that runs +it, and run by a backend's `run`, whose answer is the type the statement +says. + +## The SQL + +A statement reaches the database as written, in its own syntax. `rowtype` +reads no SQL. A placeholder is `$1`, `$2`, ... bound by position from the +shape's values, and `$1` twice asks about one value twice. Whether a +statement and its values agree in number is the database's to check, and +[`verify`'s](checking-statements.md) before any runs. + +## How many rows it answers + +| Statement | Answers | +|---|---| +| `S.exec ~params sql` | `unit` | +| `S.find ~params ~row sql` | exactly one row; none or several is an error | +| `S.find_opt ~params ~row sql` | at most one row; several is an error | +| `S.list ~params ~row sql` | every row, in the order the database sent them | +| `S.exec_count ~params sql` | how many rows it changed | + +```ocaml title="orders.ml" +module S = Rowtype + +let ship = S.exec ~params:S.int "update orders set shipped = true where id = $1" + +let count = + S.find ~params:S.int ~row:S.int + "select count(*) from orders where customer_id = $1" + +let find = + S.find_opt ~params:S.int + ~row:S.(t2 int (opt text)) + "select id, note from orders where id = $1" + +let of_customer = + S.list ~params:S.int + ~row:S.(t2 int int) + "select id, total from orders where customer_id = $1 order by id" + +let claim = + S.exec_count + ~params:S.(t2 text int) + "update orders set owner = $1 where id = $2 and owner is null" +``` + +`S.find` is for a statement the database guarantees answers one row, an +`insert ... returning` or an aggregate. A lookup that may find nothing is +`S.find_opt`'s, and one that may match several rows is `S.list`'s, or a +`limit 1` says which. `S.exec` and `S.exec_count` discard any rows the +statement answers. A statement with no parameters takes `S.unit`. + +## Running one + +`Pg.run db statement args` runs it with its parameters and answers what it +says it answers: + +```ocaml title="claim.ml" +module Pg = Rowtype_postgres + +let claimed db ~owner order = + Pg.run db Orders.claim (owner, order) + |> Result.map (fun changed -> changed = 1) +``` + +A guarded write run as `S.exec_count` is an answer rather than a write: +`update ... where owner is null` asks "did I get it", decided by the +database in one statement, where a read and then a write is two. + +A row with more columns or fewer than its shape reads is an error, as +[`verify`](checking-statements.md) refuses it before any run. + +## Reading rows as they arrive + +`Pg.fold db statement args ~init f` reads a `list` statement's rows as they +arrive, so a result of any size is read in the memory of one row: + +```ocaml title="spent.ml" +module Pg = Rowtype_postgres + +let spent db customer = + Pg.fold db Orders.of_customer customer ~init:0 (fun sum (_id, total) -> + sum + total) +``` + +Each row is decoded and handed to `f` as it arrives, as `List.fold_left` +would fold the list, without the list being made. A row that does not +decode is the answer, and `f` sees none after it. + +## One statement, many values + +`Pg.run_many db statement values` runs an `exec` statement once for each +value in one round trip, all or nothing: if any run fails, none applies. +No values sends nothing. + +```ocaml title="ship_all.ml" +module Pg = Rowtype_postgres + +let ship_all db ids = Pg.run_many db Orders.ship ids +``` + +[Bulk writes](bulk-writes.md) has the other ways to write +many rows. + +## DDL and settings + +`Pg.exec_raw db sql` runs statements with no parameters, several in one +call, and discards their rows: for DDL and a session's settings. + +```ocaml title="session.ml" +module Pg = Rowtype_postgres + +let set_up db = + Pg.exec_raw db "set statement_timeout = '5s'; set application_name = 'shop'" +``` + +A transaction is never a `begin` and a `commit` sent this way. The backend +runs its own, in [`Pg.Transaction.within`](transactions.md), +since only it can tell a commit from a transaction Postgres rolled back in +silence. + +## The same statements on every database + +`rowtype` runs no statement itself. `Rowtype.Make` over a backend gives the +functions that run statements on that database's connection, `run`, `fold`, +`run_many` and `exec_raw`, and `Rowtype_postgres` and `Rowtype_sqlite` are +each one. A statement names no database, so the same value runs on both, +and one program may use two databases at once. diff --git a/agents/pages/guide/test-databases.md b/agents/pages/guide/test-databases.md new file mode 100644 index 0000000..a0dbd4a --- /dev/null +++ b/agents/pages/guide/test-databases.md @@ -0,0 +1,93 @@ +# A database for a test run + +`rowtype-test` gives a test run Postgres the way a pytest session fixture +does: one server for the whole run, destroyed at its end whatever the +result, and a clean database for every test -- here a copy of a template +the suite's migrations made once, so no test sees another's rows and none +needs a migration down. + +``` +one Postgres container, for the whole run +├── suite_a_template its migrations run once; nobody connects to it +│ ├── a_test_1 copied from it for one test, dropped after +│ └── … +└── suite_b_template + └── … +``` + +## One server for a run + +```sh +rowtype-test run -- dune test --force +rowtype-test run --runtime docker -- dune test --force +``` + +The command starts Postgres in Podman, or in Docker with `--runtime +docker`, by its command line -- its data in memory, its durability off, on +a port the system chooses -- hands its address to the command and every +process it runs as `TEST_DATABASE_URL`, with the container it runs in as +`ROWTYPE_TEST_CONTAINER`, for a command such as `pg_dump` to run there, and +removes the container when the command ends, whatever its result. Where `TEST_DATABASE_URL` is set already, it starts +nothing. + +## A template a suite, a copy a test + +```ocaml title="test_server.ml" +(* A suite's Postgres: the server its runner hands -- rowtype-test run + hands one for a whole run -- or one of its own in Podman, removed as the + switch ends; the suite's migrations run once into a template; and a copy + of it for each case, dropped after. *) + +let run_suite env ~migrations cases = + Eio.Switch.run @@ fun sw -> + let migrate conninfo = + Rowtype_migrate_postgres.run env conninfo (fun db -> + Rowtype_migrate_postgres.apply db migrations) + in + match + Result.bind + (Rowtype_test.server ~sw ?url:(Sys.getenv_opt "TEST_DATABASE_URL") env) + (Rowtype_test.template ~setup:migrate) + with + | Error (#Rowtype_test.error as e) -> Error (Rowtype_test.error_to_string e) + | Error (#Rowtype_migrate.error as e) -> + Error (Rowtype_migrate.error_to_string e) + | Ok template -> + Ok + (List.map + (fun case -> + Rowtype_test.database template (fun conninfo -> case env conninfo)) + cases) +``` + +`Rowtype_test.server` is the server `TEST_DATABASE_URL` names; a suite run +alone, with none handed, starts one of its own and removes it when its +switch ends. `Rowtype_test.template` makes a database, runs the suite's +setup in it once -- its migrations -- ends every connection to it and +marks it a template. A setup that fails is the template's failure as +itself: a migration's error comes back as the migration's, for +`Rowtype_migrate.error_to_string` to word. `Rowtype_test.database` copies +it for one case -- +`CREATE DATABASE ... TEMPLATE`, tens of milliseconds -- rows the +migrations seeded included, and drops the copy after, with `(force)`. + +A copy is better than truncating between tests where correctness matters: +it keeps the rows migrations seed, which truncating wipes, and undoes +whatever else a test changed -- a table, a setting, a sequence. Roles and +`ALTER SYSTEM` are the server's, not a database's, so a test that makes a +role names it uniquely. + +## A killed run + +A run killed while its container ran leaves it behind. Every container +`rowtype-test` starts is labelled with the process that started it, and +the next run removes each whose process has ended: the next run is the +reaper, with no container of its own to do it. + +What a cleanup could not remove is said. A case's database that could not +be dropped is that case's `Error`. A container, a template, or the +database of a case that raised is a warning on the `Logs` source +`rowtype-test`, which `rowtype-test run` prints. + +The library reads no variable; a suite reads `TEST_DATABASE_URL` where it +starts, and hands it over. diff --git a/agents/pages/guide/transactions.md b/agents/pages/guide/transactions.md new file mode 100644 index 0000000..11e896d --- /dev/null +++ b/agents/pages/guide/transactions.md @@ -0,0 +1,108 @@ +# Transactions + +A transaction is the backend's, since each database runs one its own way: +`rowtype` runs none, and `Pg.Transaction.within` is the Postgres backend's. +SQLite's is [on its own page](sqlite.md#transactions). + +## Within a transaction + +```ocaml title="take.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let balance_of = + S.find ~params:S.int ~row:S.int "select balance from accounts where id = $1" + +let withdraw = + S.exec + ~params:S.(t2 int int) + "update accounts set balance = balance - $2 where id = $1" + +let ( let* ) = Result.bind + +let take db account amount = + Pg.Transaction.within db ~isolation:Serializable ~retries:3 (fun db -> + let* balance = Pg.run db balance_of account in + if balance < amount then Error `Insufficient + else Pg.run db withdraw (account, amount)) +``` + +`Ok` commits and `Error` rolls back. A raise inside the work rolls back and +passes. + +| Option | Default | | +|---|---|---| +| `~isolation` | the database's own, `Read_committed` in a Postgres nobody configured | `Read_committed`, `Repeatable_read` or `Serializable` | +| `~retries` | none | how many times the whole transaction runs again when it meets `` `Not_serializable `` | +| `~keep` | nothing | which refusals commit what they wrote anyway | + +Work that runs again does everything again, so work given `~retries` does +nothing but its statements: a message sent or a counter moved inside it +happens once for every attempt. Each retry is an `info` line, and the last +answer stands. + +`~keep` is for the rarer refusal that has to keep what it wrote -- a wrong +sign-in code that counts its attempt -- and still answers the refusal. + +## The transaction's own failures + +A transaction that could not commit is `` `Not_committed ``, never a silent +success, and one whose `COMMIT` was sent with no answer back is `` `Lost ``: +it may have committed. A `DEFERRABLE` constraint that refuses the write at +`COMMIT` is `` `Conflict ``, named, as it is when a statement finds it. +`` `Unsent `` is a transaction that never began, on a connection that could +not be made again, so nothing of the work was sent. + +`` `Not_committed `` is also the answer when the work answered `Ok` after a +failed statement aborted the transaction -- an error the work swallowed -- +since Postgres rolls such a transaction back in silence. A `within` inside +another is `` `Not_committed `` before anything begins, and the outer one +goes on. Each `` `Not_committed `` and `` `Lost `` is an `error` line on the +`rowtype-postgres` log source. + +The transaction's own failures are `Pg.Transaction.failure`, so a caller +whose errors are an ordinary variant tells them from its own: + +```ocaml title="members.ml" +module S = Rowtype +module Pg = Rowtype_postgres + +let add_member = + S.find ~params:S.text ~row:S.int + "insert into members (name) values ($1) returning id" + +type error = + | Empty_name + | Taken of string option + | Failed of string + | Unavailable of Pg.Transaction.failure + +let work db name = + if String.equal name "" then Error Empty_name + else + match Pg.run db add_member name with + | Ok id -> Ok id + | Error (`Conflict name) -> Error (Taken name) + | Error e -> Error (Failed (S.error_to_string e)) + +let join db name = + match + Pg.Transaction.within db (fun db -> + Result.map_error (fun e -> `Work e) (work db name)) + with + | Ok v -> Ok v + | Error (`Work e) -> Error e + | Error (`Conflict name) -> Error (Taken name) + | Error (#Pg.Transaction.failure as f) -> Error (Unavailable f) +``` + +A caller whose errors are polymorphic variants, as every statement's are, +writes nothing: the transaction's join the work's in one result. + +## A connection the server dropped + +`within` makes again a connection the server dropped before it begins, and +begins once more if the first `begin` fails, the one point where starting +again loses nothing. A fiber cancelled inside the work closes the +connection, which ends the transaction with nothing kept, and the +cancellation passes; the next `within` on it makes it again. diff --git a/agents/pages/index.md b/agents/pages/index.md new file mode 100644 index 0000000..905d5fb --- /dev/null +++ b/agents/pages/index.md @@ -0,0 +1,69 @@ +# Getting Started + +SQL queries and migrations for modern OCaml. + +rowtype runs plain SQL from OCaml. A statement is written as the database +reads it, and its parameters and its rows are described once, as OCaml +values. The same statements run on Postgres and on SQLite. A test can ask +the database to describe each one without running it, so a renamed column +fails a test instead of a request. Migrations are plain SQL files, applied +by one command for either database. + +```ocaml title="users.ml" +module S = Rowtype + +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" +``` + +## Install + +It needs opam, with a switch of OCaml 5.5 or later. + +```sh +opam repo add open-opam https://github.com/open-opam/opam-repository.git +opam install rowtype rowtype-postgres rowtype-migrate # Postgres +opam install rowtype rowtype-sqlite rowtype-migrate # SQLite, through its C library +``` + +| Package | What it is | +|---|---| +| `rowtype` | queries described once; links no database library | +| `rowtype-postgres` | the Postgres backend, over [postgres-eio](https://hyphatech.github.io/postgres-eio/) | +| `rowtype-sqlite` | the SQLite backend, over the [sqlite3](https://github.com/mmottl/sqlite3-ocaml) binding | +| `rowtype-migrate` | the migrations and the `rowtype-migrate` command, for each dialect installed beside it | +| `rowtype-test` | a Postgres database for a test run, in Podman or Docker, and the `rowtype-test` command | + +`rowtype-migrate` migrates the dialects whose backend is installed beside +it, and links no other: its libraries are `rowtype-migrate.postgres` and +`rowtype-migrate.sqlite`, each built where its backend is. + +`rowtype-sqlite` links your system's SQLite. Where it is missing, opam +offers to install it with your system's package manager. + +## Name the libraries + +A program names the libraries it uses in its `dune` file. On Postgres: + +```lisp +(libraries rowtype rowtype-postgres eio_main) +``` + +On SQLite: + +```lisp +(libraries rowtype rowtype-sqlite eio_main) +``` + +The [quick start](quick-start.md) writes a whole program, next. diff --git a/agents/pages/quick-start.md b/agents/pages/quick-start.md new file mode 100644 index 0000000..914159a --- /dev/null +++ b/agents/pages/quick-start.md @@ -0,0 +1,103 @@ +# Quick start + +A program that adds a user to Postgres and finds it again by the id +Postgres gave it. + +## The table + +It needs a Postgres it reaches as `postgres://app@localhost/shop`, holding +one table: + +```sql +create table users ( + id bigint generated always as identity primary key, + name text not null +); +``` + +## The program + +In a directory of its own, a `dune-project`: + +```lisp +(lang dune 3.18) +``` + +a `dune`: + +```lisp +(executable + (name main) + (libraries rowtype rowtype-postgres eio_main)) +``` + +and `main.ml`: + +```ocaml title="main.ml" +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" + +let () = + Eio_main.run @@ fun env -> + Eio.Switch.run @@ fun sw -> + let ( let* ) = Result.bind in + match Pg.Conninfo.of_string "postgres://app@localhost/shop" with + | Error m -> prerr_endline m + | Ok target -> ( + match + 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 + with + | Ok (Some u) -> print_endline u.name + | Ok None -> print_endline "no such user" + | Error e -> prerr_endline (S.error_to_string e)) +``` + +```console +$ dune exec ./main.exe +Ada +``` + +## What it does + +`user`, `add_user` and `find_user` are declared once, before anything +connects. `add_user` takes a `text` and answers one `int`, the id; +`find_user` takes an `int` and answers at most one `user`, read through +`S.map` from the row's two columns. `Pg.run` binds the values going in and +decodes the rows coming out, so `id` is an `int` and `u` a `user`, with no +conversion written by hand. + +Every failure is a value, here a `result`. `S.error_to_string` words one for +a log, and never holds a parameter's value. + +## Connecting + +A connection is made to a `Pg.Conninfo.t`, read once from a connection +string, a URL or a keyword list; `Pg.Conninfo.with_database` names another +database on the same server, and `Pg.Conninfo.with_connect_timeout` bounds +each address it tries. Connection strings are +[postgres-eio's](https://hyphatech.github.io/postgres-eio/), the driver +under `rowtype-postgres`. + +A program serving requests borrows its connections from a +[pool](guide/pools.md). The same statements run on +[SQLite](guide/sqlite.md) unchanged. diff --git a/agents/pages/reference.md b/agents/pages/reference.md new file mode 100644 index 0000000..fe2de7c --- /dev/null +++ b/agents/pages/reference.md @@ -0,0 +1,47 @@ +# Reference + +Every module's interface, generated by odoc from its `.mli`, where each +function says what it does, what it refuses and what it defaults to. + +## The packages + +Each package is separate, so a program links only what it uses. A `dune` +file names a library as it is installed (`rowtype-postgres`); OCaml code +names it as a module (`Rowtype_postgres`). + +| Package | Libraries | What it is | +|---|---|---| +| `rowtype` | `rowtype` | Queries described once; links no database library | +| `rowtype-postgres` | `rowtype-postgres` | The Postgres backend, over [postgres-eio](https://hyphatech.github.io/postgres-eio/) | +| `rowtype-sqlite` | `rowtype-sqlite` | The SQLite backend, over the [sqlite3](https://github.com/mmottl/sqlite3-ocaml) binding | +| `rowtype-migrate` | `rowtype-migrate`, `rowtype-migrate.postgres`, `rowtype-migrate.sqlite` | The migrations and the `rowtype-migrate` command, for each dialect installed beside it | + +## rowtype + +- [`Rowtype`](https://hyphatech.github.io/rowtype/reference/rowtype/Rowtype/index.html) -- shapes, + statements, errors, and the signature a backend fills. +- [`Rowtype_postgres`](https://hyphatech.github.io/rowtype/reference/rowtype-postgres/Rowtype_postgres/index.html) + -- connections, the pool, notifications, transactions, `COPY` and + `verify` on Postgres. Its parts: + [`Pool`](https://hyphatech.github.io/rowtype/reference/rowtype-postgres/Rowtype_postgres/Pool/index.html), + [`Listener`](https://hyphatech.github.io/rowtype/reference/rowtype-postgres/Rowtype_postgres/Listener/index.html) + and + [`Transaction`](https://hyphatech.github.io/rowtype/reference/rowtype-postgres/Rowtype_postgres/Transaction/index.html). +- [`Rowtype_sqlite`](https://hyphatech.github.io/rowtype/reference/rowtype-sqlite/Rowtype_sqlite/index.html) + -- connections, the pool, transactions, the load and `verify` on SQLite. + Its parts: + [`Pool`](https://hyphatech.github.io/rowtype/reference/rowtype-sqlite/Rowtype_sqlite/Pool/index.html) + and + [`Transaction`](https://hyphatech.github.io/rowtype/reference/rowtype-sqlite/Rowtype_sqlite/Transaction/index.html). +- [`Rowtype_migrate`](https://hyphatech.github.io/rowtype/reference/rowtype-migrate/Rowtype_migrate/index.html) + -- the files, the record and its rules, the same for every dialect. +- [`Rowtype_migrate_postgres`](https://hyphatech.github.io/rowtype/reference/rowtype-migrate/Rowtype_migrate_postgres/index.html) + -- migrating Postgres. +- [`Rowtype_migrate_sqlite`](https://hyphatech.github.io/rowtype/reference/rowtype-migrate/Rowtype_migrate_sqlite/index.html) + -- migrating SQLite. + +## What it is built on + +- [`Postgres_eio`](https://hyphatech.github.io/postgres-eio/) -- the + driver under `rowtype-postgres`, whose connection strings, pool and + listener it passes through. diff --git a/agents/pages/why-not-caqti.md b/agents/pages/why-not-caqti.md new file mode 100644 index 0000000..cfabc52 --- /dev/null +++ b/agents/pages/why-not-caqti.md @@ -0,0 +1,12 @@ +# Why not Caqti? + +Caqti is the mature choice, and the right one for MariaDB or Lwt. The +rowtype library does less, Postgres and SQLite on Eio only, and in return +gives you: + +- a driver written for Eio, [postgres-eio](https://hyphatech.github.io/postgres-eio/), + rather than libpq bindings or a driver adapted to it; +- every statement [checked against your database](guide/checking-statements.md), + from a test, without running it; +- [migrations](guide/migrations.md) in the box, the same files and + command for every dialect. diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index 52ade1b..fa9c727 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -2,6 +2,7 @@ import { fileURLToPath } from "node:url"; import { defineConfig } from "astro/config"; import starlight from "@astrojs/starlight"; import links from "starlight-links-validator"; +import agents from "starlight-hypha-agents"; import hypha from "starlight-theme-hypha"; // rowtype's documentation site, published to GitHub Pages by @@ -37,6 +38,10 @@ export default defineConfig({ tabs: { "Start here": "rocket", Guides: "book-open", Reference: "library" }, links: [{ label: "Hypha Stack", href: "https://hyphatech.io/stack", icon: "layers" }], }), + // Each page as Markdown and llms.txt, written into agents/ + // by the build, for the rowtype package to install; the docs + // workflow holds it to the pages. + agents({ dir: "../agents" }), // The reference is odoc's, in public/, which the validator cannot see. links({ errorOnLocalLinks: false, diff --git a/docs/bun.lock b/docs/bun.lock index 27faf2e..78e3565 100644 --- a/docs/bun.lock +++ b/docs/bun.lock @@ -7,8 +7,9 @@ "devDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3", + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0", }, }, }, @@ -295,6 +296,10 @@ "@ungap/structured-clone": ["@ungap/structured-clone@1.4.0", "", {}, "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ=="], + "acorn": ["acorn@8.19.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-oJlA3XiRm7Cyk6qFD2Jn8ak9B7jSy0qy00ADO3+8dpT0LSjFihQYv4C02LFCSYJV3Q37xYwwRy5m+IpIiUzqWw=="], + + "acorn-jsx": ["acorn-jsx@5.3.2", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="], + "am-i-vibing": ["am-i-vibing@0.5.0", "", { "dependencies": { "process-ancestry": "^0.1.0" }, "bin": { "am-i-vibing": "dist/cli.mjs" } }, "sha512-KLcsDhqf1XRrJmJr+9I/C0EX2K+sGrAGZFgkmd84c8TJO9zJBu+/kFInjazu1KfJWFhWDKdRWkpBzEs7s35DVA=="], "ansi-escapes": ["ansi-escapes@7.3.0", "", { "dependencies": { "environment": "^1.0.0" } }, "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg=="], @@ -399,6 +404,10 @@ "es-module-lexer": ["es-module-lexer@3.0.4", "", {}, "sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA=="], + "estree-util-is-identifier-name": ["estree-util-is-identifier-name@3.0.0", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="], + + "estree-util-visit": ["estree-util-visit@2.0.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/unist": "^3.0.0" } }, "sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww=="], + "eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="], "expressive-code": ["expressive-code@0.44.3", "", { "dependencies": { "@expressive-code/core": "^0.44.3", "@expressive-code/plugin-frames": "^0.44.3", "@expressive-code/plugin-shiki": "^0.44.3", "@expressive-code/plugin-text-markers": "^0.44.3" } }, "sha512-7RGslhJTNt01pdn5I3QmVh5C8ZIiSm0A+ORQ9j9r39oOgJVKjn/7dXl9rMT/SqmFLE6pJkTYI7UjW0BxJnW7OQ=="], @@ -535,8 +544,14 @@ "mdast-util-from-markdown": ["mdast-util-from-markdown@2.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "decode-named-character-reference": "^1.0.0", "devlop": "^1.0.0", "mdast-util-to-string": "^4.0.0", "micromark": "^4.0.0", "micromark-util-decode-numeric-character-reference": "^2.0.0", "micromark-util-decode-string": "^2.0.0", "micromark-util-normalize-identifier": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-KRLgmPaP2H1ul2bpoJkOS+9pAcDAAj9Nu1mqLnh8NLeJG5tlvj42TH80PIGBpROWlRXLk0lDrWNuZCFy/tsB4A=="], + "mdast-util-mdx": ["mdast-util-mdx@3.0.0", "", { "dependencies": { "mdast-util-from-markdown": "^2.0.0", "mdast-util-mdx-expression": "^2.0.0", "mdast-util-mdx-jsx": "^3.0.0", "mdast-util-mdxjs-esm": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w=="], + + "mdast-util-mdx-expression": ["mdast-util-mdx-expression@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-J6f+9hUp+ldTZqKRSg7Vw5V6MqjATc+3E4gf3CFNcuZNWD8XdyI6zQ8GqH7f8169MM6P7hMBRDVGnn7oHB9kXQ=="], + "mdast-util-mdx-jsx": ["mdast-util-mdx-jsx@3.2.0", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "ccount": "^2.0.0", "devlop": "^1.1.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0", "parse-entities": "^4.0.0", "stringify-entities": "^4.0.0", "unist-util-stringify-position": "^4.0.0", "vfile-message": "^4.0.0" } }, "sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q=="], + "mdast-util-mdxjs-esm": ["mdast-util-mdxjs-esm@2.0.1", "", { "dependencies": { "@types/estree-jsx": "^1.0.0", "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "devlop": "^1.0.0", "mdast-util-from-markdown": "^2.0.0", "mdast-util-to-markdown": "^2.0.0" } }, "sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg=="], + "mdast-util-phrasing": ["mdast-util-phrasing@4.1.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "unist-util-is": "^6.0.0" } }, "sha512-TqICwyvJJpBwvGAMZjj4J2n0X8QWp21b9l0o7eXyVJ25YNWYbJDVIyD1bZXE6WtV6RmKJVYmQAKWa0zWOABz2w=="], "mdast-util-to-hast": ["mdast-util-to-hast@13.2.1", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/mdast": "^4.0.0", "@ungap/structured-clone": "^1.0.0", "devlop": "^1.0.0", "micromark-util-sanitize-uri": "^2.0.0", "trim-lines": "^3.0.0", "unist-util-position": "^5.0.0", "unist-util-visit": "^5.0.0", "vfile": "^6.0.0" } }, "sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA=="], @@ -553,10 +568,22 @@ "micromark-extension-directive": ["micromark-extension-directive@4.0.0", "", { "dependencies": { "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-factory-whitespace": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "parse-entities": "^4.0.0" } }, "sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg=="], + "micromark-extension-mdx-expression": ["micromark-extension-mdx-expression@3.0.1", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q=="], + + "micromark-extension-mdx-jsx": ["micromark-extension-mdx-jsx@3.0.2", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "estree-util-is-identifier-name": "^3.0.0", "micromark-factory-mdx-expression": "^2.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ=="], + + "micromark-extension-mdx-md": ["micromark-extension-mdx-md@2.0.0", "", { "dependencies": { "micromark-util-types": "^2.0.0" } }, "sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ=="], + + "micromark-extension-mdxjs": ["micromark-extension-mdxjs@3.0.0", "", { "dependencies": { "acorn": "^8.0.0", "acorn-jsx": "^5.0.0", "micromark-extension-mdx-expression": "^3.0.0", "micromark-extension-mdx-jsx": "^3.0.0", "micromark-extension-mdx-md": "^2.0.0", "micromark-extension-mdxjs-esm": "^3.0.0", "micromark-util-combine-extensions": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ=="], + + "micromark-extension-mdxjs-esm": ["micromark-extension-mdxjs-esm@3.0.0", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-core-commonmark": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A=="], + "micromark-factory-destination": ["micromark-factory-destination@2.0.1", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA=="], "micromark-factory-label": ["micromark-factory-label@2.0.1", "", { "dependencies": { "devlop": "^1.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg=="], + "micromark-factory-mdx-expression": ["micromark-factory-mdx-expression@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "devlop": "^1.0.0", "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-events-to-acorn": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "unist-util-position-from-estree": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ=="], + "micromark-factory-space": ["micromark-factory-space@2.1.0", "", { "dependencies": { "micromark-util-character": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q=="], "micromark-factory-title": ["micromark-factory-title@2.0.1", "", { "dependencies": { "micromark-factory-space": "^2.0.0", "micromark-util-character": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0" } }, "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw=="], @@ -579,6 +606,8 @@ "micromark-util-encode": ["micromark-util-encode@2.0.1", "", {}, "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw=="], + "micromark-util-events-to-acorn": ["micromark-util-events-to-acorn@2.0.3", "", { "dependencies": { "@types/estree": "^1.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "estree-util-visit": "^2.0.0", "micromark-util-symbol": "^2.0.0", "micromark-util-types": "^2.0.0", "vfile-message": "^4.0.0" } }, "sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg=="], + "micromark-util-html-tag-name": ["micromark-util-html-tag-name@2.0.1", "", {}, "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA=="], "micromark-util-normalize-identifier": ["micromark-util-normalize-identifier@2.0.1", "", { "dependencies": { "micromark-util-symbol": "^2.0.0" } }, "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q=="], @@ -691,9 +720,11 @@ "space-separated-tokens": ["space-separated-tokens@2.0.2", "", {}, "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q=="], + "starlight-hypha-agents": ["starlight-hypha-agents@github:hyphatech/starlight-hypha-agents#3ee7026", { "dependencies": { "mdast-util-from-markdown": "^2.0.2", "mdast-util-mdx": "^3.0.0", "micromark-extension-mdxjs": "^3.0.0", "yaml": "^2.9.1" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-hypha-agents-3ee7026", "sha512-CRpk3KikuTkpb+Sbq5wMWOibJyR9DScrqijg08vp17qul6BB/GVfYV4XVK9nGVUsGJVjfYgVlCr5j51ZmXHf+A=="], + "starlight-links-validator": ["starlight-links-validator@0.27.0", "", { "dependencies": { "@astrojs/markdown-satteri": "^0.4.0", "github-slugger": "^2.0.0", "hast-util-from-html": "^2.0.3", "is-absolute-url": "^5.0.0", "mdast-util-mdx-jsx": "^3.2.0", "mdast-util-to-hast": "^13.2.1", "picomatch": "^4.0.3", "satteri": "^0.10.3", "terminal-link": "^5.0.0", "unist-util-visit": "^5.1.0", "yaml": "^2.8.3" }, "peerDependencies": { "@astrojs/starlight": ">=0.42.0", "astro": ">=7.2.10" } }, "sha512-UvPl8L9hfWR+yWbLOEtljLmpJCGcM6AVseVy5IO9dmqdOjW4R+Y8FaYyVA5axCC8RvxM5xU7M1WTerpwU8rYbw=="], - "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#4df8be9", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-4df8be9", "sha512-3ksSin8zktNtDQ9xnP2ihRZkXVaPMTXGxrFykNrXBR3vQT/sQffOD2vpeL+ZvObUP/KmslY4RPWJEnyxwi1npA=="], + "starlight-theme-hypha": ["starlight-theme-hypha@github:hyphatech/starlight-theme-hypha#a105fa6", { "dependencies": { "@fontsource-variable/roboto-slab": "^5.3.0", "@fontsource/inter-tight": "^5.3.0", "@lucide/astro": "1.48.0", "@tailwindcss/vite": "^4.3.3", "tailwindcss": "^4.3.3" }, "peerDependencies": { "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3" } }, "hyphatech-starlight-theme-hypha-a105fa6", "sha512-1lDTrqupxaVND5rueaGZVy2mokekMHaaDHAI3d4TBW8KujgEMRQ3Ftec3+CeXz4vG0NCEd8HCjyW13GBY/eUtQ=="], "std-env": ["std-env@4.3.0", "", {}, "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag=="], @@ -745,6 +776,8 @@ "unist-util-position": ["unist-util-position@5.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA=="], + "unist-util-position-from-estree": ["unist-util-position-from-estree@2.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ=="], + "unist-util-stringify-position": ["unist-util-stringify-position@4.0.0", "", { "dependencies": { "@types/unist": "^3.0.0" } }, "sha512-0ASV06AAoKCDkS2+xw5RXJywruurpbC4JZSm7nr7MOt1ojAzvyyaO+UxZf18j8FCF6kmzCZKcAgN/yu2gm2XgQ=="], "unist-util-visit": ["unist-util-visit@5.2.0", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.1.0" } }, "sha512-fpsYs/VVoZxfGY9/j3FQpZmN8wdLJaV1Pt38AaJNZu9uKIHcFU3halCdBveEq1HGKO1OEfJY65w1zvoFV1b3qQ=="], diff --git a/docs/package.json b/docs/package.json index bc8da30..c536847 100644 --- a/docs/package.json +++ b/docs/package.json @@ -6,6 +6,7 @@ "@astrojs/starlight": "~0.42.6", "astro": "^7.3.3", "starlight-links-validator": "^0.27.0", - "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.6.3" + "starlight-hypha-agents": "github:hyphatech/starlight-hypha-agents#v0.2.0", + "starlight-theme-hypha": "github:hyphatech/starlight-theme-hypha#v0.8.0" } } diff --git a/dune b/dune index 84a195a..ac355a3 100644 --- a/dune +++ b/dune @@ -6,3 +6,13 @@ (_ (flags (:standard -w +a-4-40-41-42-44-45-48-67-70)))) + +; The documentation for a user's agent, agents/, written from the site's pages +; by `make docs`: rowtype, which every other package depends on, installs it +; whole, so $(opam var rowtype:doc) holds llms.txt and each page. + +(install + (package rowtype) + (section doc) + (source_trees + (agents as .)))