Apps

Pgschema Designer

# pgschema-designer — PostgreSQL schema designer A visual designer for the PostgreSQL-native `deft/pgschema` document. It keeps the `%PgSchema{}` document as the source of truth, shows tables and views on a canvas, and emits the real artifacts an application consumes: `schema.sql`, `types.dft`, and `pgpersist.dft`. This is the PostgreSQL schema designer. `deft/schema-builder` is the generic codebase type manager (deftype/protocol overview + field constraints); this panel owns PostgreSQL tables/views/RLS and emits the `schema.sql` / `types.dft` / `pgpersist.dft` artifacts. ## Launching ```sh retro app deft/pgschema-designer ```` or copy `workspace-example.dft` into `.deft/workspaces/` and run: ```sh retro workspace pgschema-designer ```` The canvas is a `deft/ui/components/surface` widget and needs a GL host (`retro`/`hydra`). The inspector, relation list, and status bar are ordinary widgets and also render under `retra`. ## Connecting / importing The first action is either Import DB (`i`) or Open (`Ctrl+O`). - Import DB prompts for a libpq DSN (prefilled from `pgschema-designer/dsn` or `PGSCHEMA_DSN` when set), introspects the configured application schema, and loads it as an unsaved document. - Import configured DB (`Ctrl+I`) skips the prompt and uses `pgschema-designer/dsn`, falling back to `PGSCHEMA_DSN`. - Open loads a `.pgschema/schema.dft` file. Both pure `%PgSchema{...}` data files and generated `def <name> %PgSchema` modules are accepted. - Reload schema from disk re-reads the current file (asking first when the design has unsaved changes). Use it after editing `schema.dft` in an external editor. - Connect target DB… in the File menu opens a connection without replacing the document, so an opened schema can be diffed or migrated against a target database. Its DSN prompt is prefilled from the same config/env fallback. Connect configured target skips the prompt and uses `pgschema-designer/dsn` / `PGSCHEMA_DSN` directly. - Refresh re-introspects the live database. Diff and Migrate compare the document to the live catalog. Configuration (`.deft/config.dft` or a package config): ```clojure %{ "pgschema-designer/schema" "public" "pgschema-designer/dsn" "host=127.0.0.1 port=5432 dbname=clinic user=postgres" "pgschema-designer/schema-dir" "clinic.pgschema" "pgschema-designer/open" "clinic.pgschema/schema.dft" "pgschema-designer/grid" true "pgschema-designer/populate-rows" 8 "pgschema-designer/backup-dir" "" "pgschema-designer/pg-dump" "pg_dump" } ```` `pgschema-designer/schema` is the PostgreSQL schema name used for introspection and diff/migrate (default `public`). `dsn` seeds the Import DB and Connect target DB prompts (config wins over the last connected DSN) and is used directly by the quick-import/configured-target actions; it is never written to the schema document. If the workspace is running under the landlock sandbox, prefer a TCP DSN (`host=127.0.0.1 port=5432 …`) or allow the Unix-socket directory as a writable sandbox path. `open` optionally loads a schema file when the panel starts; `PGSCHEMA_OPEN` is the environment fallback for headless checks. The quick import DSN falls back to `PGSCHEMA_DSN` when config is unset. ## Files Saving writes two sibling files: ``` clinic.pgschema/ schema.dft # %PgSchema{...} document (pure data, or def form if loaded that way) design.dft # canvas positions and document name/version schema.sql # generated by Generate types.dft # generated deftype records pgpersist.dft # generated relation metadata + readers populate.json # AI dataset from Populate (optional) populate.reply.txt # raw AI reply/error (optional) backup-<schema>-<timestamp>.sql # pg_dump backup before Rebuild (optional) ```` New/imported documents are saved as pure data, so the designer can read them without evaluating generated code. The loader also accepts a `def <name> %PgSchema{...}` module (as produced by `pgschema/emit`), and saving one keeps that def form instead of silently converting it. Canvas positions live in `design.dft` so they survive reopen without polluting the schema document. ## Canvas | Action | Input | |--------|-------| | select a table/view | click its card | | select a column | click its row | | link a field (FK) | drag a table field onto another table's field | | break a link | `b`, or Schema → Break link… | | build a view | drag a table field onto a view card | | pan | drag empty canvas | | drag a card | drag its header | | zoom | wheel / trackpad scroll | | fit all | `g` or the Fit button | Tables are blue cards; views are purple and titled `view <name>`. A table with RLS enabled carries an `[RLS]` badge. Foreign-key constraints draw amber edges from the referencing table to the target table. Drag a field from the child table onto a field in the parent table to create or replace a single-column FK; the source field gets an `FK` marker and an edge. The target should be a primary-key or unique column (the status warns when it is not). Break link… (`b`) lists every FK link (child columns → parent columns) and removes the selected constraint from the document. Design changes are not applied to PostgreSQL until Migrate or Rebuild. The Table tab also lists every relation as a selectable list, so selection works without a GL canvas. Add view… (`V`) creates an empty draft view. Drag a field from a table onto the view card: - the first field sets the view base table, - more fields from the same table add output columns, - fields from another table add a `LEFT JOIN` when an FK path exists between that table and the view's tables; ON conditions come from the FK constraints, - dropping a field from an unrelated table is refused (no auto-join), - duplicate output names are prefixed with the source table name. A draft view (`view … (draft)`) is not emitted by Generate/Migrate/Rebuild until it has at least one field. The view inspector shows the base, selected columns, join count, and generated SQL. ## Editing The current panel covers structural application-schema editing: - add a table (`a`) with `id` and `created_at` starter columns; - add a column (`A` or `f`) with a type menu; - change a column type, required flag, or primary-key flag; - rename/delete the selected table, column, or view; - break a foreign-key link (`b`); - edit table/column/view Description metadata (`COMMENT ON`); - toggle table row-level security; - add an empty view (`V`), drag table fields onto it, and delete views; Deleting a table only changes the document. It removes incoming FK constraints from other tables and doc-level policies, triggers, and table grants that target the table. The confirmation lists those dependencies and view names that appear to reference the table; views are not auto-deleted. Use Rebuild to apply the deletion to PostgreSQL. Description buttons on the table/column/view inspectors edit the PostgreSQL `COMMENT ON` text. Descriptions are shown in the inspector, emitted by Generate, preserved by migration, and refreshed from the live catalog. Emptying a description clears the database comment on Migrate or Rebuild. Add table/view and rename/delete actions are available in the Schema menu. Editing markers on the canvas (PK/required/FK/RLS) updates as the document changes. Policies, grants, and roles are preserved by import, open/save, generation, diff, and migrate, but they do not yet have dedicated inspector editors. Functions and triggers have raw SQL editing and design-only deletion in the Functions tab (below); use `schema.dft` or the `pgschema` API for structured edits. ## Functions & Triggers The right-hand inspector has two tabs: Table (schema summary, the selected table/view/column properties, relation list, and migration note) and Functions (the functions and triggers in the design document). The floating Actions palette sits over the canvas; drag its title bar to move it, and click the ↔/↕ glyph (or Schema → Toggle palette orientation) to switch between horizontal and vertical layouts. The default comes from `pgschema-designer/palette-orientation` in config. Switching inspector tabs only changes the inspector. The Functions tab lists the functions and triggers in the design document. Select one to see Open in Editor and Delete; double-clicking a row opens it in the editor too. - Open in Editor writes the generated function/trigger SQL to a temporary `.sql` file and opens it in an editor panel. The file starts with a `-- pgdesign-key:` header that identifies the routine. - The project-local `pgdesign` editor extension adds PG Design → Stage SQL in Schema. It writes the current buffer to a temp file and publishes its path to this panel. The designer stores the edited SQL as the routine's `:sql` override, marks the document dirty, and does not touch PostgreSQL. Generated SQL and Diff/Migrate use the override. Discover the extension from `.deft/editor_ext/<name>/` (tag `editor-extension`) and enable it with `editor/extensions/pgdesign/enabled true`. - Delete removes a function or trigger from the design. Migrate now drops stale functions/triggers. A function used by a trigger cannot be deleted until those triggers are deleted first. Deleting a function also removes its function-grant entries from the design; policies or views that still call it must be handled separately or Migrate will fail when PostgreSQL reports the dependency. - Renaming function parameters is allowed. PostgreSQL cannot rename input parameters with `CREATE OR REPLACE`, so Migrate drops and recreates the function. Policies and triggers in the design that call it are dropped before and recreated afterward. Views, other functions, or a stale live policy that calls it but is not in the design block the replacement with a warning and must be handled first. - Function grants are emitted without an argument list when the function name is unique, so renamed parameters do not leave a stale grant. - Changing a trigger's name or target table is still rejected by the round-trip; stage a new trigger from the document instead. ## Generate / diff / migrate Generate writes `schema.sql`, `types.dft`, and `pgpersist.dft` next to the saved document. It uses the same planners as the library, so the preview and generated files are the real DDL, not a parallel dialect. Preview SQL (`p`, PostgreSQL → Preview SQL) opens the generated `schema.sql` in a workspace editor panel (creating one if needed) instead of showing it in a dialog; re-running it refreshes the same preview buffer. Diff produces a conservative migration plan without touching the database. Plan shows the statements. Migrate applies the plan in a transaction and then refreshes the document from the live catalog. The v1 migration rules are the same as `pgschema/migrate`: conservative for tables and views, while stale functions/triggers are dropped and changed triggers are replaced. A table rename is inferred when exactly one missing desired table and one stale live table have the same structural shape; it is emitted as `ALTER TABLE ... RENAME TO ...` and incoming FKs, policies, triggers, and table grants follow the new name. Table/column/view drops, column renames, type rewrites, and changed existing views/policies are reported rather than silently applied. Deleting a routine in the Functions tab is design-only until Migrate drops it. Column nullability is migrated with `ALTER COLUMN … SET/DROP NOT NULL`, so making a field required shows up as a pending statement; backfill existing NULLs first, because PostgreSQL rejects `SET NOT NULL` and the migration rolls back otherwise. ## Data viewer Toggle data viewer in the inspector (or press `v`, or use PostgreSQL → Toggle data viewer). When on, a read-only grid appears beneath the canvas and follows the current selection: a table shows `SELECT *` from the live connection, a view shows its live result. Columns come from the document, so the grid stays in schema order; re-selecting another relation refreshes it automatically. The panel header's Refresh button reruns the query after external writes. It is capped at 100 rows per relation. The viewer reads the connected live database, not the unsaved document. A table or view that has not been migrated yet reports the PostgreSQL error until you migrate or refresh. With no connection it shows a hint instead of querying. Click the grid once to focus it, then scroll with the wheel, arrows, PgUp/PgDn, Home/End, or drag the scrollbar; the data pane keeps its scroll position across refreshes. The SQL checkbox (or `s`) opens a second pane to the right of the grid showing the last data SQL. Copy SQL (or `y`) copies the whole statement to the system clipboard; the pane itself is selectable/scrollable, and Ctrl+C copies the selected lines. ## Populate from AI PostgreSQL → Populate with AI… (`P`) appends AI-generated test rows to the connected database. It builds a schema-aware prompt from the document's tables, columns, defaults, identity flags, checks, and foreign keys, then asks the configured AI provider for a JSON dataset. Tables are inserted parent-first in one transaction, with explicit identity values (`OVERRIDING SYSTEM VALUE` where needed) and sequences advanced to `max(column)` afterwards. - Existing rows are kept. Populate only inserts; it never truncates or recreates the database. Use a disposable or owned database. Migrate unsaved document changes first so the live columns match the prompt. - The number of rows requested per table is `pgschema-designer/populate-rows` (default `8`, capped at 50). - The dataset is saved as `populate.json` beside the schema file (or in the current directory for an unsaved document) before any insert, and the raw AI reply/errors go to `populate.reply.txt`. If `populate.json` already covers every table, Populate reuses it instead of calling AI; delete the file to regenerate fresh data. A failed insert rolls the transaction back and leaves the dataset on disk for inspection/retry. Reusing a dataset after a successful run can collide on primary/unique keys — delete `populate.json` for a fresh AI run. - Integer primary keys get a "next id" hint based on the live `max(id)` so a second run does not collide with existing rows. Foreign keys in the generated dataset reference rows from the same dataset. - AI configuration follows the workspace: an `:ai` prelude map (via `ai/load-cfg`) wins, otherwise `ai/provider` / `ai/model` config, then `ai/default-cfg`. Calls use temperature 0, thinking off, no tools, and retry empty/invalid/incomplete replies twice. - AI output is parsed as data only — never evaluated. After a successful run the status line reports the inserted/table counts and the data viewer refreshes if enabled. ## Rebuild from design PostgreSQL → Rebuild schema from design… (dangerous) (`R`) applies the in-memory document by dropping and recreating the application schema. It is the way to make deletions and other non-additive design changes real without a save/generate/load-SQL round trip. The action first writes a pg_dump backup of the current schema (data included) to `pgschema-designer/backup-dir`, or next to the schema file / current directory when unset. The backup filename is `backup-<schema>-<timestamp>.sql`; `pgschema-designer/pg-dump` selects the binary (default `pg_dump`). If the backup fails, nothing is dropped. After the backup, the following runs in one transaction: 1. `DROP SCHEMA <schema> CASCADE` 2. recreate the schema (and public usage grant) 3. apply the generated DDL for the current document Any error rolls the whole transaction back and leaves the database intact. On success the live document is refreshed and the data viewer updates. Roles and other schemas are untouched. All rows and all objects in the application schema are destroyed, including objects not represented by the document and extension-owned objects inside it (extensions listed in the document are recreated). Migrate remains the safe path for tables and views; it never drops stale tables or views, but it drops stale functions/triggers and replaces changed triggers. Diff/Plan shows stale tables/views so it is clear when a Rebuild is needed. ## Run SQL / reset schema The PostgreSQL menu has two file-based actions for the current connection: - Run SQL file… lists the `.sql` files in the project's current working directory (top-level files; if none exist, it scans subdirectories). Pick one from the list and it executes with `pg/exec`. The file is executed as one simple-query batch; psql meta-commands (`\i`, `\copy`, …) are not supported. It does not change the open schema document—use Refresh afterwards if the file changed the live catalog. - Clear DB + Load SQL… (dangerous) uses the same `.sql` list, then requires typing `CLEAR`. It drops the current application schema (`public` or the document/config schema) with `CASCADE`, recreates it, and runs the file in the same batch. This destroys all tables, views, functions, triggers, policies, and extensions in that schema; roles and unrelated schemas are not created or dropped. Cascading dependencies can still affect objects outside the schema, so use it against disposable or owned databases. Both actions require an active connection with rights to create/drop the schema. The clear+load batch is transactional: if the SQL fails, the drop and partial load are rolled back. Files containing explicit transaction control or non-transactional statements such as `CREATE INDEX` CONCURRENTLY` should be run with **Run SQL file…** instead.` ## Keys | Key | Action | |-----|--------| | `Ctrl+O` | open schema | | `Ctrl+S` | save | | `Ctrl+I` | import configured DSN | | `Ctrl+R` | refresh from database | | `i` | import DB (DSN prompt) | | `a` | add table | | `A` / `f` | add column to selected table | | `d` | diff | | `m` | migrate | | `n` | rename selection | | `e` | edit selected table/column/view description | | `Delete` / `Backspace` / `x` | delete selection | | `g` | fit canvas | | `p` | preview generated SQL in the editor | | `P` | populate with AI | | `R` | rebuild the schema from the design (destructive; backs up first) | | `V` | add an empty draft view | | `v` | toggle the data viewer | | `s` | toggle the SQL pane (next to the data viewer) | | `y` | copy the current data SQL | | `1`…`9`, `0` | select relation by list position (10 = `0`); with a table selected, select its column by position | | `Esc` | clear selection (returns to the relation list) | Canvas/editing shortcuts apply on the Table tab. Diff (`d`), Migrate (`m`), and refresh (`r`/`Ctrl+R`) work on both tabs. ## Limits (v1) - The data viewer is read-only (100-row cap, no ad-hoc SQL editor). Use Run SQL file… for arbitrary statements. - Drag-built views auto-join only through existing FK relationships. Raw or imported SQL views cannot accept field drops; create a new empty view to use the builder. Renaming/deleting a source table or column does not rewrite the view builder yet; recreate the view if it becomes stale. - AI populate inserts test data into the connected application schema; it never drops or truncates. It relies on the model honoring FK and check constraints, and can fail on unique/FK collisions with existing rows (the transaction rolls back). Composite/range/array values follow the model's JSON strings for those PostgreSQL types. - Rebuild requires `pg_dump` (config `pgschema-designer/pg-dump`) and a DSN saved by connecting with the DSN prompt/configured import. If the backup fails, nothing is dropped. The backup is a plain SQL dump; it is not restored automatically. - No structured policy/function/trigger/grant editors yet. Functions and triggers can be opened in the editor as raw SQL from their tab; changing a function signature or a trigger's name/table is rejected there. - Drag-built views support field projection plus FK auto-joins; manual ON/WHERE/ORDER editing is not available yet. - No multi-select, grouping, or undo. Table renames update columns, constraints, indexes, foreign-key references, policies, triggers, and table grants; raw SQL (view bodies, CHECK expressions, function bodies) is not rewritten. Deleting a table or column removes dependent local constraints/indexes and incoming foreign keys; raw SQL may still reference the deleted object. - No writable views; generated readers are reads (`all`/`find`/`get`), with `db/query` for arbitrary projections. - Custom composite types require explicit `:fields` specs in generated readers; the designer does not yet introspect them as first-class nodes. - The canvas is GL-host only. Under `retra`, use the relation list and inspector in the Table tab. - Clear DB + Load SQL… resets the current application schema, not the database or roles. It requires typing `CLEAR`; keep a backup. Files with transaction control or non-transactional statements may not be atomic. ## Tests Pure model + document I/O (no database): ```sh cd packages/pgschema-designer ../../deft/zig-out/bin/deft --prelude test/prelude.dft test test/test_designer_model.dft ../../deft/zig-out/bin/deft --prelude test/prelude.dft test test/test_designer_canvas.dft ../../deft/zig-out/bin/deft --prelude test/prelude.dft test test/test_designer_io.dft ../../deft/zig-out/bin/deft --prelude test/prelude.dft test test/test_populate.dft ```` Headless panel shell and startup open (no database): ```sh ./ui/zig-out/bin/retra drive packages/pgschema-designer/test/drive_smoke.dft \ -- packages/pgschema-designer/workspace-example.dft PGSCHEMA_OPEN=packages/pgschema/test/fixtures/clinic/clinic.pgschema/schema.dft \ ./ui/zig-out/bin/retra drive packages/pgschema-designer/test/drive_open.dft \ -- packages/pgschema-designer/workspace-example.dft PGSCHEMA_OPEN=packages/pgschema/test/fixtures/clinic/clinic.pgschema/schema.dft \ ./ui/zig-out/bin/retra drive packages/pgschema-designer/test/drive_preview.dft \ -- packages/pgschema-designer/workspace-example.dft PGSCHEMA_OPEN=packages/pgschema/test/fixtures/clinic/clinic.pgschema/schema.dft \ ./ui/zig-out/bin/retra drive packages/pgschema-designer/test/drive_routines.dft \ -- packages/pgschema-designer/workspace-example.dft ```` Import/diff/migrate smoke against a disposable PostgreSQL (the clinic fixture schema; use TCP for the headless driver): ```sh PGSCHEMA_DSN='host=127.0.0.1 port=55432 user=postgres dbname=clinic_designer' \ ./ui/zig-out/bin/retra drive packages/pgschema-designer/test/drive_import.dft \ -- packages/pgschema-designer/workspace-example.dft ```` Run-SQL / clear+load integration (creates a disposable database): ```sh cd packages/pgschema-designer DEFT_TEST_PG_DSN='host=127.0.0.1 port=55432 user=postgres dbname=postgres' \ ../../deft/zig-out/bin/deft --prelude test/prelude.dft test \ test/test_designer_sql_pg.dft ````