sqitchcraft

The tools

What each one does, how to install it, and the commands you will use most. Each repository's README has the full reference.

If you want to…Use
Change a table by editing its filesqiff
Start a new object, or a change that takes several releasescreate-migration, from the sqitch-with-templates repository
Catch lock and rewrite hazards before reviewsqint
Keep SQL files in one format, without changing what they dopgfmt
Deploy to a busy database without queueing trafficpsql-retry
Check a Haskell service's queries against the schemahasql-check
Enforce a lifecycle in the databasestatecharts, installed as the pg_statecharts extension
Build your own tooling on sqitch.plansqitch-plan, a Haskell library

Adds sqitch changes from templates that hold what we learned migrating a busy production database.

It runs sqitch add with one of 20 templates and names the change after what it creates. The migration templates stop waiting for a lock after 50 ms, the index templates build concurrently, constraints are added not valid and validated separately, and scripts that cannot run in a transaction are written to be run again. Missing values are asked for, with completion from your deploy/ folders.

nix run github:kronor-io/sqitch-with-templates -- --help
nix profile install github:kronor-io/sqitch-with-templates
CommandWrites
table, view, domainA new object in its own file
function general, function statechartA function, or a statechart callback taking fsm_event_payload
trigger row, trigger statementA trigger and its function, under trigger/<table>/
migrationA dated, hand-written change with lock timeouts in place
add-column, add-index, validate-constraintOne safe step each
non-nullable-columnFive changes: add, check not valid, backfill, validate, set not null
bulk-updateA batched update that commits between batches
rename-column-step-1, -step-2A rename that old and new code survive
add-index-partitioned, add-fk-partitionedPer-partition builds for pg_partman tables

Use --db TARGET for another target in sqitch.conf, and --template-directory for your own templates. The flake also builds sqitchPg, a sqitch with the templates installed, so plain sqitch add --template add_column works.

Compares PostgreSQL schemas and writes the difference as sqitch changes.

Edit a table's create table file and sqiff writes the migration that gets an existing database there: dependent views, functions, constraints and policies dropped and recreated around it with their comments and grants, a revert for every step, and the hazards of each one. It reads both schemas from PostgreSQL's catalogs rather than parsing SQL.

nix run github:kronor-io/sqiff -- --help
docker run --rm -v "$PWD:/work" ghcr.io/kronor-io/sqiff --help
curl -fsSL "https://github.com/kronor-io/sqiff/releases/latest/download/sqiff-$(uname -m)-linux.tar.xz" | tar -xJ -C ~/.local
CommandDoes
sqiff table FILE [--write]The migration for an edited table file, compared with master. --write adds it and reworks the table.
sqiff diff --from master|rev:REV|CONN [--to CONN]What differs and what depends on it. Exits 1 on a difference.
sqiff plan --from … [--to …]The ordered SQL, each step with its hazards.
sqiff sqitch --from … [--dry-run]Writes that plan as sqitch changes.
sqiff describe [--out DIR]The schema as one file per object, to commit and review.

Configure it in sqiff.yaml next to sqitch.conf: schemas to leave out, change-name patterns, create-migration's templates, and how to start the scratch database for --from master. It asks rather than guesses when a dropped and an added column might be a rename.

Lints sqitch migrations for PostgreSQL lock and rewrite hazards.

The static pass parses deploy scripts, PL/pgSQL bodies included, with PostgreSQL's own parser. The dynamic pass deploys each change into a scratch database and reports the locks it actually took, the casts the planner confirms defeat an index, and the functions a change left broken.

nix run github:kronor-io/sqint -- --help
sqint $(git diff --name-only main -- database/deploy)
RuleSeverityReports
lock/add-columnBLOCKA not null column without a default
lock/add-constraintBLOCKA check or foreign key without not valid
lock/alter-column-typeBLOCKA type change that rewrites the table
lock/create-indexWARNAn index built without concurrently
index/cast-on-columnWARNA cast on a column in a predicate
index/defeatedBLOCKThe planner confirms a sequential scan
txn/set-local-across-commitBLOCKset local in a block that commits
function/broken-bodyBLOCKA SQL function left failing after a change
lock/observed-*variesA lock the dynamic pass saw taken

BLOCK exits 1. There is no configuration file: silence one statement with -- lint:ignore reason="…", and the reason is required.

Formats PostgreSQL files without changing what any statement does.

It reads each file with PostgreSQL's own parser, lays out each statement, and parses the result again: a statement is rewritten only if PostgreSQL sees the same statement afterwards. Comments and blank lines between statements stay byte for byte, and the SQL statements inside PL/pgSQL bodies are formatted too.

nix run github:kronor-io/pgfmt -- --help
curl -fsSL "https://github.com/kronor-io/pgfmt/releases/latest/download/pgfmt-$(uname -m)-linux.tar.xz" | tar -xJ -C ~/.local
# the SQL files this branch adds or changes, without rework snapshots
changed=$(git diff --name-only --diff-filter=AM master -- 'database/*.sql' | grep -v @)
pgfmt $changed            # rewrite them
pgfmt --check $changed    # or only report them, for CI

