Apps
Pgschema
# pgschema — PostgreSQL-native application schemas
`pgschema` is the PostgreSQL application layer that sits beside
`deft/persist`. It does not try to be store-neutral:
- SQLite/simple apps use `deft/persist`.
- PostgreSQL applications use `pgschema` + generated `pgpersist` modules.
The schema document is the source of truth. From it, `pgschema` renders
DDL and a schema-specific `pgpersist.dft`. There is no runtime schema
reflection and no `_persist_meta_` table: the generated code knows the
schema, migrations live in the repository, and drift is detected by
introspecting the live catalog.
For interactive design, `deft/pgschema-designer` is a panel app that
imports a live schema, edits tables/columns/RLS/views on a canvas, saves
`schema.dft` + `design.dft`, generates the three artifacts, and runs
diff/migrate. Its `help/help.md` covers launch, config, keys, and limits.
## Quick start
import "deft/pgschema" as ps import "deft/pgschema/emit" as emit import "deft/pgschema/pgpersist" as db def schema %PgSchema{ :name "notes" :extensions @{ "btree_gist" } :tables @{ %PgTable{ :name "note" :columns @{ %PgColumn{ :name "id" :type :integer :primary-key true :identity :by-default } %PgColumn{ :name "title" :type :string :required true } %PgColumn{ :name "amount" :type :decimal :precision 10 :scale 2 :default "0" } } } } :views @{ %PgView{ :name "note_view" :sql "SELECT id, title, amount FROM note" :columns @{ %PgColumn{ :name "id" :type :integer } %PgColumn{ :name "title" :type :string } %PgColumn{ :name "amount" :type :decimal :precision 10 :scale 2 } } } } } set ddl [ps/sql $schema] # string or %Err set module [emit/pgpersist $schema] # generated module source
Apply the DDL with a normal PostgreSQL client:
set store [pg/connect "host=/run/postgresql dbname=notes user=app"] set r [await [pg/exec $store $ddl]]
The generated module exposes relation binders:
import "notes.pgschema/pgpersist.dft" as gen set notes [gen/note $store] set rows [await [db/all $notes]] set one [await [db/get $notes 1]]
## Document model
`%PgSchema{}` contains:
| Key | Meaning |
|---|---|
| `:name`, `:version` | schema identity and generated-code version |
| `:schema` | default PostgreSQL schema (`"public"` by default) |
| `:roles` | roles the application references; DBA-provisioned |
| `:extensions` | required extensions |
| `:tables` | `%PgTable{}` records |
| `:views` | `%PgView{}` records (`security_invoker` by default); `:draft true` views are validation-only and not emitted |
| `:functions` | `%PgFunction{}` records; `:language` is one of `:sql`, `:plpgsql`, `:pldeft`, `:pldeftu` |
| `:triggers` | `%PgTrigger{}` records |
| `:policies` | `%PgPolicy{}` records |
| `:grants` | `%PgGrant{}` records |
Tables have columns, table-level constraints, indexes, and RLS toggles.
Columns, tables, views, and functions carry an optional `:comment`
(PostgreSQL `COMMENT ON`) description, emitted by `ps/sql`, read by
`introspect`, and updated by `migrate`. Designer-built views may also carry
`:builder` (base/columns/joins) metadata; `:sql` remains canonical.
Column types are PostgreSQL-oriented: `:string`, `:integer`, `:number`
(double precision), `:decimal` with `:precision`/`:scale`, `:boolean`,
`:uuid`, `:timestamptz`, `:jsonb`, `:tstzrange`, `:tsrange`, `:daterange`,
`:int4range`, `:int8range`, `:numrange`, range arrays (`:range-array` with
a `:range-type`), and explicit `:pg-type`
escape hatches.
Raw SQL expressions are intentionally allowed for `:check`, `:default`,
`:expression`, `:using`, `:where`, view `:sql`, and function `:body`.
Functions and triggers may also carry `:sql` as a raw DDL override; when
present `ps/function-sql` / `ps/trigger-sql` emit it verbatim and diff/migrate
compare that text. The structured fields remain the routine identity (name,
args, table) used for keys and drops. The document is reviewed source, not
an evaluation surface.
## Validation and planning
- `[ps/normalize $doc]` → `%Ok{:value doc}` or `%Err`.
- `[ps/validate $doc]` → structural checks (duplicates, references,
identity types, decimal precision/scale, unknown trigger functions).
- `[ps/plan $doc]` → `%Ok{:value statements}` in dependency order.
- `[ps/sql $doc]` → one DDL string.
- `[ps/statements $doc]` → the statement vector.
The v1 emitter covers fresh-schema DDL. `pgschema/introspect` reads an
existing database back into a document:
import "deft/pgschema/introspect" as intro set r [await [intro/introspect $store "public" "clinic"]] # %Ok{:value %PgSchema{...}} or %Err set doc [get $r :value] set ddl [ps/sql $doc] # regenerate the schema set module [emit/pgpersist $doc] # regenerate the read layer
It covers application objects: tables, columns, identity/defaults,
PK/unique/FK/check/exclusion constraints, simple and expression indexes,
views, functions (SQL/PLDEFT), triggers, policies, grants, roles,
extensions, and object/column descriptions. Raw CHECK/USING/view/function
expressions are preserved as SQL. Use it to import an existing application
schema, then let the designer edit the resulting document. Table creation is topologically
ordered by FK dependencies. Live-catalog diffing and migration planning
live in `pgschema/migrate`; `pgschema` never stores a schema descriptor in
the database.
Backtracking from a live database:
set r [await [intro/introspect $store "public" "clinic"]] set doc [get $r :value] [emit/write-doc $doc "clinic.pgschema/schema.dft"] [emit/write-sql $doc "clinic.pgschema/schema.sql"] [emit/write-pgpersist $doc "clinic.pgschema/pgpersist.dft"]
`write-doc` emits a canonical one-line document; run
`deft fmt --write clinic.pgschema/schema.dft` to make it readable.
## Diff and migration
`pgschema/migrate` compares the desired document against the live catalog:
import "deft/pgschema/migrate" as mig set d [await [mig/diff $store $doc "public"]] set plan [get $d :value] [deft/stringify [get $plan :statements]] # ordered SQL [deft/stringify [get $plan :report]] # per-object status set m [await [mig/migrate $store $doc "public"]] # %Ok{:value %{:applied n :statements @{...} :report ...}}
It is deliberately conservative for tables/views and authoritative for
routines:
- creates missing extensions, tables, columns, PK/unique/FK constraints,
indexes, functions, views, triggers, policies, and grants
- replaces changed functions, triggers, and indexes (same-signature
functions use CREATE OR REPLACE; trigger and index changes are
DROP/CREATE)
- drops stale functions and triggers (the table/view/column drops remain
conservative)
- replaces a raw-SQL function whose signature text changed (for example a
parameter rename) with DROP FUNCTION + CREATE; dependent policies and
triggers from the design are dropped before it and recreated afterward.
Dependent views, other functions, or a stale live policy that is not in
the design block the replacement with a warning until handled
- emits function grants without an argument list when the function name
is unique, so argument names are not part of privilege statements;
overloaded names keep the explicit signature
- enables RLS/force-RLS when the document asks for it
- applies column nullability changes (`SET NOT NULL` / `DROP NOT NULL`);
`SET NOT NULL` fails and rolls back the migration when existing rows
contain NULL, and `DROP NOT NULL` is reported rather than applied for
primary-key/identity columns
- applies `COMMENT ON` changes for table/column/view/function descriptions
(removing a description emits `IS NULL`)
- infers a table rename when exactly one missing desired table and one
stale live table have the same structural shape, emitting
`ALTER TABLE ... RENAME TO ...` (incoming FKs, policies, triggers, and
table grants follow the new name)
- reports changed column types/defaults/identity, changed view SQL,
changed policies, extra database columns/indexes/grants, and stale
tables/views
- never drops tables/columns/views, and never revokes privileges
- applies the statements in one transaction; `CONCURRENTLY` is disabled
for planned index changes
Changed existing views/policies are reported for explicit recreation
rather than silently replaced, so a text-only difference does not produce
a perpetual migration. Functions and triggers are replaced automatically.
A function replacement that must drop the function also drops/recreates
the design policies and triggers that call it; views and other functions
that call it block the replacement with a warning.
For non-additive changes (deleting tables, rewriting objects), use the
destructive rebuild path:
set r [await [mig/rebuild $store $doc "public"]] # %Ok{:value %{:schema "public" :tables N :views M}} or %Err
`rebuild` validates and renders the document, then drops the application
schema with `CASCADE`, recreates it, and applies the generated DDL in one
transaction. It does not create a backup; callers (the designer does
this with `pg_dump`) must back up first when the data matters. Errors roll
back the transaction.
## Generated `pgpersist` modules
`[emit/types-text $doc]` / `[emit/write-types $doc path]` generate a
standalone `types.dft` of `deftype` records for every table and view.
Relations get PascalCase type names (`app_user` → `AppUser`,
`appointment_detail` → `AppointmentDetail`); `pgpersist` metadata carries
the matching `:deftype`, so `all`/`find`/`get` return typed records.
`db/query` stays map-based (it may select a subset of columns).
`[emit/pgpersist $doc]` writes a module with:
- `import "./types"` (the generated types must sit beside it)
- `schema-name` / `schema-version`
- `relations`: schema, table, kind, primary key, deftype name, and column metadata
- `repo`: bind a relation by name
- one binder per table/view (`gen/appointment`, `gen/appointment-detail`, …)
The runtime (`deft/pgschema/pgpersist`) provides:
| Function | Result |
|---|---|
| `[db/all $repo]` | all rows, decoded |
| `[db/find $repo spec]` | `:where`, `:order`, `:limit`, `:offset` |
| `[db/get $repo id]` | one row by single/composite primary key |
| `[db/count $repo ?spec]` | count with optional `:where` |
| `[db/query $repo sql ?params]` | raw SQL decoded as maps (no generated deftype) |
| `[db/with-context $store settings body]` | transaction with `set_config(..., true)` |
| `[db/with-resource $store id body]` | convenience for `app.resource_id` |
| `[db/health $store ?meta]` | database/role/server/pldeft version |
| `[db/watch $store channel handler]` | `LISTEN` + `pg/on-notify` |
Decoding rules:
- `numeric`/`:decimal` columns are selected as `::text` and returned as
`%Decimal{:value "…"}` — never f64.
- `jsonb` columns are parsed into Deft maps/vectors.
- Range columns become `%PgRange{:lower :upper :bounds :empty}` maps
(the same shape PL/Deft returns). Integer range bounds are numbers;
date/time/numeric bounds stay strings; `nil` means unbounded.
- Range arrays become vectors of `%PgRange`; type metadata carries the
element `:range-type`.
- Composite columns can use `:type :composite` with an ordered `:fields`
spec vector and are decoded with `db/decode-composite`.
- Large `int8` values should use an explicit text/decimal decode path;
the default pg client decodes integers through f64.
Range helpers:
[db/range-text [db/range 1 3]] # "[1,3)" [db/range-array-text @{ [db/range 1 3] [db/range 5 7] }] # {"[1,3)","[5,7)"} # %PgRange values work in find filters; the runtime adds the type cast. [await [db/find $ranges %{ :where %{ :span [db/range 1 3] } }]]
## Database per tenant
The primary deployment model is one database per tenant, with the
same schema document and generated module applied to each database.
There is no `tenant_id` column and no tenant-isolation policy: isolation
is the database boundary. RLS is for application roles and row
ownership inside a tenant. The DBA/app provisioner creates the database
and the referenced roles; the app applies the generated DDL and
migrations. No per-database schema descriptor is stored.
## Roles, RLS, and policies
Roles are references. `pgschema` generates `GRANT` and
`CREATE POLICY … TO role`; it never generates `CREATE ROLE` or
`DROP ROLE`. Provision roles with the database/DBA tooling.
Policies use ordinary PostgreSQL expressions. The clinic fixture uses
a session GUC:
```sql
NULLIF(current_setting('app.resource_id', true), '')::bigint
````
The `NULLIF` is intentional: PostgreSQL custom GUCs can become the empty
string after a `SET LOCAL` transaction, and casting an unset/empty value
to bigint would otherwise abort the query. `pgpersist/with-resource`
sets the GUC transaction-locally.
Application roles should not own the tables. If the app connects as the
table owner, RLS is bypassed unless `FORCE ROW LEVEL SECURITY` is set.
## Views and observability
- Views default to `WITH (security_invoker = true)` so the caller's RLS
applies to the underlying tables.
- Writes through views are not supported in v1; views are read models.
- PLDEFT triggers are the application observability seam: audit rows,
outbox rows, and `pg_notify` events.
- `app.health()`-style functions return a small JSONB map (schema
version, database, role, pldeft version) without a metadata table.
## Clinic fixture
`test/fixtures/clinic/` is derived from
`/home/ritchie/Projects/practice/schema.sql` and made deterministic:
- models scheduling as event + involvement: `appointment` + `booking`
- adds `resource_kind` / `resource_role` policy tables and a partial
exclusion constraint (`exclusive AND released_at IS NULL`)
- adds `released_at` + `appointment_release` so cancelling frees the slot
- adds `appointment.kind`, series recurrence, and authored `outcome` rows
- changes `resource.id` to `GENERATED BY DEFAULT` for explicit seed ids
- adds `doctor.consultation_fee NUMERIC(10,2)`
- adds audit/outbox tables and PLDEFT triggers
- adds `security_invoker` read views and participant/PHI RLS
- keeps roles DBA-provisioned (`roles.sql` is test/DBA-only)
Files:
```
clinic.pgschema/schema.dft # document
clinic.pgschema/parts/ # table/view/function/policy/grant sections
clinic.pgschema/types.dft # generated, checked in
clinic.pgschema/pgpersist.dft # generated, checked in
roles.sql # test-only role provisioning
seed.sql # deterministic clinic data
````
Tests:
```sh
# pure document/DDL/codegen tests
deft --prelude test/prelude.dft test test/test_pgschema.dft
# end-to-end PostgreSQL test (disposable cluster recommended)
DEFT_TEST_PG_DSN='host=/tmp/pgsock port=55432 user=postgres dbname=postgres' \
deft --prelude test/prelude.dft test test/test_clinic_pg.dft
````
The integration test creates one uniquely named database, provisions the
referenced roles if missing, applies the generated schema, seeds it,
exercises `pgpersist`, RLS, security-invoker views, exact decimals,
PLDEFT audit/outbox triggers, the exclusion constraint, and `app_health`,
then drops the database.
## Limits (v1)
- The diff planner is conservative for tables/views: no table/column/view
drops, column renames, type changes, default rewrites, or policy/view
replacement. Those are reported for a human/designer decision. Stale
functions/triggers are dropped and changed triggers are replaced. Table
renames are inferred by unique structural match. CHECK/exclusion
constraints are emitted for new tables but are not diffed on existing
tables.
- Introspection covers ordinary tables and application objects, not
partitioned tables, replication/publications, tablespaces, custom
types/domains/enums, procedures, or event triggers. Expression indexes
are preserved as raw `CREATE INDEX` statements.
- Fresh-schema ordering is tables (FK topo) → functions → views →
triggers → policies → grants. A function that queries a view, a view
that depends on another view, or a cyclic FK graph is not yet
dependency-sorted; use explicit ordering/appends for those cases.
- Function bodies are dollar-quoted with `$pgschema$`; a body containing
that exact tag is not supported.
- Referenced roles and extensions must exist in the target database;
`pgschema` validates roles in the designer/planner, but the SQL emitter
itself assumes the DBA/provisioner has created them.
- No partitioning, replication, publications, tablespaces, or fleet
migration runner. Those are DBA/system concerns.
- Views are read-only; writable views (`INSTEAD OF` triggers) are a
later application feature.
- Roles/extensions are references; no role CRUD.
- Raw SQL expressions are not structurally validated.
- The runtime supports simple `:where` equality filters; richer reads
use `db/query` or a view.
- No `_persist_meta_`, no stored schema descriptor, no runtime
reflection.