An Ecto-Style ORM
Longer than a recipe: one library, designed in the open, one decision per chapter. A database layer in the shape of Ecto, which is a good stress test of comptime because the schema is a type, the query builder is checked against that type before the program runs, migrations are data, and the driver sits behind one seam so the same code runs on SQLite or PostgreSQL.
- The schema is a type. Every other part of the library is derived from it at compile time rather than declared twice.
- A query builder that checks field names during compilation turns a class of runtime SQL errors into build errors.
errdeferis what makes a transaction correct on the error paths you did not think about, which are the ones that matter.- Put the driver behind one seam and the same query code runs on two databases. Scatter it and it runs on whichever you wrote first.
9 chapters.
- What Is an Ecto-Style ORM?The Elixir design these chapters borrow from, explained for people who never wrote Elixir.
- A Type Function as the Front DoorThe core move of a Zig library: take the caller's type, return a richer one.
- A Typed Query BuilderCompile-time field checking and injection-proof rendering, with no allocator.
- Validation from DeclarationsOptional capabilities discovered with @hasDecl, the convention-over-configuration of Zig.
- Writing RowsINSERT and UPDATE statements derived from the schema, with values as a typed array.
- The Adapter SeamOne query renderer, several SQL dialects, resolved at compile time.
- Migrations as DataSchema history as an append-only list, and applying it as a pure plan.
- The RepoThe composition root, and the fake driver that makes the whole ORM testable.
- Transactions and errdeferCOMMIT on success, ROLLBACK on every error path, enforced by four lines.