On the example project's invoice table, as an older create-migration template wrote it, with upper-case BEGIN;, and with pgfmt's defaults:

-- database/deploy/billing/table/invoice.sql
-BEGIN;
+begin;
     create table if not exists billing.invoice (
         id bigint generated always as identity primary key,
         customer_email text not null,
-        amount numeric(12,2) not null,
+        amount numeric(12, 2) not null,
         …
-    comment on table billing.invoice is
-      'An invoice sent to a customer.';
+    comment on table billing.invoice is 'An invoice sent to a customer.';
         …
     create index if not exists invoice_customer_email
-        on billing.invoice (customer_email);
+    on billing.invoice using btree (customer_email);

DDL is laid out by libpg_query, which spells a few things its own way: using btree is written out, and integer can become int. Each one parses to the same statement, which is what pgfmt checks. A set value keeps its single quotes: set lock_timeout to '50ms' stays as it is. The formatted example project deploys, verifies, reverts and deploys again exactly as before.

OptionDoes
pgfmt FILE…Rewrites the files in place; with no files, reads stdin and writes stdout, for editors.
--checkChanges nothing, names the files that are not formatted, and exits 1.
--keyword-case lower|upperHow keywords are spelled. Identifiers are never changed.
--backend auto|syntax|libpg-queryWho lays statements out: pgfmt's renderer (leading commas, DML) or libpg_query's (trailing commas, anything, and all DDL).
-vSays which statements were left as written, and why.

Format what your branch adds or changes, and leave the rest alone. A migration that is already on master has been deployed as written, and a @tag snapshot is that same deployed text, so keep both out of the file list, as the commands above do with grep -v @. Exit code 2 means a file is not valid SQL, or a statement failed the check and was kept as it was.

Runs psql again when a script fails with a lock timeout.

Retrying from outside the database avoids the subtransactions a retry loop inside PL/pgSQL would open. It reruns on canceling statement due to lock timeout only, with jittered backoff from 10 ms capped at 60 s, up to 500 times. Any other error stops it.

nix run github:kronor-io/psql-retry -- --help
PSQL_ARGS="'postgres://…' -v ON_ERROR_STOP=1 -f script.sql" psql-retry
sqitch deploy --client database/psql-retry.sh

Called directly, pass ON_ERROR_STOP=1, or psql exits 0 after an error and nothing is retried. sqitch sets it for you. The wrapper script that turns sqitch's arguments into PSQL_ARGS is on CI and deploys.

statecharts

kronor-io/statecharts

A statechart interpreter built entirely inside PostgreSQL.

Charts are rows: states, nested states, parallel regions, final states and transitions, following SCXML. Sending an event runs the transition and its on_entry and on_exit callbacks in the statement that sent it, so the state commits with your data. Every state a machine enters is logged. Send events from transactions at SERIALIZABLE, or at least REPEATABLE READ, and retry serialization failures.

create extension pg_statecharts cascade;     -- pure SQL; needs ltree. PostgreSQL 16 to 18

select fsm.start_machine_with_latest_statechart(statechart_name => 'invoice_flow');
select fsm.notify_state_machine(machine_id => 42, event_name => 'invoice.pay',
                                data => '{"amount": "120.00"}');
select fsm.is_state_active(machine_id => 42, state_id => 'paid');

Install it with PGXN (pgxn install pg_statecharts), a Debian package, or make install. On development machines, pg_statecharts_dev turns .scxml files into sqitch changes with fsm.gen_statechart_sqitch_migrations; never create it in production. A Haskell SDK generates state and event types from a chart. Projects that deployed the engine as a sqitch project can move to the extension with create extension pg_statecharts version 'sqitch'.

Lifecycles works through a real invoice chart: callbacks, the function every event goes through, late and duplicate events, and what happens when two requests race.

hasql-check

kronor-io/hasql-check

Checks the SQL in your hasql-th quotes against a live PostgreSQL schema.

hasql-th checks that a statement parses. hasql-check PREPAREs it, so a dropped column or a changed function signature fails in CI or in your editor instead of in production. Optional checks catch nullable columns decoded as non-null and casts that lose data.

git clone https://github.com/kronor-io/hasql-check
cd hasql-check && cabal install exe:hasql-check

hasql-check --nullability --types src/Billing/*.hs

sqitch-plan

kronor-io/sqitch-plan

A Haskell library to parse, query and render sqitch.plan files.

It covers the whole format, keeps line numbers, and renders a parsed plan back byte for byte. Queries answer the questions plan tooling asks: which changes come after a line, whether a change is reworked and at which tag. sqint uses it to find the changes after its baseline.

src  <- Text.IO.readFile "database/sqitch.plan"
plan <- either (fail . Text.unpack . Plan.renderParseError) pure (Plan.parsePlan src)
mapM_ (\c -> print (c.line, c.value.name, Plan.reworkTag c.value)) (Plan.changes plan)

Pin it from a cabal.project with a source-repository-package pointing at the repository.