packages feed

sqiff (empty) → 0.1.3.1

raw patch · 67 files changed

+13266/−0 lines, 67 filesdep +Diffdep +aesondep +base

Dependencies added: Diff, aeson, base, bytestring, containers, crypton, directory, file-embed, filepath, hasql, hasql-th-kronor, hedgehog, opt-env-conf, pqi-ffi, rio, sqiff, string-interpolate, tasty, tasty-expected-failure, tasty-golden, tasty-hedgehog, tasty-hunit, temporary, text, time, typed-process, vector, yaml

Files

+ LICENSE view
@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Kronor++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,499 @@+# sqiff++sqiff compares PostgreSQL schemas and writes the difference as [sqitch](https://sqitch.org) changes.++In a sqitch project, a table's deploy file says what the table *was* when it was first created. Every change after that is a migration someone wrote by hand: an `alter table`, a revert for it, the views that have to be dropped and created again around it, an index that has to be built concurrently in its own change. With sqiff you edit the `create table` file instead, as if you were writing the table today, and sqiff writes the migration that gets an existing database there:++```console+$ git diff deploy/public/table/orders.sql+-    amount integer not null,++    amount numeric(12,2) not null,++    status text not null default 'pending',+     created_at timestamptz not null default now()+ );++++create index if not exists orders_customer_email on public.orders (customer_email);++$ sqiff table deploy/public/table/orders.sql+-- public.orders.amount+--   dropped and created again around it+--     view public.daily_revenue++-- table column public.orders.amount+-- hazard: rewrites the table and its indexes+-- hazard: holds an ACCESS EXCLUSIVE lock, which blocks reads and writes, while it runs+-- hazard: fails when an existing value does not convert to the new type+-- hazard: recreating a view fails when its query relies on the old type; then edit the view+drop view public.daily_revenue;+alter table public.orders alter column amount type numeric(12,2) using amount::numeric(12,2);+create view public.daily_revenue as+SELECT (created_at)::date AS day,+    sum(amount) AS revenue+   FROM public.orders+  GROUP BY ((created_at)::date);++-- table column public.orders.status+alter table public.orders add column status text not null default 'pending'::text;++-- index public.orders_customer_email+-- outside a transaction+-- hazard: builds an index+do $$ ... $$;   -- stops if an earlier concurrent build left an invalid index+CREATE INDEX CONCURRENTLY orders_customer_email ON public.orders USING btree (customer_email);+```++Add `--write` and sqiff adds these as sqitch changes, with their reverts, and reworks the table's change so that the file you edited stays the one that creates the table.++What sqiff takes care of:++- **Dependents.** It finds the views, functions, constraints and policies that depend on what changes, drops and recreates them in order, and keeps their comments and grants.+- **Hazards.** Every step says what it costs: table rewrites, locks, lost data, casts that can fail, `not null` columns on tables with rows.+- **Safe defaults.** Indexes are built `concurrently`, outside a transaction and in a change of their own. Constraints are validated in their own transaction. Serial columns become identity columns without losing the sequence's value or grants.+- **Renames.** A dropped column and a new one of the same type might be a rename. sqiff asks you which instead of dropping data.+- **Reverts.** Each migration gets a revert script that undoes it, view recreation included.+- **Real catalogs.** sqiff reads both schemas from PostgreSQL itself rather than parsing SQL. Your edit is built in a transaction that is rolled back, so it is never left in the database.++sqiff is one of a set of tools for keeping a PostgreSQL schema in sqitch, with [sqint](https://github.com/kronor-io/sqint), [create-migration](https://github.com/kronor-io/sqitch-with-templates) and [psql-retry](https://github.com/kronor-io/psql-retry). [sqitchcraft](https://kronor-io.github.io/sqitchcraft/) shows how they fit together: the repository layout they assume, one change from an edited file to a deploy, and instructions for coding agents.++## Contents++1. [Install](#install)+2. [A walkthrough](#a-walkthrough)+   1. [Look at a database](#1-look-at-a-database)+   2. [Compare two databases](#2-compare-two-databases)+   3. [Get the SQL](#3-get-the-sql)+   4. [Write it as sqitch changes](#4-write-it-as-sqitch-changes)+   5. [Change a table by editing its file](#5-change-a-table-by-editing-its-file)+   6. [Renames](#6-renames)+   7. [When the database and the file disagree](#7-when-the-database-and-the-file-disagree)+   8. [Compare with master](#8-compare-with-master)+3. [Commands](#commands)+4. [Settings](#settings)+5. [Tests](#tests)++## Install++Install it from the flake. CI builds it for x86_64-linux, aarch64-linux and aarch64-darwin and pushes the builds to the `kronor-open` cachix cache, which the flake names, so nix downloads sqiff rather than building it once you accept the flake's settings.++```bash+nix run github:kronor-io/sqiff -- --help+```++```bash+nix profile install github:kronor-io/sqiff+```++Each version tag also publishes an image for amd64 and arm64, with sqitch, psql and git beside sqiff (but not docker, so `sqiff baseline` is not available in it):++```bash+docker run --rm -v "$PWD:/work" ghcr.io/kronor-io/sqiff --help+```++On Linux without nix, each [release](https://github.com/kronor-io/sqiff/releases) has a static binary for x86_64 and aarch64, which runs on any distribution. The tarball holds `bin/sqiff` and its bash, zsh and fish completions under `share/`, so unpacking it into `~/.local` (or `/usr/local`) installs both:++```bash+curl -fsSL "https://github.com/kronor-io/sqiff/releases/latest/download/sqiff-$(uname -m)-linux.tar.xz" | tar -xJ -C ~/.local+```++The binary is sqiff alone: install sqitch, psql and git (and docker for `--from master`) beside it.++In a clone, `nix build .#sqiff` puts the binary in `result/bin`, `nix build .#dockerImage` the image, and `scripts/build-static` the release tarball, in `dist-static/`. `nix develop` gives a shell with GHC, cabal, Postgres, sqitch and git, where `cabal build` and `cabal install` work with the dependency versions in `cabal.project.freeze`.++sqiff needs a reachable Postgres, given with `--db` (`--from` and `--to` for `diff`, `plan` and `sqitch`) or with libpq's `PG*` variables. It also runs `git` and `sqitch`, and `docker` for `--from master`.++The PL/pgSQL body checks need the [plpgsql_check](https://github.com/okbob/plpgsql_check) extension in the database. Without it, sqiff skips them and prints a note on stderr, which is left out of the examples below:++```console+sqiff: plpgsql_check is not installed; PL/pgSQL body dependencies are left out+```++## A walkthrough++The examples use a small shop database. Every output below is what sqiff printed for it.++```sql+create table public.orders (+    id bigint generated always as identity primary key,+    customer_email text not null,+    amount integer not null,+    created_at timestamptz not null default now()+);++create view public.daily_revenue as+    select created_at::date as day, sum(amount) as revenue+    from public.orders group by 1;+```++`shop_prod` has this schema. `shop_dev` has it with three changes: `amount` is `numeric(12,2)`, a `status` column is added, and an index is added on `customer_email`.++### 1. Look at a database++`describe` reads one database and counts its objects by kind:++```console+$ sqiff describe --db "dbname=shop_dev"+1	extension+1	index+3	schema+1	sequence+2	table+5	table column+1	table constraint+2	view+```++With `--out`, it writes one file per object, with grants and comments in files of their own. You can commit the folder and review a schema change as an ordinary git diff:++```console+$ sqiff describe --db "dbname=shop_dev" --out schema+$ find schema -type f | sort+schema/extension/plpgsql.sql+schema/index/public/orders_customer_email.sql+schema/schema/public.comment+schema/schema/public.privileges+schema/schema/public.sql+schema/sequence/public/orders_id_seq.privileges+schema/.sqiff+schema/table-column/public/orders/amount.sql+schema/table-column/public/orders/created_at.sql+schema/table-column/public/orders/customer_email.sql+schema/table-column/public/orders/id.sql+schema/table-column/public/orders/status.sql+schema/table-constraint/public/orders/orders_pkey.sql+schema/table/public/orders.privileges+schema/table/public/orders.sql+schema/view/public/daily_revenue.privileges+schema/view/public/daily_revenue.sql++$ cat schema/table-column/public/orders/amount.sql+type numeric(12,2)+not null+```++`--out` needs an empty or new folder. To refresh a folder that sqiff wrote earlier (the `.sqiff` file marks it), pass `--replace`.++### 2. Compare two databases++`diff` lists what turns `--from` into `--to`. Under each change it lists what depends on the changed object:++```console+$ sqiff diff --from "dbname=shop_prod" --to "dbname=shop_dev"+added   index public.orders_customer_email+changed table column public.orders.amount+  - type integer+  + type numeric(12,2)+  depended on by:+    view public.daily_revenue+added   table column public.orders.status+2 added, 0 dropped, 1 changed+```++It exits with code 1 when the databases differ and 0 when they match, so it can fail a CI job when a database has drifted from the schema in git:++```console+$ sqiff diff --from "dbname=shop_dev" --to "dbname=shop_dev"+0 added, 0 dropped, 0 changed+```++### 3. Get the SQL++`plan` prints the migration. Steps are ordered so that each one can run. Above each step, comments name the object and say how the step runs and what it can do to a live system:++```console+$ sqiff plan --from "dbname=shop_prod" --to "dbname=shop_dev"+-- table column public.orders.amount+-- hazard: may rewrite the table+-- hazard: holds an ACCESS EXCLUSIVE lock, which blocks reads and writes, while it runs+-- hazard: fails when an existing value does not convert to the new type+-- hazard: recreating a view fails when its query relies on the old type; then edit the view+drop view public.daily_revenue;+alter table public.orders alter column amount type numeric(12,2) using amount::numeric(12,2);+create view public.daily_revenue as+SELECT (created_at)::date AS day,+    sum(amount) AS revenue+   FROM public.orders+  GROUP BY ((created_at)::date);++-- table column public.orders.status+alter table public.orders add column status text not null default 'pending'::text;++-- index public.orders_customer_email+-- outside a transaction+-- hazard: builds an index+do $$+begin+    if exists (+        select from pg_index+        where indexrelid = to_regclass('public.orders_customer_email') and not indisvalid+    ) then+        raise exception using message = 'index public.orders_customer_email is invalid from an earlier failed build; drop it first';+    end if;+end+$$;++CREATE INDEX CONCURRENTLY orders_customer_email ON public.orders USING btree (customer_email);+```++Some things to notice:++- `daily_revenue` reads `amount`, so PostgreSQL would refuse to retype the column under it. sqiff drops the view and creates it again around the `alter`, with its comment.+- The index is built `CONCURRENTLY`, so writes to `orders` are not blocked while it builds. That cannot run inside a transaction, so it is marked `outside a transaction`. The `do` block stops a rerun from treating an invalid index left by an earlier failed build as done.+- Other cases have their own recipes. For example, a `serial` column that becomes an identity column keeps the sequence's current value and grants, and a `NOT VALID` constraint that becomes valid is validated in its own transaction. The fixtures in [`test/fixtures`](test/fixtures) show many more: each has `from.sql`, `to.sql` and the `diff` and `plan` sqiff prints for them.++### 4. Write it as sqitch changes++`sqitch` writes the plan into a sqitch project. Run it from the project's root. `--dry-run` lists the changes it would write:++```console+$ sqiff sqitch --from "dbname=shop_prod" --to "dbname=shop_dev" --dry-run+add	migrations/2026/11/2026-11-19-151823-alter-public.orders.amount-status	2 statements	migration: alter public.orders.amount-status+add	public/table/orders/index/orders_customer_email	1 statements	add_index: add index public.orders.orders_customer_email+```++Without `--dry-run`, sqiff calls `sqitch add` (or `sqitch rework`) for each change and fills in its deploy and revert scripts. The index gets a change of its own, because it has to run outside a transaction. sqiff checks the whole batch before writing anything, and if a write fails part-way, it leaves the project as it was. The change names come from the `names` patterns in [`sqiff.yaml`](#settings).++### 5. Change a table by editing its file++In everyday work you usually don't have a second database to compare with. You have the table's deploy file, and you want the table to look different. That is what `sqiff table` is for.++sqiff expects each table to have a deploy file of its own at `deploy/<schema>/table/<name>.sql` (the `names.table` pattern sets this). The file should use `create table if not exists` and `create index if not exists`. When sqiff reworks the change, sqitch runs the new file on databases that already have the table, and there it should do nothing:++```sql+-- deploy/public/table/orders.sql+BEGIN;++create table if not exists public.orders (+    id bigint generated always as identity primary key,+    customer_email text not null,+    amount integer not null,+    created_at timestamptz not null default now()+);++COMMIT;+```++**Step 1: edit the file.** On a branch, change the file to say what the table should be:++```sql+create table if not exists public.orders (+    id bigint generated always as identity primary key,+    customer_email text not null,+    amount numeric(12,2) not null,+    status text not null default 'pending',+    created_at timestamptz not null default now()+);++create index if not exists orders_customer_email on public.orders (customer_email);+```++**Step 2: see the migration.** `sqiff table` reads the file as it is on `master` (or `--base REV`). In one transaction that it rolls back, it builds the table from that version and from your edit, compares the two, and prints what it takes to get from one to the other. `--db` (or `PG*`) only needs to be a database with the project deployed. Nothing in it is changed:++```console+$ sqiff table deploy/public/table/orders.sql+-- public.orders.amount+--   dropped and created again around it+--     view public.daily_revenue++-- table column public.orders.amount+-- hazard: rewrites the table and its indexes+...+```++The output starts with what else the edit touches: here, the view that has to be recreated. When a dependent object would break and sqiff cannot recreate it, the output lists it and `--write` refuses, so that you change or drop the dependent first. With plpgsql_check installed, this also covers PL/pgSQL functions whose bodies use the table.++**Step 3: write it.** Run the same command with `--write`:++```console+$ sqiff table deploy/public/table/orders.sql --write+Created deploy/migrations/2026/11/2026-11-19-151805-alter-public.orders.amount-status.sql+Created revert/migrations/2026/11/2026-11-19-151805-alter-public.orders.amount-status.sql+Created verify/migrations/2026/11/2026-11-19-151805-alter-public.orders.amount-status.sql+Added "migrations/2026/11/2026-11-19-151805-alter-public.orders.amount-status" to ./sqitch.plan+Created deploy/public/table/orders/index/orders_customer_email.sql+...+Tagged "public/table/orders/index/orders_customer_email" with @2026-11-19_sqiff in ./sqitch.plan+Added "public/table/orders [public/table/orders@2026-11-19_sqiff]" to ./sqitch.plan.+...+added migrations/2026/11/2026-11-19-151805-alter-public.orders.amount-status+added public/table/orders/index/orders_customer_email+reworked public/table/orders+```++The plan now ends with:++```text+migrations/2026/11/2026-11-19-151805-alter-public.orders.amount-status   # migration: alter public.orders.amount-status+public/table/orders/index/orders_customer_email                         # add_index: add index public.orders.orders_customer_email+@2026-11-19_sqiff                                                       # sqiff: before the changes it writes+public/table/orders [public/table/orders@2026-11-19_sqiff]              # sqiff: public/table/orders as edited+```++- **The migration** alters existing databases. Its revert drops `status`, changes `amount` back to `integer` and recreates the view around that change too.+- **The index change** builds the index concurrently.+- **The rework of `public/table/orders`** keeps your edited file as the one that creates the table. On a new database it creates the table as it is now. On an existing one, `if not exists` makes it do nothing, because the migrations before it have already done the work.++**Step 4: deploy as usual.**++```console+$ sqitch deploy+Deploying changes to db:pg:shop+  + migrations/2026/11/2026-11-19-151805-alter-public.orders.amount-status .. ok+  + public/table/orders/index/orders_customer_email @2026-11-19_sqiff ....... ok+  + public/table/orders ..................................................... NOTICE:  relation "orders" already exists, skipping+NOTICE:  relation "orders_customer_email" already exists, skipping+ok+```++The two notices are the `if not exists` guards at work: the migrations before the rework have already brought the table up to date.++`sqitch revert` takes the table back to `integer` without `status`.++If you edit the file again on the same branch, run `sqiff table` again. It treats the changes the branch already added for this table as done, and moves the rework after the new migration.++### 6. Renames++From the file alone, a renamed column looks the same as a dropped column and a new column of the same type. sqiff says so, and without your answer it does not write anything that drops data:++```console+$ sqiff table deploy/public/table/orders.sql      # customer_email renamed to email+-- customer_email is dropped and email added with the same type; pass --rename customer_email:email if it is a rename, or --drop-and-add if it is not++-- table column public.orders.customer_email+-- hazard: deletes data+alter table public.orders drop column customer_email;+...++$ sqiff table deploy/public/table/orders.sql --write+sqiff: a column is dropped and another added with the same type; say whether it is a rename with --rename or --drop-and-add++$ sqiff table deploy/public/table/orders.sql --rename customer_email:email+-- table column public.orders.email+-- hazard: breaks running code that still uses the old name+alter table public.orders rename column customer_email to email;+```++Repeat `--rename OLD:NEW` for each renamed column. `rename-hint` in `sqiff.yaml` adds your team's advice to the rename warning, for example how to rename in two deploys.++### 7. When the database and the file disagree++Sometimes a database has drifted from the file: someone added a column by hand, or a migration was never folded back into the file. There are two ways to deal with it.++**Compare with the live table** instead of the file on `master`. sqiff then also shows what is in the database but not in the file. It leaves those things alone unless you pass `--allow-drops`:++```console+$ psql -c "alter table public.orders add column note text"+$ sqiff table deploy/public/table/orders.sql --against-database+-- left alone: table column public.orders.note: in the database but not in the file; --allow-drops drops it+-- the file matches the table+```++**Rewrite the file from the table**, so that the file says what the database already has:++```console+$ sqiff table deploy/public/table/orders.sql --rewrite-file+-- Deploy shop:public/table/orders to pg++BEGIN;++create table if not exists public.orders (+    id bigint generated always as identity primary key,+    customer_email text not null,+    amount integer not null,+    created_at timestamptz not null default now(),+    note text+);++COMMIT;+```++The rewrite keeps the file's text wherever it already matches the table, and changes only what differs. With `--write`, sqiff writes the file and reworks the change. `--live-from CONNINFO` reads the table, read-only, from another database, such as a production replica. sqiff refuses if that database has not yet deployed planned changes that touch the table, because the rewrite would undo them.++### 8. Compare with master++`diff`, `plan` and `sqitch` can build the `--from` side themselves. `--from master`, or `--from rev:REV`, checks out that revision and deploys its sqitch plan into a scratch Postgres started with Docker Compose. sqiff then compares that database with `--to`:++```bash+sqiff diff --from master --to "dbname=app_dev"+```++That answers "what does my dev database have that master's plan does not?". sqiff keeps the scratch database and updates it on later runs. Each repository gets its own, shared by its worktrees and jj workspaces, under `~/.cache/sqiff`. The `baseline` section of [`sqiff.yaml`](#settings) says how to start it.++## Commands++Run every command from the root of the sqitch project, where `sqitch.conf` and `sqiff.yaml` are. `table` and `sqitch` also take `--project DIR`.++| Command | What it does |+| --- | --- |+| `sqiff describe [--db C] [--out DIR [--replace]]` | Count one database's objects, or write one file per object. |+| `sqiff diff --from C\|master\|rev:REV [--to C]` | List what differs and what depends on it. Exits 1 when something differs. |+| `sqiff plan --from … [--to C]` | Print the SQL that turns `--from` into `--to`. |+| `sqiff sqitch --from … [--to C] [--dry-run] [--tag NAME]` | Write that SQL as sqitch changes. |+| `sqiff table FILE [--db C]` | Print the migration for an edited table deploy file. |+| `sqiff table FILE --write` | Add that migration with sqitch and rework the table's change. |+| `sqiff table FILE --rename OLD:NEW` / `--drop-and-add` | Say whether a dropped and added column is a rename. |+| `sqiff table FILE --against-database [--allow-drops]` | Compare with the live table instead of the file at `--base`. |+| `sqiff table FILE --rewrite-file [--live-from C] [--write]` | Rewrite the file to create the table as the database has it. |++`diff`, `plan`, `sqitch` and `describe` also take `--exclude-schema SCHEMA` (repeatable), `--include-partitions` and `--no-body-check`. `sqiff COMMAND --help` lists every option.++Exit codes: 0 when the command succeeds, 1 when `diff` finds differences (or `--rewrite-file` leaves some), and 2 when there is an error, with a one-line `sqiff: …` message on stderr.++## Settings++**Databases.** `--db`, `--from` and `--to` take a libpq connection string. When `--db` or `--to` is left out, libpq's environment names the database: `PGHOST`, `PGPORT`, `PGUSER`, `PGDATABASE`, or `PGSERVICE` with a service file.++**sqitch layout.** The top directory and plan file come from `sqitch config` (`core.top_dir`, `core.plan_file`); `--top-dir` and `--plan-file` override them.++**`sqiff.yaml`**, next to `sqitch.conf`, holds the rest. Every key is optional; an unknown key is an error.++```yaml+exclude-schemas: [audit]             # left out of every comparison+rename-hint: "..."                   # added to the warning on a column rename+templates: sqitch/templates          # sqitch templates for new changes: add_column, add_index, validate_constraint, migration++names:                               # change names; the defaults are shown+  table: "{schema}/table/{name}"+  function: "{schema}/function/{name}"+  view: "{schema}/view/{name}"+  trigger: "{schema}/trigger/{table}/{name}"+  index: "{schema}/table/{table}/index/{name}"+  type: "{schema}/type/{name}"+  migration: "migrations/{stamp}-{slug}"+  migration-stamp: "%Y/%m/%Y-%m-%d-%H%M%S"++baseline:                            # the scratch database --from master builds+  compose-file: docker-compose.yaml  # read from the revision's checkout+  service: postgres+  port-variable: PG_PORT             # the compose file's variable for the published port+  port: 0                            # 0 lets Docker pick a free port+  container-port: 5432+  environment: {}                    # more variables for docker compose+  user: postgres+  database: postgres+  password-variable: PG_PASSWORD     # or password: ...; left out, trust auth, PGPASSWORD or ~/.pgpass+  sqitch: host                       # host, or service to run sqitch inside the service+  deploy:                            # sqitch calls that deploy the revision+    - sqitch: [deploy]+      if-exists: sqitch.plan         # skip the call when this path is missing+  status: [status]                   # the sqitch call that finds changes the plan no longer has+```++In `deploy` and `status` arguments, `{host}`, `{port}`, `{user}` and `{database}` are where that sqitch reaches the baseline: the port Docker published when sqitch runs on the host, `container-port` when it runs in the service. sqitch reads `PGHOST` and `PGPORT` only for what a target's URI leaves out, so a target with a fixed URI needs one, for example:++```yaml+  deploy:+    - sqitch: [deploy, "db:pg://{user}@{host}:{port}/{database}"]+  status: [status, "db:pg://{user}@{host}:{port}/{database}"]+```++The password reaches sqitch as `PGPASSWORD` and sqiff's own connections in the connection string; it is never put in sqitch's arguments.++With `templates`, `--write` adds a change that adds a column, adds an index or validates a constraint from the matching template, passing `schema`, `table_name` and `column_name`, `index_name` or `constraint_name`; other new migrations use `migration`. In `add_column`, sqiff puts the column's type and options where `__your_type_here__ null` is, and it expects `add_index` to name the index `idx_<table_name>_<index_name>`. create-migration's templates already fit, so `templates` can point at them. Without `templates`, `--write` uses sqitch's own templates and writes the scripts itself.++## Tests++```bash+cabal test+```++The unit tests are pure. The integration tests start a throwaway PostgreSQL cluster (`initdb` from `PATH`, or the directory in `SQIFF_TEST_PG_BIN`), and for each directory under `test/fixtures` they build `from.sql` and `to.sql` and compare `sqiff diff` and `sqiff plan` with the golden files. They then apply the plan to `from` and expect `diff` to find nothing left, and do the same through `sqitch deploy`, verify and revert (`sqitch` from `PATH`, or the directory in `SQIFF_TEST_SQITCH_BIN`). A `known-bug` file marks a fixture that fails today, and a `revert-gap` file one whose changes PostgreSQL cannot fully revert; each says why. Refresh golden files with `cabal test --test-options=--accept`.
+ app/Sqiff.hs view
@@ -0,0 +1,45 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++module Sqiff (main) where++import Data.String.Interpolate (i)+import Data.Text.IO qualified as TIO+import RIO+import Sqiff.App.Compare (runDescribe, runDiff, runPlan, runSqitch)+import Sqiff.App.Env (loadAppEnv)+import Sqiff.App.Options (Command (..), DescribeOptions (..), SqitchOptions (..), parseCommand)+import Sqiff.App.Table (tableCommand)+import Sqiff.Connection (UserError (..))+import Sqiff.Sqitch (requireSqitch)+++-- | Runs the command the arguments name. A 'UserError' is one line on stderr and exit+-- code 2, as is any other failure; 'ExitCode' passes through.+main :: IO ()+main =+    handleAny unexpected+        . handle userError+        $ parseCommand+        >>= \case+            Describe opts -> do+                env <- loadAppEnv "." opts.scope+                runRIO env (runDescribe opts)+            Diff from toDb scope -> do+                env <- loadAppEnv "." scope+                runRIO env (runDiff from toDb)+            Plan from toDb scope -> do+                env <- loadAppEnv "." scope+                runRIO env (runPlan from toDb)+            Sqitch from toDb scope opts -> do+                requireSqitch+                env <- loadAppEnv opts.projectDir scope+                runRIO env (runSqitch from toDb opts)+            TableFile file db opts -> tableCommand file db opts+  where+    userError (UserError message) = TIO.hPutStrLn stderr [i|sqiff: #{message}|] >> exitWith (ExitFailure 2)+    unexpected e = case fromException e of+        Just code -> throwIO (code :: ExitCode)+        Nothing -> TIO.hPutStrLn stderr [i|sqiff: #{displayException e}|] >> exitWith (ExitFailure 2)
+ sqiff.cabal view
@@ -0,0 +1,169 @@+cabal-version:      3.0+name:               sqiff+version:            0.1.3.1+synopsis:           Describe and diff PostgreSQL schemas from their catalogs+description:+  sqiff compares PostgreSQL schemas and writes the difference as sqitch+  changes. Edit a table's create table file as if writing the table today,+  and sqiff writes the migration, revert and verify scripts that get an+  existing database there, with the dependent views and functions and the+  hazards each statement brings.++category:           Database+homepage:           https://github.com/kronor-io/sqiff+bug-reports:        https://github.com/kronor-io/sqiff/issues+license:            MIT+license-file:       LICENSE+author:             José Lorenzo Rodríguez+maintainer:         lorenzo@kronor.io+copyright:          2026 Kronor+tested-with:        GHC ==9.12.4+build-type:         Simple+extra-doc-files:    README.md+extra-source-files:+  sql/depend.sql+  sql/depend_from.sql+  sql/depend_on.sql+  sql/describe/*.sql+  sql/plpgsql/*.sql++source-repository head+  type:     git+  location: https://github.com/kronor-io/sqiff++common shared+  default-language:   GHC2021+  default-extensions:+    BlockArguments+    StrictData+    DerivingStrategies+    LambdaCase++  -- The warnings docs/readability.md relies on fail the build; the rest of -Wall+  -- stays advice.+  ghc-options:+    -Wall+    -Werror=missing-signatures+    -Werror=missing-fields+    -Werror=incomplete-patterns+    -Werror=incomplete-uni-patterns+    -Werror=incomplete-record-updates+    -Werror=incomplete-record-selectors++library+  import:          shared+  hs-source-dirs:  src+  exposed-modules:+    Sqiff.App.Compare+    Sqiff.App.Dependents+    Sqiff.App.Env+    Sqiff.App.Options+    Sqiff.App.Read+    Sqiff.App.Table+    Sqiff.App.Table.Env+    Sqiff.App.Table.Findings+    Sqiff.App.Table.Rewrite+    Sqiff.Baseline+    Sqiff.Body+    Sqiff.Catalog+    Sqiff.Catalog.PlpgsqlCheck+    Sqiff.Catalog.Rows+    Sqiff.Config+    Sqiff.Connection+    Sqiff.ConnectionString+    Sqiff.Definition+    Sqiff.Dependencies+    Sqiff.Diff+    Sqiff.Folder+    Sqiff.Git+    Sqiff.Graph+    Sqiff.Identifier+    Sqiff.Model+    Sqiff.Plan+    Sqiff.Recipe+    Sqiff.Recreate+    Sqiff.Rewrite+    Sqiff.Script+    Sqiff.Sql+    Sqiff.Sqitch+    Sqiff.Sqitch.Check+    Sqiff.Sqitch.Layout+    Sqiff.Sqitch.Plan+    Sqiff.Sqitch.Units+    Sqiff.TableEdit+    Sqiff.Timing++  -- The version above, for sqiff --version.+  other-modules:   Paths_sqiff+  autogen-modules: Paths_sqiff+  build-depends:+    , aeson              ^>=2.3.1.0+    , base               >=4.21 && <5+    , bytestring         ^>=0.12.2.0+    , containers         ^>=0.7+    , crypton            ^>=1.1.4+    , Diff               ^>=1.0.2+    , file-embed         ^>=0.0.16.0+    , filepath           ^>=1.5.5.0+    , hasql              ^>=2.0.1.0+    , hasql-th-kronor    ^>=0.5.1.1+    , opt-env-conf       ^>=0.15.0.2+    , pqi-ffi            ^>=1.0.1.0+    , rio                ^>=0.1.25.0+    , string-interpolate ^>=1.0.0.0+    , text               ^>=2.1.4+    , time               ^>=1.14+    , typed-process      ^>=0.2.13.0+    , vector             ^>=0.13.2.0+    , yaml               ^>=0.11.11.2++executable sqiff+  import:         shared+  hs-source-dirs: app+  main-is:        Sqiff.hs+  ghc-options:+    -main-is Sqiff.main -threaded -rtsopts -with-rtsopts=-N4++  build-depends:+    , base+    , rio+    , sqiff+    , string-interpolate+    , text++test-suite sqiff-test+  import:             shared+  type:               exitcode-stdio-1.0+  hs-source-dirs:     test+  main-is:            Main.hs+  other-modules:+    Integration+    Postgres+    Rewriting+    Unit+    Writing++  ghc-options:        -threaded -rtsopts -with-rtsopts=-N4+  build-tool-depends: sqiff:sqiff+  build-depends:+    , aeson+    , base+    , bytestring+    , containers+    , directory+    , filepath+    , hasql+    , hasql-th-kronor+    , hedgehog+    , rio+    , sqiff+    , string-interpolate+    , tasty+    , tasty-expected-failure+    , tasty-golden+    , tasty-hedgehog+    , tasty-hunit+    , temporary+    , text+    , time+    , typed-process
+ sql/depend.sql view
@@ -0,0 +1,58 @@+-- Edges between the objects in $1, $2 and $3 (class, object and sub-object ids), as one+-- row of arrays. View rules, column defaults, table row types and arrays of either stand+-- for the view, column, table or element type they belong to. A view's columns stand for+-- the view.+with remap (classid, objid, toclassid, toobjid, tosubid) as (+    select 'pg_rewrite'::regclass::oid, rw.oid, 'pg_class'::regclass::oid, rw.ev_class, 0+    from pg_rewrite rw+    union all+    select 'pg_attrdef'::regclass::oid, ad.oid, 'pg_class'::regclass::oid, ad.adrelid, ad.adnum::int+    from pg_attrdef ad+    union all+    select 'pg_type'::regclass::oid, t.oid, 'pg_class'::regclass::oid, k.oid, 0+    from pg_type t+    join pg_class k on k.oid = t.typrelid and k.relkind <> 'c'+    union all+    select+        'pg_type'::regclass::oid,+        ta.oid,+        case when k.oid is not null then 'pg_class'::regclass::oid else 'pg_type'::regclass::oid end,+        coalesce(k.oid, ta.typelem),+        0+    from pg_type ta+    left join pg_type te on te.oid = ta.typelem+    left join pg_class k on k.oid = te.typrelid and k.relkind <> 'c'+    where ta.typcategory = 'A'+        and ta.typelem <> 0+),+edge as (+    select distinct+        coalesce(ma.toclassid, d.classid) as classid,+        coalesce(ma.toobjid, d.objid) as objid,+        coalesce(ma.tosubid, d.objsubid) as objsubid,+        coalesce(mb.toclassid, d.refclassid) as refclassid,+        coalesce(mb.toobjid, d.refobjid) as refobjid,+        case when rk.relkind in ('v', 'm') then 0 else coalesce(mb.tosubid, d.refobjsubid) end as refobjsubid+    from pg_depend d+    left join remap ma on ma.classid = d.classid and ma.objid = d.objid+    left join remap mb on mb.classid = d.refclassid and mb.objid = d.refobjid+    left join pg_class rk on d.refclassid = 'pg_class'::regclass and rk.oid = d.refobjid+    where d.deptype in ('n', 'a', 'i')+        and d.objid >= 16384+        and d.refobjid >= 16384+),+described as (+    select k.classid::oid, k.objid::oid, k.objsubid+    from unnest($1::int8[], $2::int8[], $3::int4[]) as k (classid, objid, objsubid)+)+select+    coalesce(array_agg(e.classid::int8), '{}'),+    coalesce(array_agg(e.objid::int8), '{}'),+    coalesce(array_agg(e.objsubid::int4), '{}'),+    coalesce(array_agg(e.refclassid::int8), '{}'),+    coalesce(array_agg(e.refobjid::int8), '{}'),+    coalesce(array_agg(e.refobjsubid::int4), '{}')+from edge e+where (e.classid, e.objid, e.objsubid) is distinct from (e.refclassid, e.refobjid, e.refobjsubid)+    and exists (select from described k where k.classid = e.classid and k.objid = e.objid and k.objsubid = e.objsubid)+    and exists (select from described k where k.classid = e.refclassid and k.objid = e.refobjid and k.objsubid = e.refobjsubid)
+ sql/depend_from.sql view
@@ -0,0 +1,126 @@+-- Like depend.sql, limited to the edges reachable from $1, $2 and $3: those whose+-- referenced end is one of them or, repeatedly, the dependent end of such an edge.+-- Each step finds the pg_depend rows that reference an object through the reference+-- index, directly or through the view rules, column defaults and types that stand for+-- it. From a relation it also steps to its columns, which views and constraints depend+-- on instead of the relation; those steps are not edges. It also follows objects that+-- are not described; the caller drops their edges. A view's columns stand for the view.+with recursive+-- The starts, then every step, as (dependent, referenced, whether it is an edge); a start+-- has no referenced end.+step (classid, objid, objsubid, refclassid, refobjid, refobjsubid, edge) as (+    select s.classid::oid, s.objid::oid, s.objsubid, null::oid, null::oid, null::int4, false+    from unnest($1::int8[], $2::int8[], $3::int4[]) as s (classid, objid, objsubid)+    union+    select x.classid, x.objid, x.objsubid, p.classid, p.objid, p.objsubid, x.edge+    from step p+    cross join lateral (+        select 'pg_class'::regclass::oid as classid, a.attrelid as objid, a.attnum::int4 as objsubid, false as edge+        from pg_attribute a+        where p.classid = 'pg_class'::regclass and p.objsubid = 0 and a.attrelid = p.objid and a.attnum > 0 and not a.attisdropped+        union all+        select e.classid, e.objid, e.objsubid, true+        from (+            -- What stands for p: p itself, its view rules, its column's default, its row type+            -- and that type's array, or its array type.+            select p.classid as classid, p.objid as objid+            union all+            select 'pg_rewrite'::regclass::oid, rw.oid+            from pg_rewrite rw+            where p.classid = 'pg_class'::regclass and p.objsubid = 0 and rw.ev_class = p.objid+            union all+            select 'pg_attrdef'::regclass::oid, ad.oid+            from pg_attrdef ad+            where p.classid = 'pg_class'::regclass and p.objsubid > 0 and ad.adrelid = p.objid and ad.adnum = p.objsubid+            union all+            select 'pg_type'::regclass::oid, t.oid+            from pg_class k+            join pg_type rt on rt.oid = k.reltype+            cross join lateral (values (rt.oid), (rt.typarray)) t (oid)+            where p.classid = 'pg_class'::regclass and p.objsubid = 0 and k.oid = p.objid and k.relkind <> 'c' and t.oid <> 0+            union all+            select 'pg_type'::regclass::oid, te.typarray+            from pg_type te+            where p.classid = 'pg_type'::regclass and te.oid = p.objid and te.typarray <> 0+        ) r+        -- Looked up per object that stands for p, through the reference index. As a plain+        -- join the planner may scan every pg_depend row for each p instead, which grows+        -- with the catalog at every step; offset 0 keeps the subquery, and so this order.+        cross join lateral (+            select d0.classid, d0.objid, d0.objsubid, d0.refclassid, d0.refobjid, d0.refobjsubid, d0.deptype+            from pg_depend d0+            where d0.refclassid = r.classid and d0.refobjid = r.objid+            offset 0+        ) d+        -- The dependent and referenced ends after the same remap as depend.sql.+        cross join lateral (+            select coalesce(ma.toclassid, d.classid) as classid, coalesce(ma.toobjid, d.objid) as objid, coalesce(ma.tosubid, d.objsubid) as objsubid+            from (select) one+            left join lateral (+                select 'pg_class'::regclass::oid as toclassid, rw.ev_class as toobjid, 0 as tosubid+                from pg_rewrite rw+                where d.classid = 'pg_rewrite'::regclass and rw.oid = d.objid+                union all+                select 'pg_class'::regclass::oid, ad.adrelid, ad.adnum::int+                from pg_attrdef ad+                where d.classid = 'pg_attrdef'::regclass and ad.oid = d.objid+                union all+                select 'pg_class'::regclass::oid, k.oid, 0+                from pg_type t+                join pg_class k on k.oid = t.typrelid and k.relkind <> 'c'+                where d.classid = 'pg_type'::regclass and t.oid = d.objid+                union all+                select+                    case when k.oid is not null then 'pg_class'::regclass::oid else 'pg_type'::regclass::oid end,+                    coalesce(k.oid, ta.typelem),+                    0+                from pg_type ta+                left join pg_type te on te.oid = ta.typelem+                left join pg_class k on k.oid = te.typrelid and k.relkind <> 'c'+                where d.classid = 'pg_type'::regclass and ta.oid = d.objid and ta.typcategory = 'A' and ta.typelem <> 0+            ) ma on true+        ) e+        cross join lateral (+            select coalesce(mb.toclassid, d.refclassid) as classid, coalesce(mb.toobjid, d.refobjid) as objid, coalesce(mb.tosubid, d.refobjsubid) as objsubid+            from (select) one+            left join lateral (+                select 'pg_class'::regclass::oid as toclassid, rw.ev_class as toobjid, 0 as tosubid+                from pg_rewrite rw+                where d.refclassid = 'pg_rewrite'::regclass and rw.oid = d.refobjid+                union all+                select 'pg_class'::regclass::oid, ad.adrelid, ad.adnum::int+                from pg_attrdef ad+                where d.refclassid = 'pg_attrdef'::regclass and ad.oid = d.refobjid+                union all+                select 'pg_class'::regclass::oid, k.oid, 0+                from pg_type t+                join pg_class k on k.oid = t.typrelid and k.relkind <> 'c'+                where d.refclassid = 'pg_type'::regclass and t.oid = d.refobjid+                union all+                select+                    case when k.oid is not null then 'pg_class'::regclass::oid else 'pg_type'::regclass::oid end,+                    coalesce(k.oid, ta.typelem),+                    0+                from pg_type ta+                left join pg_type te on te.oid = ta.typelem+                left join pg_class k on k.oid = te.typrelid and k.relkind <> 'c'+                where d.refclassid = 'pg_type'::regclass and ta.oid = d.refobjid and ta.typcategory = 'A' and ta.typelem <> 0+            ) mb on true+        ) f+        where d.deptype in ('n', 'a', 'i')+            and d.objid >= 16384+            and d.refobjid >= 16384+            and (f.classid, f.objid, f.objsubid) = (p.classid, p.objid, p.objsubid)+            and (e.classid, e.objid, e.objsubid) <> (f.classid, f.objid, f.objsubid)+    ) x+)+select+    coalesce(array_agg(s.classid::int8), '{}'),+    coalesce(array_agg(s.objid::int8), '{}'),+    coalesce(array_agg(s.objsubid::int4), '{}'),+    coalesce(array_agg(s.refclassid::int8), '{}'),+    coalesce(array_agg(s.refobjid::int8), '{}'),+    coalesce(array_agg(case when k.relkind in ('v', 'm') then 0 else s.refobjsubid end::int4), '{}')+from step s+left join pg_class k on s.refclassid = 'pg_class'::regclass and k.oid = s.refobjid+where s.edge
+ sql/depend_on.sql view
@@ -0,0 +1,64 @@+-- Like depend.sql, for the pg_depend rows that reference one of $1, $2 and $3, or a view+-- rule, column default or type that stands for one. The caller keeps the edges whose+-- referenced end is a target and whose ends are both described: done here, those checks+-- compare every edge with every target, as the planner cannot tell how many the arrays+-- hold.+with remap (classid, objid, toclassid, toobjid, tosubid) as (+    select 'pg_rewrite'::regclass::oid, rw.oid, 'pg_class'::regclass::oid, rw.ev_class, 0+    from pg_rewrite rw+    union all+    select 'pg_attrdef'::regclass::oid, ad.oid, 'pg_class'::regclass::oid, ad.adrelid, ad.adnum::int+    from pg_attrdef ad+    union all+    select 'pg_type'::regclass::oid, t.oid, 'pg_class'::regclass::oid, k.oid, 0+    from pg_type t+    join pg_class k on k.oid = t.typrelid and k.relkind <> 'c'+    union all+    select+        'pg_type'::regclass::oid,+        ta.oid,+        case when k.oid is not null then 'pg_class'::regclass::oid else 'pg_type'::regclass::oid end,+        coalesce(k.oid, ta.typelem),+        0+    from pg_type ta+    left join pg_type te on te.oid = ta.typelem+    left join pg_class k on k.oid = te.typrelid and k.relkind <> 'c'+    where ta.typcategory = 'A'+        and ta.typelem <> 0+),+target as (+    select k.classid::oid, k.objid::oid, k.objsubid+    from unnest($1::int8[], $2::int8[], $3::int4[]) as k (classid, objid, objsubid)+),+referenced as (+    select t.classid, t.objid from target t+    union+    select m.classid, m.objid+    from remap m+    join target t on t.classid = m.toclassid and t.objid = m.toobjid+),+edge as (+    select distinct+        coalesce(ma.toclassid, d.classid) as classid,+        coalesce(ma.toobjid, d.objid) as objid,+        coalesce(ma.tosubid, d.objsubid) as objsubid,+        coalesce(mb.toclassid, d.refclassid) as refclassid,+        coalesce(mb.toobjid, d.refobjid) as refobjid,+        coalesce(mb.tosubid, d.refobjsubid) as refobjsubid+    from referenced r+    join pg_depend d on d.refclassid = r.classid and d.refobjid = r.objid+    left join remap ma on ma.classid = d.classid and ma.objid = d.objid+    left join remap mb on mb.classid = d.refclassid and mb.objid = d.refobjid+    where d.deptype in ('n', 'a', 'i')+        and d.objid >= 16384+        and d.refobjid >= 16384+)+select+    coalesce(array_agg(e.classid::int8), '{}'),+    coalesce(array_agg(e.objid::int8), '{}'),+    coalesce(array_agg(e.objsubid::int4), '{}'),+    coalesce(array_agg(e.refclassid::int8), '{}'),+    coalesce(array_agg(e.refobjid::int8), '{}'),+    coalesce(array_agg(e.refobjsubid::int4), '{}')+from edge e+where (e.classid, e.objid, e.objsubid) is distinct from (e.refclassid, e.refobjid, e.refobjsubid)
+ sql/describe/column.sql view
@@ -0,0 +1,95 @@+select+    'pg_class'::regclass::oid as classid,+    a.attrelid as objid,+    a.attnum::int as objsubid,+    a.attrelid as relid,+    jsonb_build_object(+        'position', a.attnum,+        -- Only there because a parent table has it.+        'inherited', not a.attislocal,+        'type', format_type(a.atttypid, a.atttypmod),+        -- The schema is left out for pg_catalog, where the built-in collations are. Looked+        -- up only for the columns that need it: as a join the planner may compare every+        -- column with every collation.+        'collation', case when a.attcollation <> t.typcollation then (+            select jsonb_build_object('schema', nullif(con.nspname, 'pg_catalog'), 'name', co.collname)+            from pg_collation co+            join pg_namespace con on con.oid = co.collnamespace+            where co.oid = a.attcollation+        ) end,+        'not_null', case+            when nn.oid is not null then jsonb_build_object(+                'validated', nn.convalidated,+                -- The name, unless it is the one PostgreSQL gives a not-null constraint.+                'name', case+                    when nn.conname ~ '_not_null[0-9]*$'+                        and (+                            starts_with(nn.conname, c.relname || '_')+                            -- PostgreSQL shortens the table and column names to fit a default name in 63 bytes.+                            or (+                                octet_length(nn.conname) = 63+                                and exists (+                                    select+                                    from generate_series(1, length(c.relname)) k+                                    cross join lateral (select regexp_replace(nn.conname, '_not_null[0-9]*$', '') as stem) s+                                    where length(s.stem) - k - 1 between 1 and length(a.attname)+                                        and left(c.relname, k) || '_' || left(a.attname, length(s.stem) - k - 1) = s.stem+                                )+                            )+                        )+                        then null+                    else nn.conname+                end+            )+        end,+        'identity', case a.attidentity+            when 'a' then 'always'+            when 'd' then 'by default'+        end,+        -- The identity sequence's options that differ from the defaults.+        'identity_options', case when a.attidentity <> '' then (+            select to_jsonb(array_remove(array[+                case when s.seqincrement <> 1 then 'increment by ' || s.seqincrement end,+                case when s.seqmin <> 1 then 'minvalue ' || s.seqmin end,+                case+                    when s.seqmax <> case s.seqtypid when 'int2'::regtype then 32767 when 'int4'::regtype then 2147483647 else 9223372036854775807 end+                        then 'maxvalue ' || s.seqmax+                end,+                case when s.seqstart <> s.seqmin then 'start with ' || s.seqstart end,+                case when s.seqcache <> 1 then 'cache ' || s.seqcache end,+                case when s.seqcycle then 'cycle' end+            ], null))+            from pg_depend d+            join pg_sequence s on s.seqrelid = d.objid+            where d.classid = 'pg_class'::regclass+                and d.refclassid = 'pg_class'::regclass+                and d.refobjid = a.attrelid+                and d.refobjsubid = a.attnum+                and d.deptype = 'i'+        ) end,+        'generated', case a.attgenerated+            when 's' then 'stored'+            when 'v' then 'virtual'+        end,+        -- The generation expression, or the default.+        'expression', pg_get_expr(ad.adbin, ad.adrelid),+        'rewrites_on_add', exists (+                select+                from regexp_matches(pg_get_expr(ad.adbin, ad.adrelid), '([[:alpha:]_][[:alnum:]_$]*)\(', 'g') m+                join pg_proc p on p.proname = m[1]+                where a.attgenerated = '' and p.provolatile = 'v'+            )+            or (t.typtype = 'd' and exists (select from pg_constraint dc where dc.contypid = a.atttypid))+    )::text as definition+from pg_attribute a+join pg_class c on c.oid = a.attrelid+join pg_namespace n on n.oid = c.relnamespace+join pg_type t on t.oid = a.atttypid+left join pg_attrdef ad on ad.adrelid = a.attrelid and ad.adnum = a.attnum+left join pg_constraint nn on nn.conrelid = a.attrelid and nn.contype = 'n' and nn.conkey = array[a.attnum]+where a.attnum > 0+    and not a.attisdropped+    and c.relkind in ('r', 'p')+    and ($2 or not c.relispartition)+    and n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'
+ sql/describe/comment.sql view
@@ -0,0 +1,41 @@+select+    d.classoid as classid,+    d.objoid as objid,+    d.objsubid,+    coalesce(i.indrelid, c.oid, nullif(k.conrelid, 0), t.tgrelid, p.polrelid) as relid,+    d.description as definition+from pg_description d+left join pg_class c on d.classoid = 'pg_class'::regclass and c.oid = d.objoid+left join pg_index i on i.indexrelid = c.oid+left join pg_constraint k on d.classoid = 'pg_constraint'::regclass and k.oid = d.objoid+left join pg_trigger t on d.classoid = 'pg_trigger'::regclass and t.oid = d.objoid+left join pg_policy p on d.classoid = 'pg_policy'::regclass and p.oid = d.objoid+left join pg_proc f on d.classoid = 'pg_proc'::regclass and f.oid = d.objoid+left join pg_type y on d.classoid = 'pg_type'::regclass and y.oid = d.objoid+left join pg_namespace s on d.classoid = 'pg_namespace'::regclass and s.oid = d.objoid+left join pg_class r on r.oid = coalesce(i.indrelid, c.oid, nullif(k.conrelid, 0), t.tgrelid, p.polrelid)+join pg_namespace n on n.oid = coalesce(r.relnamespace, f.pronamespace, y.typnamespace, k.connamespace, s.oid)+where d.classoid in (+        'pg_class'::regclass,+        'pg_constraint'::regclass,+        'pg_trigger'::regclass,+        'pg_policy'::regclass,+        'pg_proc'::regclass,+        'pg_type'::regclass,+        'pg_namespace'::regclass+    )+    and n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'+    and not (y.oid is not null and y.typrelid <> 0 and y.typtype = 'c' and exists (select from pg_class x where x.oid = y.typrelid and x.relkind <> 'c'))+    -- For one table ($3), only the comments that can belong to it, found by index.+    and ($3::text is null or d.objoid in (+        select to_regclass($3::text)::oid+        union all+        select ix.indexrelid from pg_index ix where ix.indrelid = to_regclass($3::text)+        union all+        select ck.oid from pg_constraint ck where ck.conrelid = to_regclass($3::text)+        union all+        select tg.oid from pg_trigger tg where tg.tgrelid = to_regclass($3::text)+        union all+        select po.oid from pg_policy po where po.polrelid = to_regclass($3::text)+    ))
+ sql/describe/constraint.sql view
@@ -0,0 +1,42 @@+select+    'pg_constraint'::regclass::oid as classid,+    con.oid as objid,+    0 as objsubid,+    nullif(con.conrelid, 0) as relid,+    jsonb_build_object(+        'clause', pg_get_constraintdef(con.oid),+        'kind', con.contype,+        'validated', con.convalidated,+        'inherited', not con.conislocal,+        'columns', (+            select jsonb_agg(a.attname order by k.n)+            from unnest(con.conkey) with ordinality k (attnum, n)+            join pg_attribute a on a.attrelid = con.conrelid and a.attnum = k.attnum+        ),+        'references', case+            when con.contype = 'f' then (+                select jsonb_build_object(+                    'schema', rn.nspname,+                    'table', rc.relname,+                    'columns', (+                        select jsonb_agg(a.attname order by k.n)+                        from unnest(con.confkey) with ordinality k (attnum, n)+                        join pg_attribute a on a.attrelid = con.confrelid and a.attnum = k.attnum+                    )+                )+                from pg_class rc+                join pg_namespace rn on rn.oid = rc.relnamespace+                where rc.oid = con.confrelid+            )+        end+    )::text as definition+from pg_constraint con+join pg_namespace n on n.oid = con.connamespace+left join pg_class tc on tc.oid = con.conrelid+where con.contype not in ('n', 't')+    and ($2 or not coalesce(tc.relispartition, false))+    and con.conparentid = 0+    and n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'+    -- For one table ($3), only its constraints, found by index.+    and ($3::text is null or con.conrelid = to_regclass($3::text))
+ sql/describe/extension.sql view
@@ -0,0 +1,10 @@+select+    'pg_extension'::regclass::oid as classid,+    e.oid as objid,+    0 as objsubid,+    null::oid as relid,+    jsonb_build_object(+        'version', e.extversion,+        'schema', (select n.nspname from pg_namespace n where n.oid = e.extnamespace)+    )::text as definition+from pg_extension e
+ sql/describe/function.sql view
@@ -0,0 +1,37 @@+select+    'pg_proc'::regclass::oid as classid,+    p.oid as objid,+    0 as objsubid,+    null::oid as relid,+    case+        when p.prokind = 'a' then (+            select concat_ws(+                E'\n',+                'aggregate kind ' || a.aggkind::text || ' direct args ' || a.aggnumdirectargs,+                'sfunc ' || a.aggtransfn::text,+                'stype ' || format_type(a.aggtranstype, null),+                'sspace ' || nullif(a.aggtransspace, 0),+                'finalfunc ' || nullif(a.aggfinalfn::oid, 0)::regproc::text,+                case when a.aggfinalextra then 'finalfunc_extra' end,+                'finalfunc_modify ' || a.aggfinalmodify::text,+                'combinefunc ' || nullif(a.aggcombinefn::oid, 0)::regproc::text,+                'serialfunc ' || nullif(a.aggserialfn::oid, 0)::regproc::text,+                'deserialfunc ' || nullif(a.aggdeserialfn::oid, 0)::regproc::text,+                'initcond ' || quote_literal(a.agginitval),+                'msfunc ' || nullif(a.aggmtransfn::oid, 0)::regproc::text,+                'minvfunc ' || nullif(a.aggminvtransfn::oid, 0)::regproc::text,+                'mstype ' || nullif(a.aggmtranstype, 0)::regtype::text,+                'mfinalfunc ' || nullif(a.aggmfinalfn::oid, 0)::regproc::text,+                'minitcond ' || quote_literal(a.aggminitval),+                'sortop ' || nullif(a.aggsortop, 0)::regoperator::text,+                'parallel ' || p.proparallel::text+            )+            from pg_aggregate a+            where a.aggfnoid = p.oid+        )+        else pg_get_functiondef(p.oid)+    end as definition+from pg_proc p+join pg_namespace n on n.oid = p.pronamespace+where n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'
+ sql/describe/index.sql view
@@ -0,0 +1,29 @@+select+    'pg_class'::regclass::oid as classid,+    i.indexrelid as objid,+    0 as objsubid,+    i.indrelid as relid,+    jsonb_build_object(+        'statement', pg_get_indexdef(i.indexrelid),+        'table_schema', tn.nspname,+        'table_name', tc.relname,+        'unique', i.indisunique,+        'partitioned', c.relkind = 'I'+    )::text as definition+from pg_index i+join pg_class c on c.oid = i.indexrelid+join pg_class tc on tc.oid = i.indrelid+join pg_namespace tn on tn.oid = tc.relnamespace+join pg_namespace n on n.oid = c.relnamespace+where n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'+    and ($2 or not tc.relispartition)+    and not exists (+        select+        from pg_depend d+        where d.classid = 'pg_class'::regclass+            and d.objid = i.indexrelid+            and d.refclassid = 'pg_constraint'::regclass+            and d.deptype = 'i'+    )+    and not exists (select from pg_inherits h where h.inhrelid = i.indexrelid)
+ sql/describe/policy.sql view
@@ -0,0 +1,30 @@+select+    'pg_policy'::regclass::oid as classid,+    p.oid as objid,+    0 as objsubid,+    p.polrelid as relid,+    concat_ws(+        E'\n',+        case when p.polpermissive then 'as permissive' else 'as restrictive' end,+        'for ' || case p.polcmd+            when 'r' then 'select'+            when 'a' then 'insert'+            when 'w' then 'update'+            when 'd' then 'delete'+            else 'all'+        end,+        'to ' || (+            select string_agg(r.name, ', ' order by r.name)+            from (+                select case when role = 0 then 'public' else quote_ident(pg_get_userbyid(role)) end as name+                from unnest(p.polroles) role+            ) r+        ),+        'using (' || pg_get_expr(p.polqual, p.polrelid) || ')',+        'with check (' || pg_get_expr(p.polwithcheck, p.polrelid) || ')'+    ) as definition+from pg_policy p+join pg_class c on c.oid = p.polrelid+join pg_namespace n on n.oid = c.relnamespace+where n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'
+ sql/describe/privileges.sql view
@@ -0,0 +1,45 @@+with acl as (+    select 'pg_class'::regclass::oid as classid, c.oid as objid, c.relacl as acl, c.relowner as owner+    from pg_class c+    join pg_namespace n on n.oid = c.relnamespace+    where c.relkind in ('r', 'p', 'v', 'm', 'S')+        and ($2 or not c.relispartition)+        and n.nspname <> 'information_schema'+        and n.nspname !~ '^pg_'+    union all+    select 'pg_proc'::regclass::oid, p.oid, p.proacl, p.proowner+    from pg_proc p+    join pg_namespace n on n.oid = p.pronamespace+    where n.nspname <> 'information_schema'+        and n.nspname !~ '^pg_'+    union all+    select 'pg_namespace'::regclass::oid, n.oid, n.nspacl, n.nspowner+    from pg_namespace n+    where n.nspname <> 'information_schema'+        and n.nspname !~ '^pg_'+)+select+    acl.classid,+    acl.objid,+    0 as objsubid,+    case when acl.classid = 'pg_class'::regclass then acl.objid end as relid,+    -- JSON null for the defaults, else every grant, the owner's included.+    case+        when acl.acl is null then 'null'+        else coalesce(+            (+                select jsonb_agg(+                    jsonb_build_object(+                        'grantee', case when x.grantee = 0 then null else pg_get_userbyid(x.grantee) end,+                        'privilege', x.privilege_type,+                        'grantable', x.is_grantable,+                        -- Null when the owner granted it, so owners need not match.+                        'grantor', case when x.grantor = acl.owner then null else pg_get_userbyid(x.grantor) end+                    )+                )+                from aclexplode(acl.acl) x+            ),+            '[]'::jsonb+        )::text+    end as definition+from acl
+ sql/describe/relation.sql view
@@ -0,0 +1,51 @@+select+    'pg_class'::regclass::oid as classid,+    c.oid as objid,+    0 as objsubid,+    c.oid as relid,+    case+        when c.relkind in ('v', 'm') then+            jsonb_build_object(+                'kind', 'view',+                'options', c.reloptions,+                'query', pg_get_viewdef(c.oid),+                'columns', (+                    select coalesce(jsonb_agg(jsonb_build_array(a.attname, format_type(a.atttypid, a.atttypmod)) order by a.attnum), '[]')+                    from pg_attribute a+                    where a.attrelid = c.oid and a.attnum > 0 and not a.attisdropped+                )+            )+        else jsonb_build_object(+            'kind', 'table',+            'unlogged', c.relpersistence = 'u',+            'partition_by', case when c.relkind = 'p' then pg_get_partkeydef(c.oid) end,+            'partition_of', case+                when c.relispartition then (+                    select jsonb_build_object('schema', pn.nspname, 'name', p.relname, 'bound', pg_get_expr(c.relpartbound, c.oid))+                    from pg_inherits h+                    join pg_class p on p.oid = h.inhparent+                    join pg_namespace pn on pn.oid = p.relnamespace+                    where h.inhrelid = c.oid+                )+            end,+            -- Parents by inherits, not by partitioning, in order.+            'inherits', (+                select coalesce(jsonb_agg(jsonb_build_object('schema', pn.nspname, 'name', p.relname) order by h.inhseqno), '[]')+                from pg_inherits h+                join pg_class p on p.oid = h.inhparent+                join pg_namespace pn on pn.oid = p.relnamespace+                where h.inhrelid = c.oid and not c.relispartition+            ),+            'row_security', c.relrowsecurity,+            'force_row_security', c.relforcerowsecurity,+            -- The table's storage options, then its TOAST table's with a toast. prefix.+            'options', coalesce(c.reloptions, '{}') || array(select 'toast.' || o from unnest(toast.reloptions) o)+        )+    end::text as definition+from pg_class c+join pg_namespace n on n.oid = c.relnamespace+left join pg_class toast on toast.oid = c.reltoastrelid+where c.relkind in ('r', 'p', 'v', 'm')+    and ($2 or not c.relispartition)+    and n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'
+ sql/describe/schema.sql view
@@ -0,0 +1,9 @@+select+    'pg_namespace'::regclass::oid as classid,+    n.oid as objid,+    0 as objsubid,+    null::oid as relid,+    '' as definition+from pg_namespace n+where n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'
+ sql/describe/sequence.sql view
@@ -0,0 +1,38 @@+select+    'pg_class'::regclass::oid as classid,+    s.seqrelid as objid,+    0 as objsubid,+    s.seqrelid as relid,+    jsonb_build_object(+        'type', format_type(s.seqtypid, null),+        'increment', s.seqincrement,+        'min', s.seqmin,+        'max', s.seqmax,+        'start', s.seqstart,+        'cache', s.seqcache,+        'cycle', s.seqcycle,+        -- The column whose drop takes the sequence with it.+        'owned_by', (+            select jsonb_build_object('schema', rn.nspname, 'table', rc.relname, 'column', ra.attname)+            from pg_depend d+            join pg_class rc on rc.oid = d.refobjid+            join pg_namespace rn on rn.oid = rc.relnamespace+            join pg_attribute ra on ra.attrelid = d.refobjid and ra.attnum = d.refobjsubid+            where d.classid = 'pg_class'::regclass+                and d.objid = s.seqrelid+                and d.refclassid = 'pg_class'::regclass+                and d.deptype = 'a'+        )+    )::text as definition+from pg_sequence s+join pg_class c on c.oid = s.seqrelid+join pg_namespace n on n.oid = c.relnamespace+where n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'+    and not exists (+        select+        from pg_depend d+        where d.classid = 'pg_class'::regclass+            and d.objid = s.seqrelid+            and d.deptype = 'i'+    )
+ sql/describe/trigger.sql view
@@ -0,0 +1,20 @@+select+    'pg_trigger'::regclass::oid as classid,+    t.oid as objid,+    0 as objsubid,+    t.tgrelid as relid,+    pg_get_triggerdef(t.oid)+        || case t.tgenabled+            when 'D' then E';\nALTER TABLE ' || t.tgrelid::regclass::text || ' DISABLE TRIGGER ' || quote_ident(t.tgname)+            when 'R' then E';\nALTER TABLE ' || t.tgrelid::regclass::text || ' ENABLE REPLICA TRIGGER ' || quote_ident(t.tgname)+            when 'A' then E';\nALTER TABLE ' || t.tgrelid::regclass::text || ' ENABLE ALWAYS TRIGGER ' || quote_ident(t.tgname)+            else ''+        end as definition+from pg_trigger t+join pg_class c on c.oid = t.tgrelid+join pg_namespace n on n.oid = c.relnamespace+where not t.tgisinternal+    and ($2 or not c.relispartition)+    and t.tgparentid = 0+    and n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'
+ sql/describe/type.sql view
@@ -0,0 +1,59 @@+select+    'pg_type'::regclass::oid as classid,+    t.oid as objid,+    0 as objsubid,+    null::oid as relid,+    case t.typtype+        when 'e' then jsonb_build_object(+            'kind', 'enum',+            'labels', (+                select jsonb_agg(e.enumlabel order by e.enumsortorder)+                from pg_enum e+                where e.enumtypid = t.oid+            )+        )+        when 'd' then jsonb_build_object(+            'kind', 'domain',+            'base', format_type(t.typbasetype, t.typtypmod),+            'not_null', t.typnotnull,+            'default', t.typdefault+        )+        when 'c' then jsonb_build_object(+            'kind', 'composite',+            'attributes', (+                select jsonb_agg(jsonb_build_array(a.attname, format_type(a.atttypid, a.atttypmod)) order by a.attnum)+                from pg_attribute a+                where a.attrelid = t.typrelid+                    and a.attnum > 0+                    and not a.attisdropped+            )+        )+        when 'r' then jsonb_build_object(+            'kind', 'range',+            'subtype', (select format_type(r.rngsubtype, null) from pg_range r where r.rngtypid = t.oid),+            -- Every option create type ... as range takes, in its order, the defaults left out.+            'options', (+                select (select jsonb_agg(o) from jsonb_array_elements(jsonb_build_array(+                    jsonb_build_array('subtype', format_type(r.rngsubtype, null)),+                    case when not opc.opcdefault then jsonb_build_array('subtype_opclass', quote_ident(opn.nspname) || '.' || quote_ident(opc.opcname)) end,+                    case when r.rngcollation <> 0 and r.rngcollation <> st.typcollation then jsonb_build_array('collation', quote_ident(cn.nspname) || '.' || quote_ident(co.collname)) end,+                    case when r.rngcanonical <> 0 then jsonb_build_array('canonical', r.rngcanonical::regproc::text) end,+                    case when r.rngsubdiff <> 0 then jsonb_build_array('subtype_diff', r.rngsubdiff::regproc::text) end,+                    jsonb_build_array('multirange_type_name', format_type(r.rngmultitypid, null))+                )) o where o <> 'null'::jsonb)+                from pg_range r+                join pg_type st on st.oid = r.rngsubtype+                join pg_opclass opc on opc.oid = r.rngsubopc+                join pg_namespace opn on opn.oid = opc.opcnamespace+                left join pg_collation co on co.oid = r.rngcollation+                left join pg_namespace cn on cn.oid = co.collnamespace+                where r.rngtypid = t.oid+            )+        )+    end::text as definition+from pg_type t+join pg_namespace n on n.oid = t.typnamespace+where t.typtype in ('e', 'd', 'c', 'r')+    and (t.typtype <> 'c' or exists (select from pg_class k where k.oid = t.typrelid and k.relkind = 'c'))+    and n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'
+ sql/plpgsql/depend.sql view
@@ -0,0 +1,29 @@+-- What the bodies of the functions in $1 use, as plpgsql_check's static analysis sees it,+-- as (function, class id, object id). $2 holds each function's trigger table, null for+-- other functions. @extschema@ is replaced with plpgsql_check's schema.+with f as (+    select u.oid::oid as oid, u.relid::oid as relid+    from unnest($1::int8[], $2::int8[]) u(oid, relid)+)+select distinct f.oid::int8, k.classid::int8, d.oid::int8+from f+cross join lateral (+    select d.type, d.oid+    from @extschema@.plpgsql_show_dependency_tb(f.oid::regprocedure) d+    where f.relid is null+    union all+    select d.type, d.oid+    from @extschema@.plpgsql_show_dependency_tb(f.oid::regprocedure, f.relid::regclass) d+    where f.relid is not null+) d+cross join lateral (+    select case d.type+        when 'RELATION' then 'pg_class'::regclass::oid+        when 'FUNCTION' then 'pg_proc'::regclass::oid+        when 'OPERATOR' then 'pg_operator'::regclass::oid+        when 'TYPE' then 'pg_type'::regclass::oid+    end as classid+) k+where k.classid is not null+    and d.oid >= 16384+    and (k.classid, d.oid) <> ('pg_proc'::regclass::oid, f.oid)
+ sql/plpgsql/functions.sql view
@@ -0,0 +1,44 @@+-- PL/pgSQL functions and procedures the describe queries cover. A trigger function gets+-- a table one of its triggers is on; plpgsql_check needs one to analyse its body. The+-- last column estimates how long the analysis takes: plpgsql_check plans each query, and+-- planning a query on a partitioned table opens every partition, so it counts the+-- partitions of the partitioned tables the body names.+with partitions as materialized (+    select c.relname::text as relname, count(*) as n+    from pg_class c+    join pg_inherits h on h.inhparent = c.oid+    where c.relkind = 'p'+    group by c.relname+    having count(*) >= 100+)+select+    p.oid::int8,+    p.oid::regprocedure::text,+    p.prorettype = 'trigger'::regtype,+    t.tgrelid::int8,+    e.cost::int8+from pg_proc p+join pg_language l on l.oid = p.prolang+join pg_namespace n on n.oid = p.pronamespace+left join (+    select distinct on (g.tgfoid) g.tgfoid, g.tgrelid+    from pg_trigger g+    order by g.tgfoid, g.oid+) t on t.tgfoid = p.oid+cross join lateral (+    select coalesce(sum(partitions.n), 0) as cost+    from partitions, (select p.prosrc || '' as src) b+    where strpos(b.src, partitions.relname) > 0+) e+where l.lanname = 'plpgsql'+    and n.nspname <> 'information_schema'+    and n.nspname !~ '^pg_'+    and not n.nspname = any($1)+    and not exists (+        select+        from pg_depend e+        where e.deptype = 'e'+            and e.classid = 'pg_proc'::regclass+            and e.objid = p.oid+    )+order by p.oid
+ sql/plpgsql/temp_tables.sql view
@@ -0,0 +1,59 @@+-- Creates, in this session, the temp tables PL/pgSQL functions create, so plpgsql_check+-- can analyse the statements that use them. plpgsql_make_pragma describes the ones a+-- function's own statements create, when it can plan their queries; a query on a temp+-- table another statement or a caller creates plans once that table exists, so this+-- repeats until no new table appears. It warns, whatever client_min_messages says, for+-- each table that already exists, so a function is described only while none of the+-- tables it creates do. The statements that made them are appended to the setting+-- sqiff.temp_tables. @extschema@ is replaced with plpgsql_check's schema; before+-- 2.10 this does nothing.+set client_min_messages = error;+do $$+declare+    f regprocedure;+    created text[];+    pragma text;+    name text;+    ddl text;+    added int;+    rounds int := 0;+begin+    if to_regprocedure('@extschema@.plpgsql_make_pragma(regprocedure, regclass, boolean)') is null then+        return;+    end if;+    loop+        added := 0;+        rounds := rounds + 1;+        for f, created in+            select p.oid::regprocedure, array(+                select t.m[1]+                from regexp_matches(p.prosrc, 'create\s+(?:temp|temporary)\s+table\s+(?:if\s+not\s+exists\s+)?([a-z_][a-z0-9_$]*)', 'gi') t(m)+            )+            from pg_proc p+            join pg_language l on l.oid = p.prolang+            join pg_namespace n on n.oid = p.pronamespace+            where l.lanname = 'plpgsql'+                and p.prorettype <> 'trigger'::regtype+                and n.nspname <> 'information_schema'+                and n.nspname !~ '^pg_'+                and p.prosrc ~* 'create\s+(temp|temporary)\s+table'+        loop+            continue when exists (select from unnest(created) c where to_regclass(c) is not null);+            begin+                for pragma in select m from @extschema@.plpgsql_make_pragma(f, fatal_errors => false) m loop+                    name := substring(pragma from '^table:\s*([^(]+?)\s*\(');+                    if name is not null and to_regclass(name) is null then+                        ddl := format('create temp table %s %s', name, substring(pragma from '^table:\s*[^(]+(\(.*\))\s*$'));+                        execute ddl;+                        perform set_config('sqiff.temp_tables', coalesce(current_setting('sqiff.temp_tables', true), '') || ddl || E';\n', false);+                        added := added + 1;+                    end if;+                end loop;+            exception when others then+                null;+            end;+        end loop;+        exit when added = 0 or rounds >= 10;+    end loop;+end+$$
+ src/Sqiff/App/Compare.hs view
@@ -0,0 +1,180 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | The commands that compare whole databases: describe one, list what differs between+-- two, print the migration, or write it as sqitch changes.+module Sqiff.App.Compare (+    runDescribe,+    runDiff,+    runPlan,+    runSqitch,+    report,+    summary,+) where++import Data.Algorithm.Diff (PolyDiff (..), getDiff)+import Data.String.Interpolate (i)+import Data.Time (getCurrentTime)+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.App.Env (AppEnv (..), Scope (..), Source, say)+import Sqiff.App.Options (DescribeOptions (..), SqitchOptions (..))+import Sqiff.App.Read (ComparisonInputs (..), Purpose (..), SchemaSnapshot (..), describeConnections, readBoth)+import Sqiff.Body (BodyCheck, sameDefinition)+import Sqiff.Catalog (describeOn)+import Sqiff.Config (Config (..))+import Sqiff.Connection (failWith, withConnections, withSharedSnapshot)+import Sqiff.ConnectionString (ConnectionString)+import Sqiff.Definition (Definition, printed)+import Sqiff.Dependencies (Dependencies)+import Sqiff.Diff (Change (..), Changes, affected, diff)+import Sqiff.Folder (writeFolder)+import Sqiff.Model+import Sqiff.Plan (context, cycleMessage, invert, planWith, renderStep)+import Sqiff.Recipe (Step)+import Sqiff.Recreate (withViewsAround, withViewsReplaced)+import Sqiff.Sqitch (withProject, writeUnits)+import Sqiff.Sqitch.Check (Tagging (..), batchProblems)+import Sqiff.Sqitch.Layout (findLayout, planPath)+import Sqiff.Sqitch.Plan (readPlan)+import Sqiff.Sqitch.Units (Unit (..), UnitKind (..), units)+import Sqiff.Timing (measure, timed)+++-- | Writes one file per object to @--out@, or counts the objects by kind.+runDescribe :: DescribeOptions -> RIO AppEnv ()+runDescribe opts = do+    scope <- asks (.scope)+    schema <- timed "describe.describeOn" $ withConnections opts.db describeConnections \conns ->+        liftIO (fst <$> withSharedSnapshot conns (describeOn (toList conns) scope.excluded scope.partitions Nothing))+    case opts.out of+        Just dir -> liftIO (writeFolder opts.existing dir schema)+        Nothing ->+            for_ (Map.toList (Map.fromListWith (+) [((toAddress k.object).objectType, 1 :: Int) | k <- Map.keys schema])) \(kind, n) ->+                say [i|#{n}\t#{kind}|]+++-- | Lists what differs, with what depends on it; exits 1 when something does.+runDiff :: Source -> ConnectionString -> RIO AppEnv ()+runDiff from toDb = do+    inputs <- timed "readBoth" $ readBoth from toDb ForDiff+    let fromSchema = inputs.source.schema+        deps = inputs.source.dependencies+        changes = diff (sameDefinition inputs.bodyChecks) fromSchema inputs.target.schema+        known = Set.fromList [k.object | k <- Map.keys fromSchema, k.aspect == Definition]+        affectedBy = affected known deps changes+        dependentsOf key = case key.aspect of+            Definition -> Map.findWithDefault Set.empty key.object affectedBy+            _ -> Set.empty+    measure "diff.diffAndAffected" (Map.size changes + Map.foldl' (\n s -> n + Set.size s) 0 affectedBy)+    -- In catalog order: by aspect, then kind and names as the catalog spells them.+    for_ (L.sortOn (\(key, _) -> (key.aspect, toAddress key.object)) (Map.toList changes)) \(key, change) ->+        report key change (dependentsOf key)+    say (summary changes)+    unless (Map.null changes) $ exitWith (ExitFailure 1)+++-- | Prints the migration's steps.+runPlan :: Source -> ConnectionString -> RIO AppEnv ()+runPlan from toDb = do+    planned <- planBoth from toDb+    measure "plan.planRender" (T.length (T.unlines (map renderStep planned.steps)))+    for_ planned.steps (say . renderStep)+++-- | Writes the migration as sqitch changes, or lists them with @--dry-run@.+runSqitch :: Source -> ConnectionString -> SqitchOptions -> RIO AppEnv ()+runSqitch from toDb opts = do+    config <- asks (.config)+    layout <- liftIO (findLayout opts.projectDir opts.topDir opts.planFile)+    sqitchPlan <- liftIO (readPlan (planPath layout))+    planned <- planBoth from toDb+    now <- liftIO getCurrentTime+    let inverse = Map.map invert planned.changes+        -- A retype's views are the same on both sides, so its revert recreates them+        -- around the column as the plan does.+        inverseCtx =+            withViewsReplaced planned.fromSchema planned.toDeps inverse+                . withViewsAround planned.fromSchema planned.fromDeps planned.changes+                $ context Map.empty planned.toSchema planned.fromSchema planned.toDeps inverse+        written = units config.names (const True) inverseCtx planned.changes sqitchPlan now planned.steps+        tagging = Tagging{given = opts.tag, now}+    measure "sqitch.planUnits" (sum [length u.deploy + length u.revert | u <- written])+    if opts.dryRun+        then for_ written \u -> do+            let kind = case u.kind of AddChange -> "add" :: Text; ReworkChange -> "rework"+                count = length u.deploy+                changeName = u.changeName+                unitNote = u.note+            say [i|#{kind}\t#{changeName}\t#{count} statements\t#{unitNote}|]+        else liftIO (withProject layout \project -> writeUnits project config.templates sqitchPlan tagging written)+    -- A dry run reports what would stop the write, too.+    case batchProblems sqitchPlan written of+        problems@(_ : _) | opts.dryRun -> failWith (T.intercalate "; " problems)+        _ -> pure ()+++-- | Both databases, what differs and the steps that migrate it.+data Planned = Planned+    { fromSchema :: Schema+    , fromDeps :: Dependencies+    , toSchema :: Schema+    , toDeps :: Dependencies+    , changes :: Changes+    , steps :: [Step]+    }+++planBoth :: Source -> ConnectionString -> RIO AppEnv Planned+planBoth from toDb = do+    inputs <- timed "readBoth" $ readBoth from toDb ForPlan+    let SchemaSnapshot{schema = fromSchema, dependencies = fromDeps} = inputs.source+        SchemaSnapshot{schema = toSchema, dependencies = toDeps} = inputs.target+        checks = inputs.bodyChecks+        changes = diff (sameDefinition checks) fromSchema toSchema+        adjust = withViewsReplaced toSchema fromDeps changes . withViewsAround fromSchema fromDeps changes+    steps <- either (failWith . cycleMessage) pure (planWith adjust (checks :: Map ObjectKey BodyCheck) fromSchema toSchema fromDeps toDeps changes)+    pure Planned{fromSchema, fromDeps, toSchema, toDeps, changes, steps}+++report :: MonadIO m => ObjectKey -> Change Definition -> Set ObjectId -> m ()+report key change dependents = do+    let name = render key.object+    say [i|#{verb} #{name}#{suffix}|]+    case change of+        Changed old new ->+            for_ (getDiff (T.lines (printed old)) (T.lines (printed new))) \case+                First line -> say [i|  - #{line}|]+                Second line -> say [i|  + #{line}|]+                Both _ _ -> pure ()+        _ -> pure ()+    unless (Set.null dependents) do+        say "  depended on by:"+        for_ (L.sortOn toAddress (Set.toList dependents)) \addr -> say [i|    #{render addr}|]+  where+    verb :: Text+    verb = case change of+        Added _ -> "added  "+        Dropped _ -> "dropped"+        Changed _ _ -> "changed"+    suffix :: Text+    suffix = case key.aspect of+        Definition -> ""+        Privileges -> " (privileges)"+        Comment -> " (comment)"+++summary :: Changes -> Text+summary changes = [i|#{count isAdded} added, #{count isDropped} dropped, #{count isChanged} changed|]+  where+    count p = L.length (filter p (Map.elems changes))+    isAdded = \case Added _ -> True; _ -> False+    isDropped = \case Dropped _ -> True; _ -> False+    isChanged = \case Changed _ _ -> True; _ -> False
+ src/Sqiff/App/Dependents.hs view
@@ -0,0 +1,109 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What depends on an edit's dropped or changed objects, in the database it runs on.+module Sqiff.App.Dependents (+    Dependents (..),+    exactDependentsOf,+    routinesNaming,+    dependentsScope,+    dependentsIn,+) where++import RIO+import RIO.HashSet qualified as HS+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.App.Env (BodyChecks (..), Scope (..), note)+import Sqiff.App.Read (Connected (..), reachableEdges)+import Sqiff.Catalog (Partitions (..), relationColumns)+import Sqiff.Dependencies (Dependencies, indexEdges, noDependencies)+import Sqiff.Diff (BodyText (..), Change (..), Changes, affected)+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Timing (measure, timed)+++data Dependents = Dependents+    { exact :: Map ObjectId (Set ObjectId)+    -- ^ For each object the edit drops or changes, what depends on it, directly or not,+    -- by @pg_depend@ and by the PL/pgSQL bodies plpgsql_check reads.+    , named :: Map ObjectId (Set ObjectId)+    -- ^ For each such object, the routines whose bodies name it, which the catalog does+    -- not track.+    , dbSchema :: Schema+    , dbDeps :: Dependencies+    , dbTempTables :: IO (Maybe Text)+    -- ^ The statements that make plpgsql_check's temp tables there.+    }+++-- | How 'dependentsIn' describes the database, leaving out @excluded@ schemas.+dependentsScope :: [Text] -> Scope+dependentsScope excluded = Scope{excluded, partitions = SkipPartitions, bodyCheck = SkipBodyChecks}+++-- | What depends on @object@, by @pg_depend@ and PL/pgSQL bodies.+exactDependentsOf :: ObjectId -> Dependents -> Set ObjectId+-- [allow:SqiffNamedQueries] this is the query's definition+exactDependentsOf object deps = Map.findWithDefault Set.empty object deps.exact+++-- | The routines whose bodies name @object@.+routinesNaming :: ObjectId -> Dependents -> Set ObjectId+-- [allow:SqiffNamedQueries] this is the query's definition+routinesNaming object deps = Map.findWithDefault Set.empty object deps.named+++-- | For each dropped or changed definition, its dependents by @pg_depend@ and PL/pgSQL+-- bodies, and the other functions whose text names it. @described@ is the database, as+-- 'dependentsScope' reads it, with its functions' words; it is only asked for when+-- something is dropped or changed.+dependentsIn :: [Text] -> IO (Connected, Map ObjectId BodyText) -> Changes -> IO Dependents+dependentsIn excluded described changes+    | Set.null starts = pure Dependents{exact = Map.empty, named = Map.empty, dbSchema = Map.empty, dbDeps = noDependencies, dbTempTables = pure Nothing}+    | otherwise = do+        (connected, split_) <- timed "deps.describeDatabase" described+        (edges, notes) <- timed "deps.reachableEdges" $ reachableEdges "--db" (dependentsScope excluded) starts connected (pure split_)+        for_ notes note+        let schema = connected.schema+            known = Set.fromList [k.object | k <- Map.keys schema, k.aspect == Definition]+            deps = indexEdges edges+            exact = affected known deps changes+            viewsOf object = [v | a <- Set.toList (Map.findWithDefault Set.empty object exact), isView a, Just v <- [isRelation a]]+        measure "deps.affected" (Map.foldl' (\n s -> n + Set.size s) (0 :: Int) exact)+        viewColumns <- timed "deps.relationColumns" $ relationColumns connected.conn (Set.toList (Set.fromList (concatMap viewsOf (Set.toList starts))))+        let routines = Map.toList split_+            skip = Set.fromList (map (.object) (Map.keys changes)) <> fold exact+            lower = T.toLower . nameText+            throughViews column object =+                [ lower v.schema : lower v.name : [lower c | Just c <- [column], keepsName c]+                | v <- viewsOf object+                , let keepsName c = c `Set.member` Map.findWithDefault Set.empty v viewColumns+                ]+            -- The words a function body must contain to use the object: a column by its+            -- table and name, a dropped relation by its name, and both through views.+            named object = case object of+                Column t c -> [lower t.name, lower c] : throughViews (Just c) object+                _ | Just q <- isRelation object, droppedHere object -> [lower q.name] : throughViews Nothing object+                _ -> []+            textual =+                Map.filter (not . Set.null)+                    $ Map.fromList+                        [ (addr, Set.fromList [r | (r, body) <- routines, any (all (`HS.member` body.wordSet)) wordSets, r `Set.notMember` skip])+                        | addr <- Set.toList starts+                        , let wordSets = named addr+                        , not (null wordSets)+                        ]+        measure "deps.textMatch" (Map.foldl' (\n s -> n + Set.size s) (0 :: Int) textual)+        pure Dependents{exact, named = textual, dbSchema = schema, dbDeps = deps, dbTempTables = connected.tempTableScript}+  where+    droppedHere object = case Map.lookup (definitionKey object) changes of+        Just (Dropped _) -> True+        _ -> False+    starts = Set.fromList [k.object | (k, c) <- Map.toList changes, k.aspect == Definition, removesOrChanges c]+    removesOrChanges = \case Added _ -> False; _ -> True
+ src/Sqiff/App/Env.hs view
@@ -0,0 +1,74 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What every command runs with: the project's configuration and what to read of the+-- databases, and where its output goes.+module Sqiff.App.Env (+    AppEnv (..),+    loadAppEnv,+    Scope (..),+    BodyChecks (..),+    Source (..),+    source,+    say,+    note,+) where++import Data.Text.IO qualified as TIO+import RIO+import RIO.Text qualified as T+import Sqiff.Catalog (Partitions (..))+import Sqiff.Config (Config (..), loadConfig)+import Sqiff.ConnectionString (ConnectionString, connectionString)+++data AppEnv = AppEnv+    { config :: Config+    , scope :: Scope+    -- ^ With the configuration's excluded schemas.+    }+++-- | The project's configuration in @root@, and @scope@ with the schemas it excludes.+loadAppEnv :: FilePath -> Scope -> IO AppEnv+loadAppEnv root scope = do+    config <- loadConfig root+    pure AppEnv{config, scope = scope{excluded = config.excludeSchemas <> scope.excluded}}+++-- | What a command reads of a database.+data Scope = Scope+    { excluded :: [Text]+    , partitions :: Partitions+    , bodyCheck :: BodyChecks+    }+++-- | Whether SQL-standard function bodies are recreated on @--to@ to compare them.+data BodyChecks = CheckBodies | SkipBodyChecks+    deriving stock (Eq)+++-- | What @--from@ names: a connection string, or the baseline database built from a revision.+data Source+    = Database ConnectionString+    | BaselineAt Text+++source :: Text -> Source+source s+    | s == "master" = BaselineAt s+    | Just rev <- T.stripPrefix "rev:" s = BaselineAt rev+    | otherwise = Database (connectionString s)+++-- | A line of the command's output.+say :: MonadIO m => Text -> m ()+say = liftIO . TIO.putStrLn+++-- | A line on stderr, beside the output.+note :: MonadIO m => Text -> m ()+note = liftIO . TIO.hPutStrLn stderr
+ src/Sqiff/App/Options.hs view
@@ -0,0 +1,234 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | The command line, parsed into a 'Command' whose options all apply: flags that make no+-- sense together are refused before anything runs.+module Sqiff.App.Options (+    Command (..),+    DescribeOptions (..),+    SqitchOptions (..),+    TableOptions (..),+    TableMode (..),+    MigrateOptions (..),+    Comparison (..),+    renamesOf,+    Output (..),+    SameTypeSwap (..),+    TableFlags (..),+    tableOptions,+    parseCommand,+) where++import OptEnvConf hiding (Command, commandParser)+import Paths_sqiff (version)+import RIO hiding (many, optional)+import RIO.Text qualified as T+import Sqiff.App.Env (BodyChecks (..), Scope (..), Source, source)+import Sqiff.Catalog (Partitions (..))+import Sqiff.ConnectionString (ConnectionString, connectionString)+import Sqiff.Folder (Existing (..))+import Sqiff.Identifier (Identifier, identifier)+import Sqiff.TableEdit (Drops (..))+++data Command+    = Describe DescribeOptions+    | Diff Source ConnectionString Scope+    | Plan Source ConnectionString Scope+    | Sqitch Source ConnectionString Scope SqitchOptions+    | TableFile FilePath ConnectionString TableOptions+++data DescribeOptions = DescribeOptions+    { db :: ConnectionString+    , out :: Maybe FilePath+    , existing :: Existing+    , scope :: Scope+    }+++data SqitchOptions = SqitchOptions+    { projectDir :: FilePath+    , topDir :: Maybe FilePath+    , planFile :: Maybe FilePath+    , tag :: Maybe Text+    , dryRun :: Bool+    }+++-- | The table command's options.+data TableOptions = TableOptions+    { output :: Output+    , base :: Text+    -- ^ The git revision with the file before the edit.+    , project :: FilePath+    , top :: Maybe FilePath+    , planPath :: Maybe FilePath+    , tableTag :: Maybe Text+    , mode :: TableMode+    }+++-- | Whether @table@ migrates the table to the file, or rewrites the file from the table.+data TableMode+    = MigrateToFile MigrateOptions+    | -- | From the table in this database, read-only, or in @--db@.+      RewriteFile (Maybe ConnectionString)+++data MigrateOptions = MigrateOptions+    { comparison :: Comparison+    , sameTypeSwap :: SameTypeSwap+    }+++-- | What the edited file is compared with: the file at the base revision, with the+-- columns these pairs rename, or the live table.+data Comparison+    = WithBaseFile [(Identifier, Identifier)]+    | WithLiveTable Drops+++renamesOf :: Comparison -> [(Identifier, Identifier)]+renamesOf = \case+    WithBaseFile renames -> renames+    WithLiveTable _ -> []+++-- | Whether @table@ prints the migration or writes it with sqitch.+data Output = PrintMigration | WriteMigration+    deriving stock (Eq)+++-- | A dropped column and an added one of the same type: maybe a rename, or not one.+data SameTypeSwap = AskIfRename | DropAndAdd+    deriving stock (Eq)+++-- | The table command's flags as given.+data TableFlags = TableFlags+    { output :: Output+    , againstDatabase :: Bool+    , allowDrops :: Bool+    , base :: Text+    , project :: FilePath+    , top :: Maybe FilePath+    , planPath :: Maybe FilePath+    , tableTag :: Maybe Text+    , renames :: [(Identifier, Identifier)]+    , dropAndAdd :: Bool+    , rewriteFile :: Bool+    , liveFrom :: Maybe ConnectionString+    }+++-- | The table command's options, when its flags apply together.+tableOptions :: TableFlags -> Either Text TableOptions+tableOptions f = do+    mode <-+        if f.rewriteFile+            then do+                unless (null f.renames) $ Left "--rename works with the file comparison, not --rewrite-file"+                when f.againstDatabase $ Left "--against-database works with the file comparison, not --rewrite-file"+                when f.allowDrops $ Left "--allow-drops works with --against-database, not --rewrite-file"+                when f.dropAndAdd $ Left "--drop-and-add works with the file comparison, not --rewrite-file"+                pure (RewriteFile f.liveFrom)+            else do+                when (f.againstDatabase && not (null f.renames)) $ Left "--rename works with the file comparison, not --against-database"+                when (isJust f.liveFrom) $ Left "--live-from works with --rewrite-file"+                when (f.allowDrops && not f.againstDatabase) $ Left "--allow-drops works with --against-database"+                let comparison+                        | f.againstDatabase = WithLiveTable (if f.allowDrops then AllowDrops else ReportDrops)+                        | otherwise = WithBaseFile f.renames+                pure (MigrateToFile MigrateOptions{comparison, sameTypeSwap = if f.dropAndAdd then DropAndAdd else AskIfRename})+    pure TableOptions{output = f.output, base = f.base, project = f.project, top = f.top, planPath = f.planPath, tableTag = f.tableTag, mode}+++-- | The command the arguments name. Flags that do not apply together are a parse error.+parseCommand :: IO Command+parseCommand = runParser version "Compare PostgreSQL schemas and write the migrations between them" commandParser+++commandParser :: Parser Command+commandParser =+    commands+        [ command "describe" "Read one database's schema; with --out, write one file per object" (Describe <$> describeParser)+        , command "diff" "Show what turns --from into --to; exits 1 when they differ" (twoDatabases Diff)+        , command "plan" "Print the SQL that turns --from into --to" (twoDatabases Plan)+        , command "sqitch" "Write the plan as sqitch changes" (twoDatabases Sqitch <*> sqitchOptions)+        , command+            "table"+            "Print the migration that turns a table into what its edited deploy file creates; with --write, add it and rework the file"+            tableParser+        ]+  where+    tableParser =+        TableFile+            <$> setting [help "The table's deploy file, for example database/deploy/runtime/table/payment.sql", reader str, argument, metavar "FILE"]+            <*> dbOption "db" "A database with the table as it is now; changes are rolled back"+            <*> checkMapEither (first T.unpack . tableOptions) tableFlags+    tableFlags =+        TableFlags+            <$> (bool PrintMigration WriteMigration <$> flag "write" "Add the migration with sqitch and rework the table's change")+            <*> flag "against-database" "Compare with the live table instead of the file at --base; shows drift too"+            <*> flag "allow-drops" "With --against-database, drop columns and constraints that are not in the file"+            <*> setting [help "Git revision with the file before your edit", reader str, option, long "base", metavar "REV", value "master"]+            <*> projectOption+            <*> topDirOption+            <*> planFileOption+            <*> optional (setting [help "Tag to add when the rework needs one", reader str, option, long "tag", metavar "NAME"])+            <*> many (setting [help "Column OLD is renamed to NEW; repeat for more columns", reader (eitherReader renameArg), option, long "rename", metavar "OLD:NEW"])+            <*> flag "drop-and-add" "A column dropped and one added with the same type are not a rename"+            <*> flag "rewrite-file" "Print the file rewritten to create the table as --db has it; with --write, write it and rework the change"+            <*> optional (connectionString <$> setting [help "With --rewrite-file, read the table from this database, read-only, instead of --db; --db still builds the file", reader str, option, long "live-from", metavar "CONNINFO"])+    flag key description = setting [help description, switch True, long key, value False]+    renameArg s = case T.split (== ':') (T.pack s) of+        [old, new] | not (T.null old), not (T.null new) -> Right (identifier old, identifier new)+        _ -> Left "expected OLD:NEW"+    dbOption key description =+        connectionString+            <$> setting+                [ help (description <> "; left out, libpq's PGHOST, PGPORT, PGUSER, PGDATABASE or PGSERVICE name it")+                , reader str+                , option+                , long key+                , metavar "CONNINFO"+                , value ""+                ]+    projectOption = setting [help "Where sqitch.conf and sqiff.yaml are", reader str, option, long "project", metavar "DIR", value "."]+    topDirOption = optional (setting [help "sqitch's top directory; sqitch config's core.top_dir when left out", reader str, option, long "top-dir", metavar "DIR"])+    planFileOption = optional (setting [help "sqitch's plan; sqitch config's core.plan_file when left out", reader str, option, long "plan-file", metavar "FILE"])+    sqitchOptions =+        SqitchOptions+            <$> projectOption+            <*> topDirOption+            <*> planFileOption+            <*> optional (setting [help "Tag to add when a rework needs one", reader str, option, long "tag", metavar "NAME"])+            <*> flag "dry-run" "List the changes without writing them"+    twoDatabases constructor =+        constructor+            <$> ( source+                    <$> setting+                        [ help "The database to change; master or rev:REV builds or updates the baseline database at that revision and uses it"+                        , reader str+                        , option+                        , long "from"+                        , metavar "CONNINFO|master|rev:REV"+                        ]+                )+            <*> dbOption "to" "The database with the desired schema"+            <*> scopeParser+    describeParser =+        DescribeOptions+            <$> dbOption "db" "The database to read"+            <*> optional (setting [help "Write one file per object to this directory", reader str, option, long "out", metavar "DIR"])+            <*> (bool KeepExisting ReplaceOwn <$> flag "replace" "Clear --out first, if sqiff wrote it")+            <*> scopeParser+    scopeParser =+        Scope+            <$> many (setting [help "Leave this schema out, besides sqiff.yaml's exclude-schemas", reader str, option, long "exclude-schema", metavar "SCHEMA"])+            <*> (bool SkipPartitions IncludePartitions <$> flag "include-partitions" "Also compare partitions and their columns")+            <*> (bool CheckBodies SkipBodyChecks <$> flag "no-body-check" "Skip recreating SQL-standard function bodies in rolled-back transactions on --to")
+ src/Sqiff/App/Read.hs view
@@ -0,0 +1,413 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Reads databases: their schemas over a few connections at once, and the dependency+-- edges a command needs. Connections live in scopes, so they are released however the+-- command ends.+module Sqiff.App.Read (+    Connected (..),+    withDatabase,+    describeConnections,+    Purpose (..),+    SchemaSnapshot (..),+    ComparisonInputs (..),+    readBoth,+    reachableEdges,+    routineWords,+    withSource,+) where++import Data.String.Interpolate (i)+import Hasql.Connection qualified as Connection+import RIO+import RIO.HashSet qualified as HS+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.NonEmpty (nonEmpty)+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.App.Env (AppEnv (..), BodyChecks (..), Scope (..), Source (..), note)+import Sqiff.Baseline (withBaseline)+import Sqiff.Body (BodyCheck, checkBodies)+import Sqiff.Catalog (Addresses, CatalogId (..), dependenciesFrom, dependenciesOn, describeOn, edgesBetween, pgClass, pgProc)+import Sqiff.Catalog.PlpgsqlCheck (PlFunction (..), PlFunctions (..), Skipped, analyseBodies, bodyUses, plpgsqlFunctions, tempTableStatements)+import Sqiff.Config (Config (..))+import Sqiff.Connection (withConnection, withConnections, withSharedSnapshot)+import Sqiff.ConnectionString (ConnectionString)+import Sqiff.Definition (printed)+import Sqiff.Dependencies (Dependencies, indexEdges, reachableFrom)+import Sqiff.Diff (BodyCandidate (..), BodyText (..), Change (..), Changes, bodiesToAnalyse, bodyText, diff)+import Sqiff.Model+import Sqiff.Timing (measure, timed)+++-- | Connections per database; the describe queries run over all of them at once.+describeConnections :: Int+describeConnections = 4+++-- | A described database and its open connections, valid inside 'withDatabase'.+data Connected = Connected+    { conn :: Connection.Connection+    , extra :: [Connection.Connection]+    -- ^ More connections to spread queries over.+    , schema :: Schema+    , addresses :: Addresses+    , tempTableScript :: IO (Maybe Text)+    -- ^ The statements that make plpgsql_check's temp tables there.+    }+++-- | Runs @action@ with the database described over 'describeConnections' connections. The+-- connections open and the description starts the first time @action@ asks for it; all+-- are released when @action@ returns or fails.+withDatabase :: Scope -> ConnectionString -> (IO Connected -> IO a) -> IO a+withDatabase scope db = onDemand \use ->+    withConnections db describeConnections \(conn :| extra) ->+        withAsync (withConnection db tempTableStatements) \tempTables -> do+            (schema, addresses) <- withSharedSnapshot (conn :| extra) $ describeOn (conn : extra) scope.excluded scope.partitions Nothing+            use Connected{conn, extra, schema, addresses, tempTableScript = wait tempTables}+++-- | Runs @action@ with a way to get what @acquire@ makes. @acquire@ runs, in a thread of its+-- own, the first time @action@ asks, and what it holds is released when @action@ ends.+onDemand :: ((a -> IO ()) -> IO ()) -> (IO a -> IO b) -> IO b+onDemand acquire action = do+    wanted <- newEmptyMVar+    ready <- newEmptyMVar+    done <- newEmptyMVar+    withAsync (readMVar wanted >> acquire \a -> putMVar ready a >> readMVar done) \holder -> do+        let get = do+                void (tryPutMVar wanted ())+                race (wait holder) (readMVar ready) >>= \case+                    Right a -> pure a+                    Left () -> throwString "the resource was released before it was ready"+        action get `finally` tryPutMVar done ()+++-- | Which edges a command uses.+data Needed+    = -- | Edges from @pg_depend@, and the body edges 'Sqiff.Diff.affected' can reach from these.+      ReachableFrom (Set ObjectId)+    | -- | Edges from @pg_depend@, and edges from the bodies of these functions only.+      BodiesOf (Set ObjectId)+    | -- | None; plpgsql_check still lists the functions it cannot analyse.+      NoEdges+++-- | Whether a command lists the differences or plans the migration.+data Purpose = ForDiff | ForPlan+    deriving stock (Eq)+++-- | The edges a command needs, given the objects that differ between the databases.+neededFor :: Purpose -> Changes -> Needed+neededFor purpose changes+    | Map.null changes = NoEdges+    | purpose == ForPlan = BodiesOf (Set.fromList [k.object | k <- Map.keys changes])+    | null starts = NoEdges+    | otherwise = ReachableFrom (Set.fromList starts)+  where+    starts = [k.object | (k, c) <- Map.toList changes, k.aspect == Definition, removesOrChanges c]+    removesOrChanges = \case Added _ -> False; _ -> True+++-- | Edges from @pg_depend@ and, when plpgsql_check is installed, from PL/pgSQL bodies,+-- with notes for stderr. @label@ names the database in the notes.+edgesOf :: Text -> Scope -> Needed -> Connected -> IO ([Edge], [Text])+edgesOf label scope needed connected = timed [i|edgesOf #{label}|] case needed of+    ReachableFrom starts -> reachableEdges label scope starts connected (routineWords connected.schema)+    _ -> do+        let Connected{conn, extra, addresses, tempTableScript = made} = connected+            wantedIds wanted = [ids | (ids, object) <- Map.toList addresses, object `Set.member` wanted]+            only = case needed of+                BodiesOf wanted -> Just (Set.fromList [ids.objectOid | ids <- wantedIds wanted, ids.classId == pgProc])+                _ -> Just Set.empty+        (edges, body) <-+            concurrently+                ( timed [i|edgesOf.dependOn #{label}|] case needed of+                    BodiesOf wanted -> dependenciesOn conn addresses (wantedIds wanted)+                    _ -> pure []+                )+                (timed [i|edgesOf.bodyUses #{label}|] $ fmap (first (edgesBetween addresses)) <$> bodyUses (fromMaybe (conn :| []) (nonEmpty extra)) scope.excluded only made)+        pure (edges <> maybe [] fst body, bodyNotes label (snd <$> body))+++bodyNotes :: Text -> Maybe Skipped -> [Text]+bodyNotes label = \case+    Nothing -> ["sqiff: plpgsql_check is not installed; PL/pgSQL body dependencies are left out"]+    Just [] -> []+    Just skipped ->+        let n = length skipped+         in [i|sqiff: plpgsql_check could not analyse #{n} PL/pgSQL functions on #{label}; their body dependencies are left out:|]+                : [[i|  #{name}: #{reason}|] | (name, reason) <- skipped]+++-- | How far 'reachableEdges' has got.+data Reach = Reach+    { explored :: Set ObjectId+    -- ^ The objects whose @pg_depend@ edges have been read.+    , catalogEdges :: [Edge]+    , bodyEdges :: [Edge]+    -- ^ The edges plpgsql_check found in the bodies analysed.+    , analysed :: Set Int64+    -- ^ The functions whose bodies have been analysed, by oid.+    , failed :: Skipped+    }+++reachedSoFar :: Reach -> Dependencies+reachedSoFar reach = indexEdges (reach.catalogEdges <> reach.bodyEdges)+++-- | A database's addresses, indexed both ways 'reachableEdges' looks them up. Built once.+data AddressIndex = AddressIndex+    { addresses :: Addresses+    , idsOf :: Map ObjectId [CatalogId]+    -- ^ The catalog ids of each object.+    , columnsOf :: Map ObjectId [ObjectId]+    -- ^ The columns of each relation.+    }+++addressIndex :: Addresses -> AddressIndex+addressIndex addresses =+    AddressIndex+        { addresses+        , idsOf = Map.fromListWith (<>) [(object, [ids]) | (ids, object) <- Map.toList addresses]+        , columnsOf = Map.fromListWith (<>) [(rel, [object]) | (ids, object) <- Map.toList addresses, ids.classId == pgClass, ids.subId > 0, Just rel <- [relationWith ids]]+        }+  where+    relationWith ids = Map.lookup (CatalogId pgClass ids.objectOid 0) addresses+++-- | The catalog ids of these objects, to read their @pg_depend@ edges by.+idsFor :: AddressIndex -> Set ObjectId -> [CatalogId]+idsFor index = concatMap (\a -> Map.findWithDefault [] a index.idsOf) . Set.toList+++-- | These objects and the columns of those that are relations.+withColumns :: AddressIndex -> Set ObjectId -> Set ObjectId+withColumns index xs = xs <> Set.fromList (concatMap (\a -> Map.findWithDefault [] a index.columnsOf) (Set.toList xs))+++-- | What every round of 'discoverReachable' reads from; it does not change between rounds.+data ReachInput = ReachInput+    { conn :: Connection.Connection+    , extra :: [Connection.Connection]+    , index :: AddressIndex+    , tempTableScript :: IO (Maybe Text)+    , starts :: Set ObjectId+    , functions :: PlFunctions+    , candidates :: [BodyCandidate PlFunction]+    , implicit :: [ObjectId]+    -- ^ The functions behind user-defined casts and operators.+    }+++-- | The @pg_depend@ edges reachable from @starts@, and the body edges of the PL/pgSQL+-- functions 'bodiesToAnalyse' picks, repeated until nothing new is reached or picked.+reachableEdges :: Text -> Scope -> Set ObjectId -> Connected -> IO (Map ObjectId BodyText) -> IO ([Edge], [Text])+reachableEdges label scope starts Connected{conn, extra, schema, addresses, tempTableScript} splitWords = timed [i|reachableEdges #{label}|] do+    let index = addressIndex addresses+    (edges, functions) <-+        concurrently+            (timed "reach.dependFrom0" $ dependenciesFrom conn addresses (idsFor index starts))+            ( timed "reach.functionsAndWords"+                $ plpgsqlFunctions (fromMaybe conn (listToMaybe extra)) scope.excluded+                >>= traverse \fs -> do+                    split_ <- splitWords+                    candidates <- bodyCandidates schema addresses split_ fs.checkable+                    pure (fs, candidates)+            )+    case functions of+        Nothing -> pure (edges, bodyNotes label Nothing)+        Just (fs, candidates) -> do+            let input =+                    ReachInput+                        { conn+                        , extra+                        , index+                        , tempTableScript+                        , starts+                        , functions = fs+                        , candidates+                        , implicit = [a | o <- fs.implicit, Just a <- [Map.lookup (CatalogId pgProc o 0) addresses]]+                        }+            reached <- discoverReachable input (firstReach index starts edges)+            pure (reached.catalogEdges <> reached.bodyEdges, bodyNotes label (Just (fs.unchecked <> inCheckableOrder fs reached.failed)))+++-- | The checkable functions as 'bodiesToAnalyse' sees them. Their words are split over+-- eight threads and forced there.+bodyCandidates :: Schema -> Addresses -> Map ObjectId BodyText -> [PlFunction] -> IO [BodyCandidate PlFunction]+bodyCandidates schema addresses split_ checkable =+    concat <$> pooledMapConcurrently forced (eightParts checkable)+  where+    forced part = do+        let candidates = mapMaybe (bodyCandidate addresses (wordsAt schema split_)) part+        _ <- evaluate (foldl' (\n c -> n + HS.size c.body.wordSet) (0 :: Int) candidates)+        pure candidates+++-- | A function with its object, its words, and the table it is a trigger on; 'Nothing'+-- when it has no address.+bodyCandidate :: Addresses -> (ObjectId -> BodyText) -> PlFunction -> Maybe (BodyCandidate PlFunction)+bodyCandidate addresses wordsOfObject f = do+    object <- Map.lookup (CatalogId pgProc f.oid 0) addresses+    pure+        BodyCandidate+            { value = f+            , object+            , body = wordsOfObject object+            , triggerRelation = f.relid >>= \r -> Map.lookup (CatalogId pgClass r 0) addresses+            }+++-- | The words of a routine: split already, or split from its definition here.+wordsAt :: Schema -> Map ObjectId BodyText -> ObjectId -> BodyText+wordsAt schema split_ object = fromMaybe (bodyText (maybe "" printed (Map.lookup (definitionKey object) schema))) (Map.lookup object split_)+++-- | Where the search starts: the first @pg_depend@ edges read, nothing analysed yet.+firstReach :: AddressIndex -> Set ObjectId -> [Edge] -> Reach+firstReach index starts edges =+    Reach+        { explored = withColumns index (starts <> Set.fromList (map (.dependent) edges))+        , catalogEdges = edges+        , bodyEdges = []+        , analysed = Set.empty+        , failed = []+        }+++-- | One round: read the @pg_depend@ edges of what is newly reached, then analyse the+-- bodies that may reach further; repeated until neither adds anything.+discoverReachable :: ReachInput -> Reach -> IO Reach+discoverReachable input reach = do+    let frontier = (input.starts <> reachableFrom (reachedSoFar reach) input.starts) `Set.difference` reach.explored+    more <- timed "reach.dependFrom" $ dependenciesFrom input.conn input.index.addresses (idsFor input.index frontier)+    let read_ = reach{explored = reach.explored <> withColumns input.index (frontier <> Set.fromList (map (.dependent) more)), catalogEdges = reach.catalogEdges <> more}+    case [f | f <- picked input (reachedSoFar read_), f.oid `Set.notMember` read_.analysed] of+        []+            | Set.null frontier -> pure read_+            | otherwise -> discoverReachable input read_+        todo -> analyse input todo read_ >>= discoverReachable input+++-- | The functions whose bodies may reach further. All of them once a cast or operator+-- function is reached, since bodies use those without naming them.+picked :: ReachInput -> Dependencies -> [PlFunction]+picked input deps+    | any (`Set.member` (input.starts <> reachableFrom deps input.starts)) input.implicit = [f.value | f <- input.candidates]+    | otherwise = bodiesToAnalyse deps input.starts input.candidates+++-- | Analyses the bodies of @todo@ and adds the edges found.+analyse :: ReachInput -> [PlFunction] -> Reach -> IO Reach+analyse input todo reach = do+    let fs = input.functions+    (uses, failed) <- timed [i|reach.analyseBodies n=#{length todo}|] $ analyseBodies (input.conn :| input.extra) fs{tempTables = input.tempTableScript >>= maybe fs.tempTables pure} todo+    pure+        reach+            { analysed = reach.analysed <> Set.fromList (map (.oid) todo)+            , bodyEdges = reach.bodyEdges <> edgesBetween input.index.addresses uses+            , failed = reach.failed <> failed+            }+++-- | The functions plpgsql_check could not analyse, in the order it lists the checkable ones.+inCheckableOrder :: PlFunctions -> Skipped -> Skipped+inCheckableOrder fs = L.sortOn (\(name, _) -> Map.lookup name position)+  where+    position = Map.fromList (zip [f.name | f <- fs.checkable] [0 :: Int ..])+++-- | The words of every function's and procedure's definition, split on every core.+routineWords :: Schema -> IO (Map ObjectId BodyText)+routineWords schema = do+    let routines = [(k.object, printed def) | (k, def) <- Map.toList schema, k.aspect == Definition, isRoutine k.object]+        split part = do+            let split_ = [(addr, bodyText def) | (addr, def) <- part]+            _ <- evaluate (foldl' (\n (_, b) -> n + HS.size b.wordSet + T.length b.lowered) (0 :: Int) split_)+            pure split_+    Map.fromList . concat <$> pooledMapConcurrently split (eightParts routines)+++-- | The list dealt into eight parts, in turn: work for eight threads.+eightParts :: [a] -> [[a]]+eightParts xs = [[x | (n, x) <- zip [0 :: Int ..] xs, n `mod` 8 == k] | k <- [0 .. 7]]+++-- | A database's schema and the dependency edges read from it.+data SchemaSnapshot = SchemaSnapshot+    { schema :: Schema+    , dependencies :: Dependencies+    }+++-- | What 'readBoth' reads: @--from@, @--to@, and the body checks of @--to@.+data ComparisonInputs = ComparisonInputs+    { source :: SchemaSnapshot+    , target :: SchemaSnapshot+    , bodyChecks :: Map ObjectKey BodyCheck+    }+++-- | Reads both databases at the same time, then the edges the command needs, given what+-- differs, alongside the body checks; the edges of @--to@ only for 'ForPlan'.+readBoth :: Source -> ConnectionString -> Purpose -> RIO AppEnv ComparisonInputs+readBoth from toDb purpose = do+    env <- ask+    let scope = env.scope+    liftIO $ withDatabase scope toDb \describeTo -> withAsync (timed "describe --to" describeTo) \toDescribed -> do+        withSource env.config from \fromDb -> withDatabase scope fromDb \describeFrom -> do+            (fromDatabase, toDatabase) <-+                timed "readBoth.describe" $ concurrently (timed "describe --from" describeFrom) (wait toDescribed)+            let fromSchema = fromDatabase.schema+                toSchema = toDatabase.schema+                plainChanges = diff (\_ a b -> a == b) fromSchema toSchema+                -- What depends on the changes in --from, to the end of the chain, so views+                -- on views of a retyped column are found; in --to, for ordering, what the+                -- changed objects use.+                fromNeeded = neededFor ForDiff plainChanges+                toNeeded = neededFor ForPlan plainChanges+            measure "readBoth.plainDiff" (Map.size plainChanges)+            (((fromEdges, fromNotes), (toEdges, toNotes)), checks) <-+                timed "readBoth.edgesAndChecks"+                    $ concurrently+                        ( concurrently+                            (edgesOf "--from" scope fromNeeded fromDatabase)+                            (if purpose == ForPlan then edgesOf "--to" scope toNeeded toDatabase else pure ([], []))+                        )+                        (bodyChecks scope toDb toSchema plainChanges)+            for_ (fromNotes <> toNotes) note+            pure+                ComparisonInputs+                    { source = SchemaSnapshot{schema = fromSchema, dependencies = indexEdges fromEdges}+                    , target = SchemaSnapshot{schema = toSchema, dependencies = indexEdges toEdges}+                    , bodyChecks = checks+                    }+++-- | Body checks for the definitions that are added or changed: no other check is consulted.+bodyChecks :: Scope -> ConnectionString -> Schema -> Changes -> IO (Map ObjectKey BodyCheck)+bodyChecks scope toDb toSchema plainChanges+    | scope.bodyCheck == CheckBodies =+        withConnection toDb \conn ->+            timed "bodyChecks" $ checkBodies conn (Map.restrictKeys toSchema addedOrChanged)+    | otherwise = pure Map.empty+  where+    addedOrChanged = Map.keysSet (Map.filter (\case Dropped _ -> False; _ -> True) plainChanges)+++-- | Runs @action@ with the database @--from@ names, holding the baseline for it when that+-- is what it names.+withSource :: Config -> Source -> (ConnectionString -> IO a) -> IO a+withSource config source action = case source of+    Database db -> action db+    BaselineAt rev -> timed "baseline" (withBaseline config.baseline rev action)
+ src/Sqiff/App/Table.hs view
@@ -0,0 +1,383 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | The table command: the migration that turns a table into what its edited deploy file+-- creates, printed or written with sqitch.+module Sqiff.App.Table (+    tableCommand,+    forTable,+    replayable,+) where++import Data.String.Interpolate (i)+import Data.Text.IO qualified as TIO+import Data.Time (getCurrentTime)+import Hasql.Connection qualified as Connection+import RIO+import RIO.Directory (makeAbsolute)+import RIO.FilePath (makeRelative, normalise, (</>))+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.App.Dependents (Dependents (..), dependentsIn, dependentsScope, exactDependentsOf)+import Sqiff.App.Env (say)+import Sqiff.App.Options (Comparison (..), MigrateOptions (..), Output (..), TableMode (..), TableOptions (..), renamesOf)+import Sqiff.App.Read (Connected (..), routineWords, withDatabase)+import Sqiff.App.Table.Env+import Sqiff.App.Table.Findings+import Sqiff.App.Table.Rewrite+import Sqiff.Catalog.PlpgsqlCheck (BodyError (..), Outcome (..), bodyErrorText, bodyErrors)+import Sqiff.Config (Config (..), Names (..), fill, loadConfig, match)+import Sqiff.Connection (failWith)+import Sqiff.ConnectionString (ConnectionString)+import Sqiff.Definition hiding (DomainType)+import Sqiff.Dependencies (noDependencies)+import Sqiff.Diff (BodyText (..), Change (..))+import Sqiff.Git (findRepo, showFile)+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Plan (context, cycleMessage, invert, renderStep)+import Sqiff.Recipe (Step (..))+import Sqiff.Recreate (standardBody)+import Sqiff.Script (splitStatements, withoutCommitsInDoBlock, withoutTransactionControl)+import Sqiff.Sqitch (PreviousFile (..), moveToEnd, requireSqitch, reworkEdited, withProject, writeUnits)+import Sqiff.Sqitch.Check (Tagging (..))+import Sqiff.Sqitch.Layout (Layout (..), Script (..), findLayout, planPath, scriptPath)+import Sqiff.Sqitch.Plan (SqitchPlan (..), parsePlan, readPlan)+import Sqiff.Sqitch.Units (Unit (..), slug, units)+import Sqiff.Sql (replaceInCode)+import Sqiff.TableEdit (Baseline (..), Live (..), TableEdit (..), TypeChange (..), aside, compareTable, firstFailure, foreignKeyError, typeChangeFacts, withEditedTable)+import Sqiff.Timing (measure, timed)+++-- | Prints the migration that turns the table into what its edited file creates, or+-- writes it with sqitch.+tableCommand :: FilePath -> ConnectionString -> TableOptions -> IO ()+tableCommand file db opts = do+    requireSqitch+    root <- makeAbsolute opts.project+    config <- loadConfig root+    layout <- findLayout root opts.top opts.planPath+    (absFile, changeName, table) <- locateTable config.names layout root file+    statements <- parseFile file "" =<< readFileUtf8 absFile+    let envWith repo original = TableEnv{opts, db, file, root, repo, config, layout, sqitchChange = changeName, table, statements, original}+    case opts.mode of+        RewriteFile liveFrom -> do+            repo <- findRepo root+            original <- timed "table.baseFile" $ showFile repo opts.base absFile+            runRIO (envWith repo original) (rewriteFromDatabase liveFrom)+        MigrateToFile migrate ->+            -- The database is described while git shows the file at the base revision when+            -- the comparison will need it; otherwise only once an edit asks for it.+            withDatabase (dependentsScope config.excludeSchemas) db \describe -> do+                let described = describe >>= \c -> (c,) <$> routineWords c.schema+                    needed = case migrate.comparison of+                        WithLiveTable _ -> True+                        WithBaseFile renames -> not (null renames)+                startingIf needed described \early -> do+                    repo <- findRepo root+                    original <- timed "table.baseFile" $ showFile repo opts.base absFile+                    let unchanged = Right statements == (withoutTransactionControl <=< splitStatements) original+                    startingIf (not needed && not unchanged) early \later ->+                        runRIO (envWith repo original) (compareAndReport migrate later)+++-- | Runs @action@ with @get@, started now in the background when @now@ is set.+startingIf :: Bool -> IO a -> (IO a -> IO b) -> IO b+startingIf now get action+    | now = withAsync get (action . wait)+    | otherwise = action get+++-- | The file's absolute path, its sqitch change and its table, by the table name pattern.+-- [allow:SqiffNamedTuples] pre-existing at adoption+locateTable :: Names -> Layout -> FilePath -> FilePath -> IO (FilePath, Text, QName)+locateTable names layout root file = do+    absFile <- makeAbsolute file+    let deployDir = normalise (root </> layout.deployDir)+        relative = T.pack (makeRelative deployDir absFile)+        pattern = names.table+    changeName <- maybe (failWith [i|#{file} is not under #{deployDir}|]) pure (T.stripSuffix ".sql" relative)+    table <- case match pattern changeName of+        Just values+            | Just s <- lookup "schema" values+            , Just t <- lookup "name" values+            , not ("@" `T.isInfixOf` t) ->+                pure (qname s t)+        _ -> failWith [i|#{file} is not a table's own deploy file (#{pattern}.sql under #{deployDir})|]+    pure (absFile, changeName, table)+++-- | Compares the table, checks what depends on the edit, and prints or writes the migration.+compareAndReport :: MigrateOptions -> IO (Connected, Map ObjectId BodyText) -> RIO TableEnv ()+compareAndReport migrate described = do+    env <- ask+    let opts = env.opts+        table = env.table+        renames = renamesOf migrate.comparison+    branchChanges <- branchChangesFor migrate.comparison+    let branchStatements = concatMap snd branchChanges+        normalised = T.toLower . T.unwords . T.words . T.dropWhileEnd (== ';') . T.strip . withoutLeadingComments+        pendingRenames = [r | r <- renames, normalised (renameSql table r) `notElem` map normalised branchStatements]+    for_ branchChanges \(n, _) -> say [i|-- already on this branch: #{n}|]+    baseline <- case migrate.comparison of+        WithLiveTable drops -> pure (LiveTable SameDatabase drops)+        WithBaseFile _ -> BaseFile . (<> (branchStatements <> map (renameSql table) pendingRenames)) <$> parseFile env.file (atBase opts) env.original+    timed "table.connect" . withScratch env.db $ \conn -> compareWith migrate described branchChanges pendingRenames baseline conn+++-- | 'compareAndReport' once the baseline is known, on the scratch connection.+compareWith :: MigrateOptions -> IO (Connected, Map ObjectId BodyText) -> [(Text, [Text])] -> [(Identifier, Identifier)] -> Baseline -> Connection.Connection -> RIO TableEnv ()+compareWith migrate described branchChanges pendingRenames baseline conn = do+    env <- ask+    let opts = env.opts+        table = env.table+    edit <- timed "table.compare1" $ liftIO (compareTable conn baseline table env.statements)+    let renamedFrom = Set.fromList [Column table old | (old, _) <- renamesOf migrate.comparison]+    deps <- timed "table.dependentsIn" $ liftIO (dependentsIn env.config.excludeSchemas described (edit.changes <> Map.fromSet (const (Dropped (Printed ""))) (Set.map (ObjectKey Definition) renamedFrom)))+    bodies <- bodyResultsFor conn baseline deps+    let retyped = retypedColumns edit+    foreignKeyBreaks <- liftIO (foreignKeyBreaksFor conn deps retyped)+    typeFacts <- liftIO (typeFactsFor conn edit retyped)+    findings <- either (failWith . cycleMessage) pure $ findingsFor env migrate Evidence{edit, deps, bodies, retyped, foreignKeyBreaks, typeFacts, branchChanges, pendingRenames, renamedFrom}+    measure "table.planRender" (T.length (T.unlines (map renderStep findings.steps <> findings.usage)) + length findings.blocking)+    printLeftAlone edit+    case opts.output of+        PrintMigration -> printMigration findings+        WriteMigration -> writeMigration conn baseline edit findings+++-- | This branch's changes for the table, with the statements the comparison can replay;+-- none against the database.+branchChangesFor :: Comparison -> RIO TableEnv [(Text, [Text])]+branchChangesFor comparison = do+    env <- ask+    let opts = env.opts+    case comparison of+        WithLiveTable _ -> pure []+        WithBaseFile _ -> do+            current <- liftIO (readPlan (planPath env.layout))+            basePlan <- liftIO (parsePlan <$> showFile env.repo opts.base (planPath env.layout))+            let before = Set.fromList basePlan.changes+            for (filter (\n -> n `Set.notMember` before && forTable env.config.names env.table n) (nubOrd current.changes)) \n -> do+                script <- readFileUtf8 (scriptPath env.layout Deploy n)+                (n,) . replayable <$> either (\e -> failWith [i|#{n}: #{e}|]) pure ((withoutTransactionControl <=< splitStatements) script)+++-- | Checks the PL/pgSQL and string-bodied SQL functions that depend on the edit or name it,+-- before and after the edit.+bodyResultsFor :: Connection.Connection -> Baseline -> Dependents -> RIO TableEnv BodyResults+bodyResultsFor conn baseline deps = do+    env <- ask+    let candidates = bodyCandidates env.table deps+        functions = Set.size (Set.fromList (map (.signature) (candidates.plpgsql <> candidates.sqlBodies)))+        check made =+            timed [i|table.bodyErrors n=#{functions}|]+                $ bodyErrors conn (nameText aside) (qualified env.table) made (map (.signature) candidates.plpgsql) (map (.signature) candidates.sqlBodies)+    comparison <-+        if null candidates.plpgsql && null candidates.sqlBodies+            then pure Nothing+            else+                timed "table.compare2"+                    . liftIO+                    $ withEditedTable conn baseline env.table env.statements (check deps.dbTempTables) (\before -> (\after -> BodyComparison <$> before <*> after) <$> check (pure Nothing))+    pure (classifyBodyResults env.table candidates comparison)+++-- | A function whose body the check reads.+data Checkable = Checkable+    { object :: ObjectId+    , signature :: Text+    , definition :: Text+    }+++-- | The functions to check: PL/pgSQL ones, and SQL ones with a string body, which+-- PostgreSQL validates when asked.+data BodyCandidates = BodyCandidates+    { plpgsql :: [Checkable]+    , sqlBodies :: [Checkable]+    }+++-- | What the check found before the edit and after it.+data BodyComparison = BodyComparison+    { before :: Set BodyError+    , after :: Set BodyError+    }+++-- | The routines that depend on the edit or name it, except ones taking the table's row+-- type, which the check cannot call with the edited table.+bodyCandidates :: QName -> Dependents -> BodyCandidates+bodyCandidates table deps =+    BodyCandidates+        { plpgsql = [c | c <- checkable, "LANGUAGE plpgsql" `T.isInfixOf` c.definition]+        , sqlBodies = [c | c <- checkable, "LANGUAGE sql" `T.isInfixOf` c.definition, not (standardBody c.definition)]+        }+  where+    routines = Set.toList (Set.filter (\a -> isRoutine a && not (takesRowType a)) (fold deps.named <> fold deps.exact))+    checkable = [Checkable{object = a, signature = routineSignature a, definition = printed def} | a <- routines, Just def <- [Map.lookup (definitionKey a) deps.dbSchema]]+    takesRowType = \case+        Routine _ _ args -> any ((`elem` [qualified table, qualified table <> "[]"]) . typeText) args+        _ -> False+++-- | How the check names a routine.+routineSignature :: ObjectId -> Text+routineSignature = \case+    Routine _ q args -> let list = T.intercalate ", " (map typeText args) in [i|#{qualified q}(#{list})|]+    a -> render a+++-- | The functions the edit breaks, with the first new error of each, and the ones the+-- check passes: checked, with no new error, and running no dynamic SQL it cannot see.+classifyBodyResults :: QName -> BodyCandidates -> Maybe BodyComparison -> BodyResults+classifyBodyResults table candidates comparison =+    BodyResults{breaking, passed}+  where+    all' = candidates.plpgsql <> candidates.sqlBodies+    bySignature = Map.fromList [(c.signature, c.object) | c <- all']+    newErrors = (\b -> Set.filter (not . callsWithRowType) (Set.difference b.after b.before)) <$> comparison+    unchecked = Set.fromList [e.signature | Just b <- [comparison], e <- Set.toList b.after, e.outcome == NotChecked]+    breaking = Map.fromListWith (\_ earlier -> earlier) [(a, bodyErrorText e) | e <- maybe [] Set.toList newErrors, Just a <- [Map.lookup e.signature bySignature]]+    passed =+        Set.fromList+            [ c.object+            | isJust newErrors+            , c <- all'+            , c.object `Map.notMember` breaking+            , c.signature `Set.notMember` unchecked+            , not ("execute" `T.isInfixOf` T.toLower c.definition)+            ]+    -- An error about calling a function with the table's row type, which the check+    -- cannot make with the edited table.+    callsWithRowType e = let message = bodyErrorText e in "function " `T.isPrefixOf` message && any (\end -> (qualified table <> end) `T.isInfixOf` message) [")", ","]+++-- | The foreign keys on retyped columns that cannot be rebuilt with the new types, with+-- PostgreSQL's error.+foreignKeyBreaksFor :: Connection.Connection -> Dependents -> [Retyped] -> IO (Map ObjectId [(ObjectId, Text)])+foreignKeyBreaksFor conn deps retyped =+    timed "table.foreignKeys"+        $ Map.fromListWith (<>)+        . catMaybes+        <$> for+            [ (addr, k, types)+            | addr <- map retypedObject retyped+            , k@(TableConstraint onTable _) <- Set.toList (exactDependentsOf addr deps)+            , Just (ConstraintDefinition def) <- [Map.lookup (definitionKey k) deps.dbSchema]+            , Just types <- [foreignKeyTypes typeIn onTable def]+            ]+            \(addr, k, types) -> fmap (\err -> (addr, [(k, err)])) <$> foreignKeyError conn types+  where+    typeIn t c = fmap typeText case [r.newType | r <- retyped, r.table == t, r.column == c] of+        ty : _ -> Just ty+        [] -> (.colType) <$> (asColumn =<< Map.lookup (definitionKey (Column t c)) deps.dbSchema)+++-- | For each retyped column, whether the change rewrites the table and whether the new+-- type is a domain.+typeFactsFor :: Connection.Connection -> TableEdit -> [Retyped] -> IO (Map ObjectId TypeChange)+typeFactsFor conn edit retyped =+    timed "table.typeChangeFacts" $ Map.fromList . catMaybes <$> for retyped \r ->+        let addr = retypedObject r+         in case asColumn =<< Map.lookup (definitionKey addr) edit.current of+                Just o -> fmap (addr,) <$> typeChangeFacts conn (typeText o.colType) (typeText r.newType)+                Nothing -> pure Nothing+++-- | The differences the comparison leaves alone, with the reason; an object's comment+-- goes with it.+printLeftAlone :: MonadIO m => TableEdit -> m ()+printLeftAlone edit = do+    let leftAlone = Set.fromList [k.object | (k, _) <- edit.ignored, k.aspect == Definition]+    for_ [(k, reason) | (k, reason) <- edit.ignored, not (k.aspect == Comment && k.object `Set.member` leftAlone)] \(k, reason) -> do+        let name = render k.object <> if k.aspect == Privileges then " (privileges)" else ""+        say [i|-- left alone: #{name}: #{reason}|]+++printMigration :: MonadIO m => Findings -> m ()+printMigration f = do+    let same = f.same+    for_ f.usage \line -> say [i|-- #{line}|]+    unless (null f.usage) $ say ""+    if null f.steps+        then say [i|-- #{same}|]+        else for_ f.steps (say . renderStep)+++-- | Adds the migration with sqitch and reworks the table's change.+writeMigration :: Connection.Connection -> Baseline -> TableEdit -> Findings -> RIO TableEnv ()+writeMigration conn baseline edit f = do+    env <- ask+    let opts = env.opts+        table = env.table+        changeName = env.sqitchChange+        same = f.same+    when (null f.steps) do+        say [i|nothing to write: #{same}|]+        exitSuccess+    for_ f.usage (liftIO . TIO.hPutStrLn stderr)+    unless (null f.blocking) do+        let n = length f.blocking+        failWith [i|#{n} dependencies on what the edit drops or retypes; change or drop the dependents first|]+    unless (null f.renameLike) $ failWith "a column is dropped and another added with the same type; say whether it is a rename with --rename or --drop-and-add"+    sqitchPlan <- timed "write.readPlan" $ liftIO (readPlan (planPath env.layout))+    basePlan <- timed "write.basePlan" $ liftIO (parsePlan <$> showFile env.repo opts.base (planPath env.layout))+    now <- liftIO getCurrentTime+    let inverseCtx = f.withViews (context Map.empty edit.desired edit.current noDependencies (Map.map invert edit.changes))+        isIndex s = case s.object of Index _ -> True; _ -> False+        written = units env.config.names isIndex inverseCtx edit.changes sqitchPlan now f.steps+        tagging = Tagging{given = opts.tableTag, now}+        entries p = length (filter (== changeName) p.changes)+        alreadyReworked = entries sqitchPlan > entries basePlan+    previous <- parseFile env.file (atBase opts) env.original+    oldFileFails <- timed "table.compare3" $ liftIO (withEditedTable conn baseline table env.statements (pure ()) (const (firstFailure conn previous)))+    let baseRev = opts.base+    for_ oldFileFails \err ->+        say [i|the file at #{baseRev} fails on the edited table (#{err}); the rework's revert does nothing and the migrations revert the table|]+    liftIO $ withProject env.layout \project -> do+        timed "write.writeUnits" $ writeUnits project env.config.templates sqitchPlan tagging written+        if alreadyReworked+            then moveToEnd project changeName+            else+                timed "write.reworkEdited"+                    $ reworkEdited project tagging changeName [i|sqiff: #{changeName} as edited|] env.original (maybe PreviousFileRuns (const PreviousFileFails) oldFileFails)+    for_ written \u -> let name = u.changeName in say [i|added #{name}|]+    say+        ( if alreadyReworked+            then [i|moved the branch's rework of #{changeName} after the new migrations; if this branch is deployed locally, revert it to before the rework first|]+            else [i|reworked #{changeName}|]+        )+++-- | Whether a sqitch change is about the table, by the names sqiff gives: one of its+-- indexes, or <schema>.<table> in a migration's name, which is lower-cased and has other+-- characters made dashes ('slug').+forTable :: Names -> QName -> Text -> Bool+forTable names t n =+    let indexes = fill names.index [("schema", nameText t.schema), ("table", nameText t.name), ("name", "")]+        padded = [i|#{n}-|] :: Text+     in indexes+            `T.isPrefixOf` n+            || or+                [ [i|#{before}#{key}#{after}|] `T.isInfixOf` padded+                | key <- nubOrd [dotted t, slug (dotted t)]+                , before <- ["-", "/" :: Text]+                , after <- [".", "-" :: Text]+                ]+++-- | A migration's statements as they can run inside the comparison's transaction:+-- without session settings, with concurrent index builds made plain, and with the+-- commits of a batched backfill's @do@ block left out.+replayable :: [Text] -> [Text]+replayable = map (withoutCommitsInDoBlock . replaceInCode "concurrently " "" . replaceInCode "CONCURRENTLY " "") . filter (not . setting)+  where+    setting s = any (`T.isPrefixOf` T.toLower (withoutLeadingComments s)) ["set ", "reset ", "select set_config("]
+ src/Sqiff/App/Table/Env.hs view
@@ -0,0 +1,74 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What the table command works on, and the helpers its parts share.+module Sqiff.App.Table.Env (+    TableEnv (..),+    parseFile,+    atBase,+    renameSql,+    withoutLeadingComments,+    withScratch,+) where++import Data.String.Interpolate (i)+import Hasql.Connection qualified as Connection+import RIO+import RIO.Text qualified as T+import Sqiff.App.Options (TableOptions (..))+import Sqiff.Config (Config (..))+import Sqiff.Connection (failWith, withConnection)+import Sqiff.ConnectionString (ConnectionString, redacted)+import Sqiff.Git (Repo)+import Sqiff.Identifier+import Sqiff.Script (splitStatements, withoutTransactionControl)+import Sqiff.Sqitch.Layout (Layout (..))+import Sqiff.TableEdit (requireScratch)+++-- | What the table command works on: its options, the deploy file before and after the+-- edit, and where they live.+data TableEnv = TableEnv+    { opts :: TableOptions+    , db :: ConnectionString+    , file :: FilePath+    , root :: FilePath+    , repo :: Repo+    , config :: Config+    , layout :: Layout+    , sqitchChange :: Text+    , table :: QName+    , statements :: [Text]+    , original :: Text+    }+++-- | Runs @action@ with a connection to the database the table command edits in+-- rolled-back transactions; released when it returns or fails.+withScratch :: MonadUnliftIO m => ConnectionString -> (Connection.Connection -> m a) -> m a+withScratch db action = withConnection db \conn -> do+    liftIO (requireScratch (redacted db) conn)+    action conn+++-- | A deploy file's statements; @label@ names the version in a parse error.+parseFile :: MonadIO m => FilePath -> Text -> Text -> m [Text]+parseFile file label = either (\e -> failWith [i|#{file}#{label}: #{e}|]) pure . (withoutTransactionControl <=< splitStatements)+++atBase :: TableOptions -> Text+atBase opts = let base = opts.base in [i| at #{base}|]+++renameSql :: QName -> (Identifier, Identifier) -> Text+renameSql table (old, new) = [i|alter table #{qualified table} rename column #{quoted old} to #{quoted new}|]+++-- | A statement from its first line of code.+withoutLeadingComments :: Text -> Text+withoutLeadingComments = T.stripStart . T.unlines . dropWhile (\l -> T.null (T.strip l) || "--" `T.isPrefixOf` T.stripStart l) . T.lines
+ src/Sqiff/App/Table/Findings.hs view
@@ -0,0 +1,425 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What the table command reports about an edit, from what the comparison and the checks+-- found: the migration's steps, what depends on the edit, and what blocks it.+module Sqiff.App.Table.Findings (+    Retyped (..),+    retypedObject,+    retypedColumns,+    BodyResults (..),+    Evidence (..),+    Findings (..),+    RenameCandidate (..),+    findingsFor,+    foreignKeyTypes,+) where++import Data.String.Interpolate (i)+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.App.Dependents (Dependents (..), exactDependentsOf, routinesNaming)+import Sqiff.App.Options (Comparison (..), MigrateOptions (..), SameTypeSwap (..), TableOptions (..), renamesOf)+import Sqiff.App.Table.Env+import Sqiff.Config (Config (..))+import Sqiff.Definition hiding (DomainType)+import Sqiff.Dependencies (noDependencies)+import Sqiff.Diff (Change (..))+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Plan (DependencyCycle, planWith)+import Sqiff.Recipe (Context (viewsAround), Hazard (..), Phase (..), Role (..), Step (..), Txn (..), Undo (..))+import Sqiff.Recreate (Recreation (..), viewsAroundTypeChanges)+import Sqiff.TableEdit (TableEdit (..), TableRewrite (..), TargetType (..), TypeChange (..))+++-- | A column whose type the edit changes.+data Retyped = Retyped+    { table :: QName+    , column :: Identifier+    , newType :: TypeName+    }+++retypedObject :: Retyped -> ObjectId+retypedObject r = Column r.table r.column+++-- | The functions the body check finds broken by the edit, and the ones it passes.+data BodyResults = BodyResults+    { breaking :: Map ObjectId Text+    , passed :: Set ObjectId+    }+++-- | What the comparison and the checks found.+data Evidence = Evidence+    { edit :: TableEdit+    , deps :: Dependents+    , bodies :: BodyResults+    , retyped :: [Retyped]+    , foreignKeyBreaks :: Map ObjectId [(ObjectId, Text)]+    , typeFacts :: Map ObjectId TypeChange+    , branchChanges :: [(Text, [Text])]+    , pendingRenames :: [(Identifier, Identifier)]+    , renamedFrom :: Set ObjectId+    }+++-- | The migration's steps and what the command reports about them.+data Findings = Findings+    { steps :: [Step]+    , usage :: [Text]+    -- ^ The report on what uses the edited objects, line by line.+    , blocking :: [ObjectId]+    -- ^ What the migration would break.+    , renameLike :: [RenameCandidate]+    , same :: Text+    -- ^ What to say when there is nothing to migrate.+    , withViews :: Context -> Context+    }+++-- | A dropped column and an added one of the same type, which may be a rename.+data RenameCandidate = RenameCandidate+    { droppedColumn :: Identifier+    , addedColumn :: Identifier+    }+++retypedColumns :: TableEdit -> [Retyped]+retypedColumns edit =+    [ Retyped{table = t, column = c, newType = n.colType}+    | (k, Changed old new) <- Map.toList edit.changes+    , k.aspect == Definition+    , ColumnDefinition o <- [old]+    , ColumnDefinition n <- [new]+    , columnTypeChanged o n+    , Column t c <- [k.object]+    ]+++findingsFor :: TableEnv -> MigrateOptions -> Evidence -> Either DependencyCycle Findings+findingsFor env migrate ev = do+    planned <- planWith withViews Map.empty ev.edit.current ev.edit.desired noDependencies noDependencies ev.edit.changes+    pure+        Findings+            { steps = renames <> map (refineHazards env.table ev) planned+            , usage = usageReport effects ev <> map renameNote candidates+            , blocking = Set.toList (blockers effects ev)+            , renameLike = candidates+            , same = nothingToMigrate env migrate ev+            , withViews+            }+  where+    effects = effectsOf env.table ev+    renames = map (renameStep env ev.edit) ev.pendingRenames+    candidates = renameCandidates migrate ev.edit+    withViews c = c{viewsAround = Map.map (.statements) effects.recreations}+++-- | What the edit does to the objects it changes, which decides what happens to what+-- depends on them.+data Effects = Effects+    { table :: QName+    , dropped :: Set ObjectId+    , recreations :: Map (QName, Identifier) Recreation+    -- ^ What goes and comes back around each retyped column.+    , recreatedAround :: Map ObjectId (Set ObjectId)+    -- ^ For each retyped column, the objects that go and come back around it. Every+    -- retyped column has an entry, empty when nothing goes around it: being a key here+    -- is what marks a column as retyped.+    }+++effectsOf :: QName -> Evidence -> Effects+effectsOf table ev =+    Effects+        { table+        , dropped = Set.fromList [k.object | (k, Dropped _) <- Map.toList ev.edit.changes, k.aspect == Definition]+        , recreations+        , recreatedAround =+            Map.fromListWith+                (<>)+                [ (retypedObject r, maybe Set.empty (.members) (Map.lookup (r.table, r.column) recreations))+                | r <- ev.retyped+                ]+        }+  where+    recreations =+        viewsAroundTypeChanges ev.deps.exact ev.deps.dbSchema ev.deps.dbDeps [(r.table, r.column, retypedObject r) | r <- ev.retyped]+++-- | Whether @dependent@ is dropped with a dropped column of @table@: its indexes and its+-- table's constraints.+goesWithColumn :: QName -> ObjectId -> Bool+goesWithColumn table = \case+    Index _ -> True+    TableConstraint t _ -> t == table+    _ -> False+++-- | Whether @dependent@ of @column@ is dropped and created again around its type change.+-- A trigger on a view that is created again comes back with it.+recreatedWith :: Effects -> ObjectId -> ObjectId -> Bool+recreatedWith effects column dependent =+    dependent `Set.member` around || case dependent of+        Trigger t _ -> any (\v -> isView v && isRelation v == Just t) around+        _ -> False+  where+    around = Map.findWithDefault Set.empty column effects.recreatedAround+++-- | Whether PostgreSQL rebuilds @dependent@ itself when a column it uses changes type.+rebuiltWithColumn :: ObjectId -> Bool+rebuiltWithColumn = \case+    Index _ -> True+    TableConstraint{} -> True+    Sequence _ -> True+    _ -> False+++-- | What the migration would break: what depends on a dropped column and does not go+-- with it, what depends on a retyped column and is neither created again, rebuilt nor+-- checked, the routines whose bodies break, and the foreign keys that cannot be rebuilt.+blockers :: Effects -> Evidence -> Set ObjectId+blockers effects ev = onDropped <> onRetyped <> Map.keysSet ev.bodies.breaking <> unbuildableForeignKeys+  where+    onDropped =+        Set.fromList+            [ d+            | (object, ds) <- Map.toList ev.deps.exact+            , object `Set.member` effects.dropped+            , d <- Set.toList ds+            , not (goesWithColumn effects.table d)+            ]+    onRetyped =+        Set.fromList+            [ d+            | (object, ds) <- Map.toList ev.deps.exact+            , -- The column is retyped.+            object `Map.member` effects.recreatedAround+            , d <- Set.toList ds+            , not (recreatedWith effects object d)+            , not (rebuiltWithColumn d)+            , d `Set.notMember` ev.bodies.passed+            ]+    unbuildableForeignKeys = Set.fromList [k | ks <- Map.elems ev.foreignKeyBreaks, (k, _) <- ks]+++-- | A retyping step's hazards, made exact by what PostgreSQL says the type change does:+-- whether it rewrites the table, and so whether a value can fail to convert, and the+-- other tables its foreign keys lock and check again.+refineHazards :: QName -> Evidence -> Step -> Step+refineHazards table ev step = case Map.lookup step.object ev.typeFacts of+    Just (TypeChange rewrite target)+        | MayRewriteTable `elem` step.hazards ->+            let rewrites = rewrite == RewritesFiles+                exact = \case+                    MayRewriteTable -> [RewritesTable | rewrites]+                    ConversionMayFail -> [ConversionMayFail | rewrites || target == DomainType]+                    h -> [h]+                onOther other = LocksOther other : [RechecksForeignKey other | rewrites]+             in step{hazards = concatMap exact step.hazards <> concatMap onOther (foreignKeyPartners table ev.deps step.object)}+    _ -> step+++-- | The other tables that foreign keys depending on @column@ tie to @table@, as SQL+-- names them, in order.+foreignKeyPartners :: QName -> Dependents -> ObjectId -> [Text]+foreignKeyPartners table deps column =+    Set.toList+        . Set.fromList+        $ [ qualified other+          | k@(TableConstraint onTable _) <- Set.toList (exactDependentsOf column deps)+          , Just (ConstraintDefinition def) <- [Map.lookup (definitionKey k) deps.dbSchema]+          , Just target <- [def.references]+          , let other = if onTable == table then target.table else onTable+          , other /= table+          ]+++-- | The step that renames a column from @old@ to @new@ before anything else, undone by+-- renaming it back.+renameStep :: TableEnv -> TableEdit -> (Identifier, Identifier) -> Step+renameStep env edit (old, new) =+    Step+        { phase = DropPhase+        , role = RenamesColumn+        , rank = -1+        , object = renamed+        , sql = renameSql env.table (old, new)+        , txn = Shared+        , hazards = [MayFail ("breaks running code that still uses the old name" <> foldMap ("; " <>) env.config.renameHint)]+        , key = definitionKey renamed+        , change = Changed def def+        , undo =+            UndoBy+                [ Step+                    { phase = DropPhase+                    , role = RenamesColumn+                    , rank = -1+                    , object = Column env.table old+                    , sql = renameSql env.table (new, old)+                    , txn = Shared+                    , hazards = []+                    , key = definitionKey renamed+                    , change = Changed def def+                    , undo = UndoObject+                    }+                ]+        }+  where+    renamed = Column env.table new+    def = Map.findWithDefault (Printed "") (definitionKey renamed) edit.desired+++-- | The dropped and added columns of the same type, unless renames were given or the+-- user said such a pair is a drop and an add.+renameCandidates :: MigrateOptions -> TableEdit -> [RenameCandidate]+renameCandidates migrate edit =+    [ RenameCandidate{droppedColumn, addedColumn}+    | null (renamesOf migrate.comparison)+    , migrate.sameTypeSwap == AskIfRename+    , (droppedColumn, oldType) <- columnsWhere \case Dropped d -> Just d; _ -> Nothing+    , (addedColumn, newType) <- columnsWhere \case Added d -> Just d; _ -> Nothing+    , oldType == newType+    ]+  where+    columnsWhere side =+        [ (c, def.colType)+        | (k, change) <- Map.toList edit.changes+        , k.aspect == Definition+        , Column _ c <- [k.object]+        , Just def <- [asColumn =<< side change]+        ]+++renameNote :: RenameCandidate -> Text+renameNote candidate =+    let old = nameText candidate.droppedColumn+        new = nameText candidate.addedColumn+     in [i|#{old} is dropped and #{new} added with the same type; pass --rename #{old}:#{new} if it is a rename, or --drop-and-add if it is not|]+++-- | What to say when the file needs no migration.+nothingToMigrate :: TableEnv -> MigrateOptions -> Evidence -> Text+nothingToMigrate env migrate ev+    | WithLiveTable _ <- migrate.comparison = "the file matches the table"+    | not (null ev.branchChanges) = "this branch's changes already cover the file"+    | otherwise = let base = env.opts.base in [i|the file has no schema changes since #{base}|]+++-- | What happens to the objects that use one the edit changes.+data Usage = Usage+    { object :: ObjectId+    , followsRename :: Bool+    -- ^ The object is a column being renamed, which its users follow.+    , usedBy :: [ObjectId]+    , droppedWith :: [ObjectId]+    , recreatedAround :: [ObjectId]+    , breaks :: [(ObjectId, Text)]+    -- ^ Routines whose bodies break, with PostgreSQL's error.+    , unbuildableForeignKeys :: [(ObjectId, Text)]+    -- ^ Foreign keys that cannot be rebuilt with the new type, with PostgreSQL's error.+    , namedIn :: [ObjectId]+    -- ^ Routines that name the object in a body no check covered.+    }+++usageOf :: Effects -> Evidence -> ObjectId -> Usage+usageOf effects ev object =+    Usage+        { object+        , followsRename = object `Set.member` ev.renamedFrom+        , usedBy+        , droppedWith+        , recreatedAround+        , breaks = [(d, why) | d <- Set.toList (routinesNaming object ev.deps <> dependents), Just why <- [Map.lookup d ev.bodies.breaking]]+        , unbuildableForeignKeys = Map.findWithDefault [] object ev.foreignKeyBreaks+        , namedIn = Set.toList (uncheckedNaming ev object)+        }+  where+    dependents = exactDependentsOf object ev.deps+    isDropped = object `Set.member` effects.dropped+    (droppedWith, rest) = L.partition (\d -> isDropped && goesWithColumn effects.table d) (Set.toList dependents)+    (recreatedAround, usedBy) = L.partition (recreatedWith effects object) (filter (`Map.notMember` ev.bodies.breaking) rest)+++-- | The routines that name @object@ and that the body check neither found broken nor+-- passed.+uncheckedNaming :: Evidence -> ObjectId -> Set ObjectId+uncheckedNaming ev object = Set.filter unchecked (routinesNaming object ev.deps)+  where+    unchecked r = r `Map.notMember` ev.bodies.breaking && r `Set.notMember` ev.bodies.passed+++-- | An object is reported when something uses it, breaks or names it; foreign keys that+-- cannot be rebuilt show only along with those.+reported :: Usage -> Bool+reported u = not (null u.usedBy && null u.droppedWith && null u.recreatedAround && null u.breaks && null u.namedIn)+++-- | The usage of every object the edit changes, as report lines.+usageReport :: Effects -> Evidence -> [Text]+usageReport effects ev =+    concatMap (renderUsage (shortName listed))+        . filter reported+        . map (usageOf effects ev)+        $ Set.toList (Map.keysSet ev.deps.exact <> Map.keysSet ev.deps.named)+  where+    listed = fold ev.deps.exact <> foldMap (uncheckedNaming ev) (Map.keys ev.deps.named)+++renderUsage :: (ObjectId -> Text) -> Usage -> [Text]+renderUsage name u =+    T.intercalate "." (toAddress u.object).objectNames+        : objects (if u.followsRename then "used by, and follows the rename" else "used by") u.usedBy+            <> objects "dropped with it" u.droppedWith+            <> objects "dropped and created again around it" u.recreatedAround+            <> explained "breaks" u.breaks+            <> explained "cannot be rebuilt with the new type" u.unbuildableForeignKeys+            <> objects "named in" u.namedIn+  where+    objects :: Text -> [ObjectId] -> [Text]+    objects heading = \case+        [] -> []+        ds -> ("  " <> heading) : map item ds+    explained :: Text -> [(ObjectId, Text)] -> [Text]+    explained heading = \case+        [] -> []+        ds -> ("  " <> heading) : concat [[item d, "      " <> why] | (d, why) <- ds]+    item d = "    " <> name d+++-- | An object's name in the report: a routine by its name, with its arguments only when+-- one of @listed@ shares the name, and anything else by its kind and name.+shortName :: Set ObjectId -> ObjectId -> Text+shortName listed object = kind <> T.intercalate "." address.objectNames <> args+  where+    address = toAddress object+    kind = if isRoutine object then "" else address.objectType <> " "+    args+        | withoutArgs object `Set.member` overloaded = [i|(#{T.intercalate ", " address.objectArgs})|]+        | otherwise = ""+    overloaded = Map.keysSet (Map.filter (> (1 :: Int)) (Map.fromListWith (+) [(withoutArgs a, 1) | a <- Set.toList listed]))+    withoutArgs = \case+        Routine k q _ -> Routine k q []+        a -> a+++-- | For a foreign key on @table@, each of its columns' types paired with the referenced+-- column's, by @typeIn table column@.+foreignKeyTypes :: (QName -> Identifier -> Maybe Text) -> QName -> ConstraintDef -> Maybe [(Text, Text)]+foreignKeyTypes typeIn table def = do+    target <- def.references+    guard (length def.columns == length target.columns && not (null def.columns))+    for (zip def.columns target.columns) \(a, b) -> (,) <$> typeIn table a <*> typeIn target.table b
+ src/Sqiff/App/Table/Rewrite.hs view
@@ -0,0 +1,174 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | The table command's @--rewrite-file@: the deploy file rewritten from the table as a+-- database has it.+module Sqiff.App.Table.Rewrite (+    rewriteFromDatabase,+    changesTableIn,+) where++import Data.Char (isAlphaNum)+import Data.String.Interpolate (i)+import Data.Text.IO qualified as TIO+import Data.Time (getCurrentTime)+import Hasql.Connection qualified as Connection+import RIO+import RIO.Directory (doesFileExist)+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import RIO.Text.Partial qualified as TP+import Sqiff.App.Env (say)+import Sqiff.App.Options (Output (..), TableOptions (..))+import Sqiff.App.Table.Env+import Sqiff.Config (Config (..), Names (..), fill)+import Sqiff.Connection (failWith, withConnection)+import Sqiff.ConnectionString (ConnectionString, redacted)+import Sqiff.Git (showFile)+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Rewrite (Rewrite (..), fileDrift, rewriteFile)+import Sqiff.Script (splitStatements)+import Sqiff.Sqitch (PreviousFile (..), reworkEdited, withProject, writeTracked)+import Sqiff.Sqitch.Check (Tagging (..))+import Sqiff.Sqitch.Layout (Script (..), planPath, scriptPath)+import Sqiff.Sqitch.Plan (SqitchPlan (..), deployedChanges, parsePlan, plannedChanges, readPlan)+import Sqiff.TableEdit (Baseline (..), Drops (..), Live (..), TableEdit (..), columnOrder, compareTable, readOnly)+import Sqiff.Timing (timed)+++-- | Prints the file rewritten to create the table as the database has it, or writes it+-- and reworks the change.+--+-- The table is read from @liveFrom@, read-only, when it is given.+rewriteFromDatabase :: Maybe ConnectionString -> RIO TableEnv ()+rewriteFromDatabase liveFrom = do+    env <- ask+    current <- readFileUtf8 env.file+    withScratch env.db \conn -> case liveFrom of+        Nothing -> rewriteFrom liveFrom current conn (SameDatabase, conn)+        Just name -> withConnection name \c -> do+            liftIO (readOnly c)+            rewriteFrom liveFrom current conn (OtherDatabase c, c)+++-- | 'rewriteFromDatabase' on the scratch connection, with the table as @live@ has it.+rewriteFrom :: Maybe ConnectionString -> Text -> Connection.Connection -> (Live, Connection.Connection) -> RIO TableEnv ()+rewriteFrom liveFrom current conn (live, liveConn) = do+    env <- ask+    let opts = env.opts+        table = env.table+        liveDb = redacted (fromMaybe env.db liveFrom)+    order <- liftIO (columnOrder liveConn table)+    when (null order) $ failWith [i|#{qualified table} is not in #{liveDb}; there is nothing to rewrite the file from|]+    for_ liveFrom \_ -> do+        pending <- undeployedTouching liveConn+        let n = length pending+            names = T.intercalate ", " pending+        unless (null pending) $ failWith [i|#{liveDb} has not deployed #{n} planned changes that touch #{qualified table}, and a rewrite from it would undo them: #{names}|]+    edit <- timed "rewrite.compare" $ liftIO (compareTable conn (LiveTable live ReportDrops) table env.statements)+    ownFiles <-+        fmap Set.fromList+            . filterM (\n -> doesFileExist (scriptPath env.layout Deploy (fill env.config.names.index [("schema", nameText table.schema), ("table", nameText table.name), ("name", nameText n)])))+            $ [q.name | k <- Map.keys edit.current, Index q <- [k.object]]+    let path = env.file+    rewrite <- either (\e -> failWith [i|#{path}: #{e}|]) pure (rewriteFile table ownFiles order edit.current edit.desired current)+    remaining <-+        if rewrite.text == current+            then pure (fileDrift ownFiles edit.desired edit.current)+            else do+                rewritten <- parseFile env.file " as rewritten" rewrite.text+                check <- timed "rewrite.check" $ liftIO (compareTable conn (LiveTable live ReportDrops) table rewritten)+                pure (fileDrift ownFiles check.desired check.current)+    let still = [render k.object <> (if k.aspect == Comment then " (comment)" else "") | k <- Map.keys remaining]+    for_ still \s -> liftIO (TIO.hPutStrLn stderr [i|-- still differs: #{s}|])+    case opts.output of+        PrintMigration -> do+            case (rewrite.text == current, null still) of+                (True, True) -> say "-- the file matches the table"+                (True, False) -> say "-- the file is unchanged; the differences above are left to you"+                (False, _) -> liftIO (TIO.putStr rewrite.text)+            unless (null still) $ exitWith (ExitFailure 1)+        WriteMigration+            | not (null still) -> let n = length still in failWith [i|the rewritten file still differs from the table in #{n} places; nothing written|]+            | rewrite.text == current -> say "nothing to write: the file matches the table"+            | otherwise -> do+                sqitchPlan <- liftIO (readPlan (planPath env.layout))+                basePlan <- liftIO (parsePlan <$> showFile env.repo opts.base (planPath env.layout))+                now <- liftIO getCurrentTime+                let changeName = env.sqitchChange+                    entries p = length (filter (== changeName) p.changes)+                    tagging = Tagging{given = opts.tableTag, now}+                    alreadyReworked = entries sqitchPlan > entries basePlan+                liftIO $ withProject env.layout \project -> do+                    writeTracked project env.file rewrite.text+                    unless alreadyReworked+                        $ reworkEdited project tagging changeName [i|sqiff: #{changeName} as the database has it|] current PreviousFileRuns+                say+                    ( if alreadyReworked+                        then [i|rewrote #{changeName}; the branch already reworks it|]+                        else [i|rewrote and reworked #{changeName}|]+                    )+++-- | The planned changes @live@'s sqitch registry lacks whose deploy scripts name the table.+undeployedTouching :: Connection.Connection -> RIO TableEnv [Text]+undeployedTouching live = do+    env <- ask+    let table = env.table+        touching name = do+            let path = scriptPath env.layout Deploy name+            exists <- doesFileExist path+            if not exists+                then pure (Just [i|#{name} (no deploy file)|])+                else+                    splitStatements <$> readFileUtf8 path <&> \case+                        Left _ -> Just [i|#{name} (its statements could not be read)|]+                        Right statements -> bool Nothing (Just name) (any (changesTableIn table) statements)+    planText <- readFileUtf8 (planPath env.layout)+    deployed <- liftIO (deployedChanges live (parsePlan planText).project)+    when (Set.null deployed) $ failWith "the live database's sqitch registry has no changes of this project"+    let pending = nubOrd [name | c@(name, _) <- plannedChanges planText, c `Set.notMember` deployed]+    catMaybes <$> traverse touching pending+++-- | Whether @statement@ changes @table@: creates, alters, drops or grants on it, or creates+-- or comments on something of its own. A do block counts if it names the table. An+-- unqualified name counts as the table when its name matches: a change that may touch+-- it is treated as one that does.+changesTableIn :: QName -> Text -> Bool+changesTableIn table statement = case ws of+    "alter" : "table" : rest -> startsWithTable (dropWhile (`elem` ["if", "exists", "only"]) rest)+    "drop" : "table" : rest -> anyIn (dropWhile (`elem` ["if", "exists"]) rest)+    "comment" : "on" : "column" : n : _ -> isTable (T.dropWhileEnd (== '.') (T.dropWhileEnd (/= '.') (bare n)))+    "comment" : "on" : "table" : rest -> startsWithTable rest+    "comment" : "on" : _ -> afterOn+    verb : _ | verb `elem` ["grant", "revoke"] -> anyIn (dropWhile (== "table") (drop 1 (dropWhile (/= "on") ws)))+    "create" : rest+        | any (`elem` ["function", "procedure", "view", "materialized"]) (take 3 rest) -> False+        | "table" `elem` take 3 rest -> startsWithTable (dropWhile (`elem` ["if", "not", "exists"]) (drop 1 (dropWhile (/= "table") rest)))+        | otherwise -> afterOn+    "do" : _ -> named+    _ -> False+  where+    ws = T.words (T.toLower (withoutLeadingComments statement))+    bare = T.takeWhile (`notElem` ("(;," :: String))+    unquoted = T.filter (/= '"')+    qualifiedName = T.toLower (dotted table)+    plainName = T.toLower (nameText table.name)+    isTable n = let n' = unquoted (bare n) in n' == qualifiedName || (not ("." `T.isInfixOf` n') && n' == plainName)+    startsWithTable = \case+        n : _ -> isTable n+        [] -> False+    -- A list of names, up to the word after it.+    anyIn = any isTable . concatMap (filter (not . T.null) . T.split (== ',')) . takeWhile (`notElem` ["to", "from", "cascade", "restrict"])+    afterOn = startsWithTable (dropWhile (== "only") (drop 1 (dropWhile (/= "on") ws)))+    named = any mentions (nubOrd [qualifiedName, T.toLower (qualified table), plainName])+    mentions needle = any (\(before, rest) -> boundary (T.takeEnd 1 before) && boundary (T.take 1 (T.drop (T.length needle) rest))) (TP.breakOnAll needle (T.toLower statement))+    boundary t = maybe True (\(c, _) -> not (isAlphaNum c || c == '_' || c == '.')) (T.uncons t)
+ src/Sqiff/Baseline.hs view
@@ -0,0 +1,312 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | A scratch PostgreSQL holding the schema a revision's sqitch plan produces, run from a+-- git worktree at that revision with the revision's own compose file.+module Sqiff.Baseline (withBaseline) where++import Crypto.Hash (SHA256 (..), hashWith)+import Data.Char (isDigit)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import Data.Text.IO qualified as TIO+import GHC.IO.Handle.Lock (LockMode (..), hLock, hTryLock, hUnlock)+import RIO+import RIO.Directory (XdgDirectory (..), canonicalizePath, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, doesPathExist, findExecutable, getXdgDirectory, removeDirectoryRecursive, removeFile)+import RIO.FilePath (takeDirectory, (</>))+import RIO.Map qualified as Map+import Sqiff.Config (BaselineConfig (..), DeployStep (..), Password (..), SqitchPlace (..), fill)+import Sqiff.Connection (failWith)+import Sqiff.ConnectionString (ConnectionString, fromPairs)+import Sqiff.Git (Repo, commonDir, findRepo, git, resolveCommit)+import System.Environment (getEnvironment, lookupEnv)+import System.Process.Typed (ProcessConfig, nullStream, proc, readProcess, runProcess, setEnv, setStdin, setStdout, setWorkingDir, useHandleOpen)+++-- | Where one repository's baseline lives; its worktrees and jj workspaces share it.+data Paths = Paths+    { project :: Text+    , checkout :: FilePath+    , stateFile :: FilePath+    }+++-- | Runs @action@ with the baseline database holding the schema of @rev@'s sqitch plan.+--+-- A lock in the cache keeps runs apart: the database is brought up to date under an+-- exclusive lock, then used under a shared one, so runs that need the same revision share+-- it and a run that needs another waits until they are done.+withBaseline :: BaselineConfig -> Text -> (ConnectionString -> IO a) -> IO a+withBaseline cfg rev action = do+    for_ ["docker", "git"] \tool -> do+        found <- findExecutable tool+        when (isNothing found) $ failWith [i|#{tool} is not on PATH; the baseline database needs it|]+    repo <- findRepo "."+    common <- commonDir repo+    let key = T.take 12 (tshow (hashWith SHA256 (encodeUtf8 (T.pack common))))+    cache <- getXdgDirectory XdgCache ("sqiff" </> T.unpack key)+    createDirectoryIfMissing True cache+    let p = Paths{project = "sqiff-" <> key, checkout = cache </> "checkout", stateFile = cache </> "baseline-state"}+    commit <- resolveCommit repo rev+    let wanted = BaselineState{commit, settings = settingsFingerprint cfg}+    withBinaryFile (cache </> "lock") ReadWriteMode \lock -> do+        let locked :: LockMode -> Text -> IO ()+            locked mode what = do+                free <- hTryLock lock mode+                unless free do+                    note [i|waiting for another sqiff run #{what} the baseline database|]+                    hLock lock mode+            ready = do+                state <- readState p+                running <- doesPathExist (p.checkout </> ".git") >>= bool (pure False) (isRunning cfg p)+                pure (state == Just wanted && running)+            loop = do+                locked ExclusiveLock "using"+                ( do+                        isReady <- ready+                        unless isReady $ bringTo cfg repo common p rev wanted+                    )+                    `finally` hUnlock lock+                -- Another run may bring it elsewhere between the two locks.+                locked SharedLock "changing"+                isReady <- ready `onException` hUnlock lock+                if isReady+                    then (connInfo cfg p >>= action) `finally` hUnlock lock+                    else hUnlock lock >> loop+        loop+++-- | What the baseline database was built from: the commit, and the settings that shape the+-- deploy.+data BaselineState = BaselineState+    { commit :: Text+    , settings :: Text+    }+    deriving stock (Eq)+++readState :: Paths -> IO (Maybe BaselineState)+readState p =+    doesFileExist p.stateFile >>= \case+        False -> pure Nothing+        True ->+            T.lines <$> readFileUtf8 p.stateFile <&> \case+                [commit, settings] -> Just BaselineState{commit, settings}+                _ -> Nothing+++-- | A hash of the settings that decide what the deploy produces, without the password.+settingsFingerprint :: BaselineConfig -> Text+settingsFingerprint cfg =+    T.take 16+        . tshow+        . hashWith SHA256+        . encodeUtf8+        . T.unlines+        $ [ T.pack cfg.composeFile+          , cfg.service+          , tshow cfg.containerPort+          , cfg.user+          , cfg.database+          , case cfg.sqitch of OnHost -> "host"; InService -> "service"+          , tshow (Map.toList cfg.environment)+          , tshow [(step.args, step.ifExists) | step <- cfg.deploy]+          , tshow cfg.status+          ]+++-- | Brings the baseline database to @wanted@: moves the checkout and deploys what the plan+-- adds, or starts from an empty volume when the deploy settings changed or the deployed+-- changes are not all in the plan.+bringTo :: BaselineConfig -> Repo -> FilePath -> Paths -> Text -> BaselineState -> IO ()+bringTo cfg repo common p rev wanted = do+    let commit = wanted.commit+    note [i|bringing the baseline database to #{T.take 12 commit} (#{rev})|]+    previous <- readState p+    whenM (doesFileExist p.stateFile) $ removeFile p.stateFile+    checkoutAt cfg repo common p commit+    when (maybe False ((/= wanted.settings) . (.settings)) previous) do+        note "the baseline settings in sqiff.yaml changed; rebuilding from scratch"+        compose cfg p ["down", "-v"]+    start cfg p+    stale <- staleDeploy cfg p+    when stale do+        note "the deployed changes are not all in this revision's plan; rebuilding from scratch"+        compose cfg p ["down", "-v"]+        start cfg p+    for_ cfg.deploy \step -> do+        present <- maybe (pure True) (doesPathExist . (p.checkout </>)) step.ifExists+        when present $ sqitchIn cfg p step.args+    writeFileUtf8 p.stateFile [i|#{commit}\n#{wanted.settings}\n|]+++note :: Text -> IO ()+note message = TIO.hPutStrLn stderr ("sqiff: " <> message)+++-- | The connection string for the port Docker published the service on.+connInfo :: BaselineConfig -> Paths -> IO ConnectionString+connInfo cfg p = do+    port <- publishedPort cfg p+    password <- passwordOf cfg+    let pairs = [("host", "localhost"), ("port", port), ("user", cfg.user), ("dbname", cfg.database)] <> [("password", pw) | pw <- maybeToList password]+    pure (fromPairs pairs)+++passwordOf :: BaselineConfig -> IO (Maybe Text)+passwordOf cfg = case cfg.password of+    Nothing -> pure Nothing+    Just (PasswordText pw) -> pure (Just pw)+    Just (PasswordVariable var) -> lookupEnv (T.unpack var) >>= maybe (failWith [i|baseline.password-variable names #{var}, which is not set|]) (pure . Just . T.pack)+++publishedPort :: BaselineConfig -> Paths -> IO Text+publishedPort cfg p = do+    let containerPort = cfg.containerPort+    (code, out, err) <- readCompose cfg p ["port", T.unpack cfg.service, show containerPort]+    case T.breakOnEnd ":" out of+        (_, port) | code == ExitSuccess, not (T.null port), T.all isDigit port -> pure port+        _ -> failWith [i|the baseline service publishes no port for #{containerPort}: #{out}#{err}|]+++-- | Creates the git worktree at @commit@, or moves it there. A checkout that is not a+-- worktree of this repository is stopped and replaced; the database volume stays.+checkoutAt :: BaselineConfig -> Repo -> FilePath -> Paths -> Text -> IO ()+checkoutAt cfg repo common p commit =+    ours >>= \case+        True -> do+            let args = ["-C", p.checkout, "checkout", "--quiet", "--force", "--detach", T.unpack commit]+            code <- runProcess (toStderr (proc "git" args))+            unless (code == ExitSuccess) $ failWith [i|git #{unwords args} failed|]+        False -> do+            let checkout = p.checkout+            whenM (doesDirectoryExist checkout) do+                note [i|replacing #{checkout} with a git worktree|]+                whenM (doesFileExist (p.checkout </> cfg.composeFile)) $ compose cfg p ["down"]+                removeDirectoryRecursive p.checkout+            createDirectoryIfMissing True (takeDirectory p.checkout)+            git repo ["worktree", "prune"]+            git repo ["worktree", "add", "--quiet", "--detach", p.checkout, T.unpack commit]+  where+    ours =+        doesPathExist (p.checkout </> ".git") >>= \case+            False -> pure False+            True -> do+                (code, out, _) <- readProcess (quiet (proc "git" ["-C", p.checkout, "rev-parse", "--path-format=absolute", "--git-common-dir"]))+                case code of+                    ExitSuccess -> (== common) <$> canonicalizePath (T.unpack (decode out))+                    ExitFailure _ -> pure False+++-- | Starts the server and waits until it accepts connections over TCP, which it does+-- once the init scripts are done: the image's temporary server for them listens on the+-- Unix socket only. The check runs in the container, so it asks its loopback, on the+-- port the server listens on there.+start :: BaselineConfig -> Paths -> IO ()+start cfg p = do+    compose cfg p ["up", "-d", service]+    awaitReady (0 :: Int)+  where+    service = T.unpack cfg.service+    project = p.project+    awaitReady n = do+        (code, _, _) <- readCompose cfg p ["exec", "-T", service, "pg_isready", "-q", "-h", "127.0.0.1", "-p", show cfg.containerPort]+        unless (code == ExitSuccess) do+            (_, state, _) <- readCompose cfg p ["ps", "-a", "--format", "{{.State}}", service]+            when (T.strip state `elem` ["exited", "dead"] || n >= 900)+                $ failWith [i|the baseline server did not come up; see docker compose -p #{project} logs #{service}|]+            when (n == 5) $ note [i|waiting for the baseline server (docker compose -p #{project} logs -f #{service})|]+            threadDelay 2_000_000+            awaitReady (n + 1)+++-- | Whether sqitch reports deployed changes that the checkout's plan does not have.+staleDeploy :: BaselineConfig -> Paths -> IO Bool+staleDeploy cfg p = do+    (_, out, err) <- readProcess . quiet =<< sqitchProc cfg p cfg.status+    pure ("Cannot find" `T.isInfixOf` decode (out <> err))+++sqitchIn :: BaselineConfig -> Paths -> [Text] -> IO ()+sqitchIn cfg p args = do+    code <- runProcess . toStderr =<< sqitchProc cfg p args+    case code of+        ExitSuccess -> pure ()+        ExitFailure n -> failWith [i|sqitch #{T.unwords args} failed for the baseline database with exit code #{n}|]+++-- | sqitch in the service, or on this machine in the checkout with libpq's variables+-- pointing at the published port. @{host}@, @{port}@, @{user}@ and @{database}@ in the+-- arguments are where that sqitch reaches the baseline.+sqitchProc :: BaselineConfig -> Paths -> [Text] -> IO (ProcessConfig () () ())+sqitchProc cfg p args = do+    password <- passwordOf cfg+    let withPassword = [("PGPASSWORD", T.unpack pw) | pw <- maybeToList password]+        filled port = map (\a -> fill a [("host", "localhost"), ("port", port), ("user", cfg.user), ("database", cfg.database)]) args+    case cfg.sqitch of+        InService -> do+            env <- composeEnv cfg+            let passOn = concat [["-e", "PGPASSWORD"] | isJust password]+                exec = ["exec", "-T"] <> passOn <> [T.unpack cfg.service, "sqitch"]+            pure (setEnv (withPassword <> env) (composeProc cfg p (exec <> map T.unpack (filled (tshow cfg.containerPort)))))+        OnHost -> do+            port <- publishedPort cfg p+            env <- getEnvironment+            let ours = [("PGHOST", "localhost"), ("PGPORT", T.unpack port), ("PGUSER", T.unpack cfg.user), ("PGDATABASE", T.unpack cfg.database)] <> withPassword+                others = filter ((`notElem` (["PGSERVICE", "PGHOSTADDR"] <> map fst ours)) . fst) env+            pure (setEnv (ours <> others) (setWorkingDir p.checkout (quiet (proc "sqitch" (map T.unpack (filled port))))))+++isRunning :: BaselineConfig -> Paths -> IO Bool+isRunning cfg p = do+    (code, out, _) <- readCompose cfg p ["ps", "--status", "running", "-q", T.unpack cfg.service]+    pure (code == ExitSuccess && not (T.null (T.strip out)))+++compose :: BaselineConfig -> Paths -> [String] -> IO ()+compose cfg p args = do+    env <- composeEnv cfg+    code <- runProcess (toStderr (setEnv env (composeProc cfg p args)))+    let project = p.project+    case code of+        ExitSuccess -> pure ()+        ExitFailure n -> failWith [i|docker compose -p #{project} #{unwords args} failed with exit code #{n}|]+++-- [allow:SqiffNamedTuples] pre-existing at adoption+readCompose :: BaselineConfig -> Paths -> [String] -> IO (ExitCode, Text, Text)+readCompose cfg p args = do+    env <- composeEnv cfg+    (code, out, err) <- readProcess (quiet (setEnv env (composeProc cfg p args)))+    pure (code, decode out, decode err)+++-- | The checkout's own compose file, so image, command, init scripts and mounts all come+-- from the revision being built.+composeProc :: BaselineConfig -> Paths -> [String] -> ProcessConfig () () ()+composeProc cfg p args = proc "docker" (["compose", "-p", T.unpack p.project, "-f", p.checkout </> cfg.composeFile] <> args)+++-- | The caller's environment with the configured variables, the port variable (0 lets+-- Docker pick a free port), and without a dev stack's compose settings.+composeEnv :: BaselineConfig -> IO [(String, String)]+composeEnv cfg = do+    env <- getEnvironment+    let ours = [(T.unpack k, T.unpack v) | (k, v) <- Map.toList cfg.environment] <> [(T.unpack v, show cfg.port) | v <- maybeToList cfg.portVariable]+        dropped = map fst ours <> ["COMPOSE_FILE", "COMPOSE_PROJECT_NAME", "COMPOSE_PROFILES"]+    pure (ours <> filter ((`notElem` dropped) . fst) env)+++quiet :: ProcessConfig i o e -> ProcessConfig () o e+quiet = setStdin nullStream+++toStderr :: ProcessConfig i o e -> ProcessConfig () () e+toStderr = setStdout (useHandleOpen stderr) . quiet+++decode :: LByteString -> Text+decode = T.strip . decodeUtf8Lenient . toStrictBytes
+ src/Sqiff/Body.hs view
@@ -0,0 +1,120 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Recreates functions with SQL-standard bodies from their printed text in rolled-back+-- transactions, to see whether that text parses and prints back the same.+module Sqiff.Body (+    BodyCheck (..),+    checkBodies,+    sameDefinition,+) where++import Data.String.Interpolate (i)+import Data.Text qualified as T+import Hasql.Connection qualified as Connection+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Hasql.TH (singletonStatement, vectorStatement)+import RIO+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Vector qualified as V+import Sqiff.Connection (errorText, failWith, qualifiedNames)+import Sqiff.Definition (Definition, printed)+import Sqiff.Model (Address (..), Aspect (..), ObjectKey (..), Schema, fromAddress, isRoutine, toAddress)+++data BodyCheck+    = -- | Recreating from the printed text prints it back unchanged.+      RoundTrips+    | -- | It parses, but prints back as this other text.+      Reprints Text+    | -- | It does not parse; this repaired text does, and prints back the original.+      Repaired Text+    | -- | Neither the printed text nor a repair parses.+      DoesNotParse Text+    deriving stock (Eq, Show)+++-- | Checks every function in @schema@ that has a SQL-standard body; needs a database+-- that accepts writes.+checkBodies :: Connection.Connection -> Schema -> IO (Map ObjectKey BodyCheck)+checkBodies conn schema = qualifiedNames conn do+    sqlBodyFunctions <-+        if any (isRoutine . (.object)) (Map.keys schema)+            then toList <$> run sqlBodies ()+            else pure []+    let keys = Set.fromList [definitionKey (toList names) (toList args) kind | (names, args, kind) <- sqlBodyFunctions]+    Map.traverseWithKey (\k -> roundTrip k . printed) (Map.restrictKeys schema keys)+  where+    definitionKey names args kind = ObjectKey Definition (fromAddress (Address kind names args))++    -- Runs the printed definition and compares it with what PostgreSQL prints back.+    roundTrip k original =+        rolledBack (recreate original *> printDefinition k) >>= \case+            Right reprinted+                | reprinted == original -> pure RoundTrips+                | otherwise -> pure (Reprints reprinted)+            Left parseError -> case repair original of+                Nothing -> pure (DoesNotParse parseError)+                Just repaired -> do+                    fromRepaired <- rolledBack (recreate repaired *> printDefinition k)+                    pure if fromRepaired == Right original then Repaired repaired else DoesNotParse parseError++    run :: Statement.Statement p a -> p -> IO a+    run statement params = Connection.use conn (Session.statement params statement) >>= either (\e -> failWith [i|query failed: #{errorText e}|]) pure++    recreate :: Text -> Session.Session ()+    recreate definition = Session.script (definition <> ";")++    printDefinition :: ObjectKey -> Session.Session Text+    printDefinition k = let addr = toAddress k.object in Session.statement (V.fromList addr.objectNames, V.fromList addr.objectArgs) printedSql++    rolledBack :: Session.Session a -> IO (Either Text a)+    rolledBack session =+        Connection.use conn (Session.script "begin" *> session <* Session.script "rollback") >>= \case+            Right a -> pure (Right a)+            Left err -> do+                void (Connection.use conn (Session.script "rollback"))+                pure . Left . T.take 300 . T.unwords . T.words . errorText $ err++    printedSql :: Statement.Statement (Vector Text, Vector Text) Text+    printedSql =+        [singletonStatement|+            select pg_get_functiondef(to_regprocedure(format('%I.%I(%s)', ($1::text[])[1], ($1::text[])[2], array_to_string($2::text[], ', '))))::text+        |]++    sqlBodies :: Statement.Statement () (Vector (Vector Text, Vector Text, Text))+    sqlBodies =+        [vectorStatement|+            select+                a.object_names::text[]+              , a.object_args::text[]+              , a.type::text+            from pg_proc p+            join pg_namespace n+              on n.oid = p.pronamespace+            cross join lateral pg_identify_object_as_address('pg_proc'::regclass, p.oid, 0) a+            where p.prosqlbody is not null+              and n.nspname <> 'information_schema'+              and n.nspname !~ '^pg_'+        |]+++-- | PostgreSQL can print an @ON CONFLICT@ reference to @EXCLUDED@ as @excluded_1@, which+-- does not parse back.+repair :: Text -> Maybe Text+repair def =+    let fixed = foldl' (\t n -> T.replace [i|excluded_#{n}.|] "excluded." t) def [1 :: Int .. 9]+     in if fixed == def then Nothing else Just fixed+++-- | Two definitions are the same object when the texts match, or when the desired one+-- reprints as the current one: that is what recreating it from its printed text gives.+sameDefinition :: Map ObjectKey BodyCheck -> ObjectKey -> Definition -> Definition -> Bool+sameDefinition checks k current desired =+    current == desired || case Map.lookup k checks of+        Just (Reprints p) -> printed current == p+        _ -> False
+ src/Sqiff/Catalog.hs view
@@ -0,0 +1,256 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Reads a database's schema from its catalog: one definition per object, keyed by+-- @pg_identify_object_as_address@ so the same object matches across databases.+module Sqiff.Catalog (+    CatalogId (..),+    ClassOid (..),+    pgClass,+    pgProc,+    describe,+    Partitions (..),+    Addresses,+    describeOn,+    dependencies,+    dependenciesOn,+    dependenciesFrom,+    edgesBetween,+    relationColumns,+) where++import Data.Aeson qualified as Aeson+import Data.Aeson.Types qualified as Aeson+import Data.FileEmbed (embedDir, embedFile, makeRelativeToProject)+import Data.Functor.Contravariant (contramap)+import Data.String.Interpolate (i)+import Hasql.Connection qualified as Connection+import Hasql.Decoders qualified as D+import Hasql.Encoders qualified as E+import Hasql.Statement qualified as Statement+import Hasql.TH (vectorStatement)+import RIO+import RIO.FilePath (takeBaseName)+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import RIO.Vector qualified as V+import Sqiff.Catalog.Rows+import Sqiff.Connection (failWith, qualifiedNames, run)+import Sqiff.Definition (Definition (..))+import Sqiff.Identifier (Identifier, QName (..), identifier, nameText, qname)+import Sqiff.Model+import Sqiff.Timing (timed)+++describeQueries :: [(FilePath, ByteString)]+describeQueries = $(makeRelativeToProject "sql/describe" >>= embedDir)+++dependQuery :: ByteString+dependQuery = $(makeRelativeToProject "sql/depend.sql" >>= embedFile)+++-- | Each described object, by its catalog ids.+type Addresses = Map CatalogId ObjectId+++-- | Whether partitions and their objects are described.+data Partitions = SkipPartitions | IncludePartitions+    deriving stock (Eq, Show)+++-- | Every object outside system schemas, extension members and the excluded schemas.+describe :: Connection.Connection -> [Text] -> Partitions -> IO Schema+describe conn excluded partitions = fst <$> describeOn [conn] excluded partitions Nothing+++-- | 'describe' with the queries spread over the connections, limited to one table's+-- objects when @onlyTable@ names it, and with each object's catalog ids.+describeOn :: [Connection.Connection] -> [Text] -> Partitions -> Maybe Text -> IO (Schema, Addresses)+describeOn conns excluded partitions onlyTable = do+    queue <- newIORef (maybe ordered (const (map (,Nothing) describeQueries)) onlyTable)+    let next = atomicModifyIORef' queue \case+            [] -> ([], Nothing)+            q : rest -> (rest, Just q)+        worker conn = next >>= maybe (pure []) (\q -> (:) <$> describeOne conn q <*> worker conn)+    parts <- concat <$> forConcurrently conns (\conn -> qualifiedNames conn (worker conn))+    (,) <$> evaluate (Map.unions (map fst parts)) <*> evaluate (Map.unions (map snd parts))+  where+    ordered =+        concat [[(q, Just 0), (q, Just 1)] | q <- byName slowest]+            <> [(q, Nothing) | q <- byName middling <> [q | q@(f, _) <- describeQueries, takeBaseName f `notElem` (slowest <> middling)]]+    slowest = ["column", "privileges", "function"]+    middling = ["constraint", "index", "relation"]+    byName names = [q | n <- names, q@(f, _) <- describeQueries, takeBaseName f == n]++    describeOne conn ((file, body), parity) =+        timed [i|describeQuery #{name} #{maybe "" show parity}|] do+            rows <- run conn (excluded, partitions == IncludePartitions, onlyTable, parity) (describeStatement body)+            definitions <- for rows \(_, object, text) ->+                either (\e -> failWith [i|the catalog's description of #{render object} does not parse: #{e}|]) (pure . (ObjectKey (aspectOf name) object,)) (decodeDefinition name text)+            evaluate+                $ force+                    ( Map.fromList definitions+                    , Map.fromList [(ids, object) | (ids, object, _) <- rows]+                    )+      where+        name = takeBaseName file++    describeStatement body =+        Statement.unpreparable (wrap (decodeUtf8Lenient body)) describeParams+            $ D.rowList ((,,) <$> catalogIdRow <*> objectRow <*> textColumn)++    aspectOf = \case+        "privileges" -> Privileges+        "comment" -> Comment+        _ -> Definition++    -- Most queries describe their objects as JSON; routines, triggers, policies,+    -- schemas and comments are kept as the catalog prints them.+    decodeDefinition :: String -> Text -> Either String Definition+    decodeDefinition = \case+        "column" -> fmap ColumnDefinition . Aeson.eitherDecodeStrict . encodeUtf8+        "privileges" -> fmap AclDefinition . Aeson.eitherDecodeStrict . encodeUtf8+        "index" -> fmap IndexDefinition . Aeson.eitherDecodeStrict . encodeUtf8+        "constraint" -> fmap ConstraintDefinition . Aeson.eitherDecodeStrict . encodeUtf8+        "relation" -> Aeson.eitherDecodeStrict . encodeUtf8 >=> relation+        "sequence" -> fmap SequenceDefinition . Aeson.eitherDecodeStrict . encodeUtf8+        "extension" -> fmap ExtensionDefinition . Aeson.eitherDecodeStrict . encodeUtf8+        "type" -> fmap TypeDefinition . Aeson.eitherDecodeStrict . encodeUtf8+        _ -> Right . Printed+    relation = Aeson.parseEither \v -> flip (Aeson.withObject "relation") v \o ->+        o Aeson..: "kind" >>= \case+            "view" -> ViewDefinition <$> Aeson.parseJSON v+            "table" -> TableDefinition <$> Aeson.parseJSON v+            other -> fail ("unknown relation kind " <> T.unpack other)++    wrap body =+        [i|+            with o as (+            #{body}+            )+            select o.classid::int8, o.objid::int8, o.objsubid::int4, a.type, a.object_names, a.object_args, coalesce(o.definition, '')+            from o+            cross join lateral pg_identify_object_as_address(o.classid, o.objid, o.objsubid) a+            where ($3::text is null or o.relid = to_regclass($3::text))+                and ($4::int4 is null or o.objid::int8 % 2 = $4::int4)+                -- Functions a type makes for itself, such as a range type's constructors,+                -- come and go with the type.+                and not (+                    o.classid = 'pg_proc'::regclass+                    and exists (select from pg_depend d where d.classid = o.classid and d.objid = o.objid and d.deptype = 'i')+                )+                and not exists (+                    select+                    from pg_depend e+                    where e.deptype = 'e'+                        and (+                            (e.classid = o.classid and e.objid = o.objid)+                            or (e.classid = 'pg_class'::regclass and e.objid = o.relid)+                        )+                )+                and (+                    cardinality($1) = 0+                    or not coalesce(+                        coalesce(+                            (select ident.schema from pg_identify_object(o.classid, o.objid, o.objsubid) ident),+                            (select n.nspname::text from pg_class c join pg_namespace n on n.oid = c.relnamespace where c.oid = o.relid),+                            case when a.type = 'schema' then a.object_names[1] end+                        ) = any($1),+                        false+                    )+                )+                and ($2 or not exists (select from pg_class p where p.relispartition and p.oid = o.relid))+        |]+++-- | Edges from @pg_depend@ between described objects.+dependencies :: Connection.Connection -> Addresses -> IO [Edge]+dependencies conn addresses =+    edgesBetween addresses <$> run conn (Map.keys addresses) (Statement.unpreparable (decodeUtf8Lenient dependQuery) catalogIdsParams edgeRows)+++-- | 'dependencies' limited to the edges whose referenced end is one of @targets@.+dependenciesOn :: Connection.Connection -> Addresses -> [CatalogId] -> IO [Edge]+dependenciesOn _ _ [] = pure []+dependenciesOn conn addresses targets =+    timed [i|dependenciesOn n=#{length targets}|]+        $ edgesBetween addresses+        . filter (\(_, referenced) -> referenced `Set.member` targetSet)+        <$> run conn targets (Statement.unpreparable (decodeUtf8Lenient dependOnQuery) catalogIdsParams edgeRows)+  where+    targetSet = Set.fromList targets+++dependOnQuery :: ByteString+dependOnQuery = $(makeRelativeToProject "sql/depend_on.sql" >>= embedFile)+++-- | 'dependencies' limited to the edges reachable from @starts@ through dependents.+dependenciesFrom :: Connection.Connection -> Addresses -> [CatalogId] -> IO [Edge]+dependenciesFrom _ _ [] = pure []+dependenciesFrom conn addresses starts =+    timed [i|dependenciesFrom n=#{length starts}|]+        $ edgesBetween addresses+        <$> run conn starts (Statement.unpreparable (decodeUtf8Lenient dependFromQuery) catalogIdsParams edgeRows)+++dependFromQuery :: ByteString+dependFromQuery = $(makeRelativeToProject "sql/depend_from.sql" >>= embedFile)+++-- | The dependency queries' one row: dependents and referenced objects as six parallel arrays.+edgeRows :: D.Result [(CatalogId, CatalogId)]+edgeRows = D.singleRow (zip <$> catalogIdArrays <*> catalogIdArrays)+  where+    catalogIdArrays = L.zipWith3 CatalogId <$> (map ClassOid <$> int8Array) <*> int8Array <*> int4Array+++-- | The edges whose ends are both described.+edgesBetween :: Addresses -> [(CatalogId, CatalogId)] -> [Edge]+edgesBetween addresses pairs =+    [Edge a b | (x, y) <- pairs, Just a <- [Map.lookup x addresses], Just b <- [Map.lookup y addresses]]+++-- | The column names of the given relations, by schema and name.+relationColumns :: Connection.Connection -> [QName] -> IO (Map QName (Set Identifier))+relationColumns conn relations =+    Map.fromListWith (<>)+        . map (\(s, r, c) -> (qname s r, Set.singleton (identifier c)))+        . toList+        <$> run conn (V.fromList (map (nameText . (.schema)) relations), V.fromList (map (nameText . (.name)) relations)) query+  where+    query :: Statement.Statement (Vector Text, Vector Text) (Vector (Text, Text, Text))+    query =+        [vectorStatement|+            select+                n.nspname::text+              , c.relname::text+              , a.attname::text+            from unnest($1::text[], $2::text[]) u (s, r)+            join pg_namespace n+              on n.nspname = u.s+            join pg_class c+              on c.relnamespace = n.oid+             and c.relname = u.r+            join pg_attribute a+              on a.attrelid = c.oid+             and a.attnum > 0+             and not a.attisdropped+        |]+++-- [allow:SqiffNamedTuples] pre-existing at adoption+describeParams :: E.Params ([Text], Bool, Maybe Text, Maybe Int32)+describeParams =+    contramap (\(excluded, _, _, _) -> excluded) excludedParam+        <> contramap (\(_, includePartitions, _, _) -> includePartitions) (E.param (E.nonNullable E.bool))+        <> contramap (\(_, _, onlyTable, _) -> onlyTable) (E.param (E.nullable E.text))+        <> contramap (\(_, _, _, half) -> half) (E.param (E.nullable E.int4))
+ src/Sqiff/Catalog/PlpgsqlCheck.hs view
@@ -0,0 +1,325 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What plpgsql_check finds in function bodies: the objects they use, and the errors an+-- edit causes in them.+module Sqiff.Catalog.PlpgsqlCheck (+    Skipped,+    BodyUses,+    bodyUses,+    PlFunction (..),+    PlFunctions (..),+    plpgsqlFunctions,+    analyseBodies,+    bodyErrors,+    BodyError (..),+    Outcome (..),+    bodyErrorText,+    tempTableStatements,+) where++import Data.FileEmbed (embedFile, makeRelativeToProject)+import Data.Functor.Contravariant (contramap)+import Data.String.Interpolate (i)+import Hasql.Connection qualified as Connection+import Hasql.Decoders qualified as D+import Hasql.Encoders qualified as E+import Hasql.Errors qualified as Errors+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Hasql.TH (maybeStatement, singletonStatement, vectorStatement)+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import RIO.Text.Partial qualified as TP+import Sqiff.Catalog.Rows+import Sqiff.Connection (errorText, failWith, inRolledBackTransaction, qualifiedNames, run, serverError)+import Sqiff.Sql (doBlock, literal)+import Sqiff.Timing (timed)+++plpgsqlFunctionsQuery :: ByteString+plpgsqlFunctionsQuery = $(makeRelativeToProject "sql/plpgsql/functions.sql" >>= embedFile)+++plpgsqlDependQuery :: ByteString+plpgsqlDependQuery = $(makeRelativeToProject "sql/plpgsql/depend.sql" >>= embedFile)+++plpgsqlTempTablesScript :: ByteString+plpgsqlTempTablesScript = $(makeRelativeToProject "sql/plpgsql/temp_tables.sql" >>= embedFile)+++-- | Functions plpgsql_check could not analyse, with the reason.+type Skipped = [(Text, Text)]+++-- | Pairs of a function and what its body uses, and the functions not analysed.+type BodyUses = ([(CatalogId, CatalogId)], Skipped)+++-- | What PL/pgSQL bodies use, as catalog ids, for the functions in @only@ or all of them;+-- 'Nothing' when plpgsql_check is not installed.+bodyUses :: NonEmpty Connection.Connection -> [Text] -> Maybe (Set Int64) -> IO (Maybe Text) -> IO (Maybe BodyUses)+bodyUses conns@(conn :| _) excluded only madeTempTables =+    plpgsqlFunctions conn excluded >>= traverse \fs -> do+        let checkable = maybe fs.checkable (\oids -> [f | f <- fs.checkable, f.oid `Set.member` oids]) only+        (uses, failed) <- analyseBodies conns fs{tempTables = madeTempTables >>= maybe fs.tempTables pure} checkable+        pure (uses, fs.unchecked <> failed)+++-- | The statements temp_tables.sql runs on a connection without temp tables; 'Nothing'+-- when PostgreSQL refuses the script, so the script itself is run instead, or when+-- plpgsql_check is not installed. Losing the connection is an error.+tempTableStatements :: Connection.Connection -> IO (Maybe Text)+tempTableStatements conn =+    timed "tempTableStatements"+        $ run conn () plpgsqlCheckSchema+        >>= \case+            Nothing -> pure Nothing+            Just extSchema -> do+                result <-+                    inRolledBackTransaction conn "the temp table script" $ Connection.use conn do+                        Session.script (TP.replace "@extschema@" extSchema (decodeUtf8Lenient plpgsqlTempTablesScript))+                        Session.statement () [singletonStatement| select coalesce(current_setting('sqiff.temp_tables', true), '') :: text |]+                case result of+                    Right statements -> pure (Just ("set client_min_messages = error;\n" <> statements))+                    Left e+                        | isJust (serverError e) -> pure Nothing+                        | otherwise -> failWith [i|the temp table script failed: #{errorText e}|]+++-- | A PL/pgSQL function plpgsql_check can analyse: its oid, name, trigger table and+-- estimated cost.+data PlFunction = PlFunction+    { oid :: Int64+    , name :: Text+    , relid :: Maybe Int64+    , cost :: Int64+    }+++-- | The PL/pgSQL functions to analyse, the ones that cannot be, and the functions behind+-- user-defined casts and operators.+data PlFunctions = PlFunctions+    { query :: Text+    , tempTables :: IO Text+    , checkable :: [PlFunction]+    , unchecked :: Skipped+    , implicit :: [Int64]+    }+++-- | The PL/pgSQL functions the describe queries cover; 'Nothing' when plpgsql_check is+-- not installed.+plpgsqlFunctions :: Connection.Connection -> [Text] -> IO (Maybe PlFunctions)+plpgsqlFunctions conn excluded =+    timed "plpgsqlFunctions"+        $ qualifiedNames conn+        $ run conn () plpgsqlCheckSchema+        >>= traverse \extSchema -> do+            functions <- run conn excluded (Statement.unpreparable (decodeUtf8Lenient plpgsqlFunctionsQuery) excludedParam (D.rowList functionRow))+            implicit <- toList <$> run conn () implicitQuery+            let (unchecked, checkable) = partitionEithers (map triggerTable functions)+            let withSchema = TP.replace "@extschema@" extSchema . decodeUtf8Lenient+            pure PlFunctions{query = withSchema plpgsqlDependQuery, tempTables = pure (withSchema plpgsqlTempTablesScript), checkable, unchecked, implicit}+  where+    implicitQuery =+        [vectorStatement|+            select castfunc::int8+            from pg_cast+            where castfunc >= 16384+            union+            select oprcode::int8+            from pg_operator+            where oprcode >= 16384+        |]+    functionRow = (,,,,) <$> D.column (D.nonNullable D.int8) <*> textColumn <*> D.column (D.nonNullable D.bool) <*> D.column (D.nullable D.int8) <*> int8Column+    triggerTable (oid, name, isTrigger, relid, cost)+        | isTrigger && isNothing relid = Left (name, "no trigger uses it")+        | otherwise = Right (PlFunction oid name relid cost)+++-- | What the bodies of @functions@ use, and the ones plpgsql_check failed on, in the+-- order of @fs@, the slowest analysed first.+analyseBodies :: NonEmpty Connection.Connection -> PlFunctions -> [PlFunction] -> IO BodyUses+analyseBodies conns fs functions = do+    let+        (slow, fast) = L.partition ((> 0) . (.cost)) functions+    queue <- newIORef (map pure (L.sortOn (Down . (.cost)) slow) <> chunks fast)+    let next = atomicModifyIORef' queue \case+            [] -> ([], Nothing)+            b : rest -> (rest, Just b)+        batch c b = let firstName = maybe "" (\f -> f.name) (listToMaybe b) in (:) <$> timed [i|analyse.batch n=#{length b} first=#{firstName}|] (inBatches c fs.query b) <*> work c+        work c = next >>= maybe (pure []) (batch c)+        worker c =+            next >>= \case+                Nothing -> pure []+                Just b -> do+                    void (timed "analyse.tempTables" $ fs.tempTables >>= Connection.use c . Session.script)+                    batch c b `finally` void (Connection.use c (Session.script "discard temp; reset client_min_messages"))+    results <- concat <$> forConcurrently (toList conns) worker+    let position = Map.fromList (zip [f.name | f <- fs.checkable] [0 :: Int ..])+        failed = L.sortOn (\(name, _) -> Map.lookup name position) (concatMap snd results)+    pure (concatMap fst results, failed)+  where+    chunks xs = case L.splitAt batchSize xs of+        ([], _) -> []+        (b, rest) -> b : chunks rest++    batchSize = 16++    inBatches _ _ [] = pure ([], [])+    inBatches c query batch =+        Connection.use c (Session.statement batch (Statement.unpreparable query dependParams (D.rowList useRow)))+            >>= \case+                Right uses -> pure ([(CatalogId pgProc f 0, CatalogId (ClassOid k) o 0) | (f, k, o) <- uses], [])+                Left (Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError _ message _ _ _)))+                    | [f] <- batch -> pure ([], [(f.name, message)])+                    | otherwise -> do+                        let (left, right) = L.splitAt (length batch `div` 2) batch+                        (e1, s1) <- inBatches c query left+                        (e2, s2) <- inBatches c query right+                        pure (e1 <> e2, s1 <> s2)+                Left e -> failWith [i|query failed: #{errorText e}|]++    dependParams =+        contramap (map (.oid)) (E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int8))))+            <> contramap (map (.relid)) (E.param (E.nonNullable (E.foldableArray (E.nullable E.int8))))++    useRow = (,,) <$> int8Column <*> int8Column <*> int8Column+++-- | What checking one function's body found.+data BodyError = BodyError+    { signature :: Text+    , line :: Int32+    -- ^ 0 when the error is not on a line of the body.+    , outcome :: Outcome+    , message :: Text+    }+++-- | Whether the body was checked and found wrong, or could not be checked.+data Outcome = Fails | NotChecked+    deriving stock (Eq, Show)+++-- | Errors compare as their function, line and text, so one function's errors keep the+-- order they had as text.+instance Eq BodyError where+    a == b = errorOrder a == errorOrder b+++instance Ord BodyError where+    compare = comparing errorOrder+++-- [allow:SqiffNamedTuples] a sort key: errors compare as this triple+errorOrder :: BodyError -> (Text, Int32, Text)+errorOrder e = (e.signature, e.line, bodyErrorText e)+++-- | The error as the report shows it.+bodyErrorText :: BodyError -> Text+bodyErrorText e = case e.outcome of+    Fails -> e.message+    NotChecked -> "not checked: " <> e.message+++-- | plpgsql_check's errors for these signatures in the transaction @conn@ is in;+-- 'Nothing' when plpgsql_check is not installed.+bodyErrors :: Connection.Connection -> Text -> Text -> IO (Maybe Text) -> [Text] -> [Text] -> IO (Maybe (Set BodyError))+bodyErrors conn aside table made signatures sqlSignatures =+    run conn () plpgsqlCheckSchema+        >>= traverse \extSchema -> do+            tempTables <- made >>= maybe (pure (TP.replace "@extschema@" extSchema (decodeUtf8Lenient plpgsqlTempTablesScript))) pure+            made' <- timed "bodyErrors.tempTables" $ guarded (Connection.use conn (Session.script tempTables))+            recompiled <- if null signatures then pure (Right ()) else timed "bodyErrors.recompile" $ guarded (Connection.use conn (Session.script recompile))+            plErrors <- case (made', recompiled) of+                (Left e, _) -> pure [[notChecked s ("plpgsql_check's temp tables could not be made: " <> errorText e) | s <- signatures]]+                (_, Left e) -> pure [[notChecked s ("the functions could not be recompiled: " <> errorText e) | s <- signatures]]+                _ -> for (chunks signatures) (timed "bodyErrors.batch" . inBatches extSchema)+            sqlErrors <- for sqlSignatures \signature ->+                either (\e -> [BodyError{signature, line = 0, outcome = Fails, message = errorText e}]) (const [])+                    <$> timed ("bodyErrors.sql " <> signature) (guarded (Connection.use conn (Session.statement signature validate)))+            pure (Set.fromList (concat (plErrors <> sqlErrors)))+  where+    validate = [singletonStatement| select pg_catalog.fmgr_sql_validator(to_regprocedure($1 :: text)) :: text? |]+    recompile =+        let list = T.intercalate ", " (map literal signatures)+         in doBlock+                [i|+declare f record;+begin+    for f in select p.oid::regprocedure as signature, p.prosecdef from pg_proc p where p.oid in (select to_regprocedure(s) from unnest(array[#{list}]::text[]) s) loop+        execute format('alter routine %s %s', f.signature, case when f.prosecdef then 'security definer' else 'security invoker' end);+    end loop;+end |]+    guarded action = do+        savepoint "savepoint sqiff_check"+        result <- action+        savepoint (either (const "rollback to savepoint sqiff_check") (const "release savepoint sqiff_check") result)+        pure result+    savepoint sql = Connection.use conn (Session.script sql) >>= either (\e -> failWith [i|the body check lost its transaction: #{errorText e}|]) pure+    inBatches _ [] = pure []+    inBatches extSchema batch =+        guarded (Connection.use conn (Session.statement (batch, table) (Statement.unpreparable (query extSchema) params decoder))) >>= \case+            Right errors -> pure errors+            Left e@(Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _))+                | [s] <- batch -> pure [notChecked s (errorText e)]+            Left e+                | [_] <- batch -> failWith [i|the body check failed: #{errorText e}|]+                | otherwise -> do+                    let (left, right) = L.splitAt (length batch `div` 2) batch+                    (<>) <$> inBatches extSchema left <*> inBatches extSchema right+    chunks xs = case L.splitAt 16 xs of+        ([], _) -> []+        (b, rest) -> b : chunks rest+    params = contramap fst (E.param (E.nonNullable (E.foldableArray (E.nonNullable E.text)))) <> contramap snd (E.param (E.nonNullable E.text))+    notChecked signature message = BodyError{signature, line = 0, outcome = NotChecked, message}+    decoder = D.rowList ((\signature line message -> BodyError{signature, line, outcome = Fails, message}) <$> textColumn <*> D.column (D.nonNullable D.int4) <*> textColumn)+    query extSchema =+        [i|+            select s.signature, e.lineno, e.message+            from unnest($1::text[]) with ordinality s (signature, n)+            cross join lateral (+                select coalesce(c.lineno, 0)::int4 as lineno, c.message+                from pg_proc f+                left join lateral (select t.tgrelid, t.tgoldtable, t.tgnewtable from pg_trigger t where t.tgfoid = f.oid order by t.oid limit 1) t on true+                cross join lateral #{extSchema}.plpgsql_check_function_tb(+                    f.oid::regprocedure,+                    coalesce(+                        case+                            when (select n.nspname from pg_class k join pg_namespace n on n.oid = k.relnamespace where k.oid = t.tgrelid) = #{literal aside} then to_regclass($2)+                            else t.tgrelid::regclass+                        end,+                        0::regclass+                    ),+                    fatal_errors => false,+                    oldtable => t.tgoldtable,+                    newtable => t.tgnewtable+                ) c+                where f.oid = to_regprocedure(s.signature)+                    and not (f.prorettype = 'trigger'::regtype and t.tgrelid is null)+                    and c.level = 'error'+            ) e+            order by s.n+        |]+++-- | The schema plpgsql_check is installed in, if it is.+plpgsqlCheckSchema :: Statement.Statement () (Maybe Text)+plpgsqlCheckSchema =+    [maybeStatement|+        select extnamespace::regnamespace::text+        from pg_extension+        where extname = 'plpgsql_check'+    |]
+ src/Sqiff/Catalog/Rows.hs view
@@ -0,0 +1,88 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Catalog ids and the encoders and decoders the catalog queries share.+module Sqiff.Catalog.Rows (+    ClassOid (..),+    pgClass,+    pgProc,+    CatalogId (..),+    excludedParam,+    catalogIdsParams,+    catalogIdRow,+    int8Column,+    int8Array,+    int4Array,+    objectRow,+    textColumn,+    textArrayColumn,+) where++import Data.Functor.Contravariant (contramap)+import Hasql.Decoders qualified as D+import Hasql.Encoders qualified as E+import RIO+import Sqiff.Model (Address (..), ObjectId, fromAddress)+++-- | The oid of a system catalog, such as @pg_class@.+newtype ClassOid = ClassOid Int64+    deriving newtype (Eq, Ord, Show, NFData)+++pgClass, pgProc :: ClassOid+pgClass = ClassOid 1259+pgProc = ClassOid 1255+++-- | An object's class, object and sub-object id, as in @pg_depend@.+data CatalogId = CatalogId+    { classId :: ClassOid+    , objectOid :: Int64+    , subId :: Int32+    }+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++excludedParam :: E.Params [Text]+excludedParam = E.param (E.nonNullable (E.foldableArray (E.nonNullable E.text)))+++-- | Catalog ids as three parallel arrays: classes, objects and sub-objects.+catalogIdsParams :: E.Params [CatalogId]+catalogIdsParams =+    contramap (map (\c -> let ClassOid oid = c.classId in oid)) (E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int8))))+        <> contramap (map (.objectOid)) (E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int8))))+        <> contramap (map (.subId)) (E.param (E.nonNullable (E.foldableArray (E.nonNullable E.int4))))+++catalogIdRow :: D.Row CatalogId+catalogIdRow = CatalogId <$> (ClassOid <$> int8Column) <*> int8Column <*> D.column (D.nonNullable D.int4)+++int8Column :: D.Row Int64+int8Column = D.column (D.nonNullable D.int8)+++int8Array :: D.Row [Int64]+int8Array = D.column (D.nonNullable (D.listArray (D.nonNullable D.int8)))+++int4Array :: D.Row [Int32]+int4Array = D.column (D.nonNullable (D.listArray (D.nonNullable D.int4)))+++-- | An object as @pg_identify_object_as_address@ names it, parsed.+objectRow :: D.Row ObjectId+objectRow = fmap fromAddress (Address <$> textColumn <*> textArrayColumn <*> textArrayColumn)+++textColumn :: D.Row Text+textColumn = D.column (D.nonNullable D.text)+++textArrayColumn :: D.Row [Text]+textArrayColumn = D.column (D.nonNullable (D.listArray (D.nonNullable D.text)))
+ src/Sqiff/Config.hs view
@@ -0,0 +1,211 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | The project's @sqiff.yaml@, and the sqitch layout from @sqitch config@.+module Sqiff.Config (+    Config (..),+    Names (..),+    BaselineConfig (..),+    Password (..),+    SqitchPlace (..),+    DeployStep (..),+    loadConfig,+    configFile,+    fill,+    match,+) where++import Data.Aeson (FromJSON (..), Object, withObject, withText, (.!=), (.:), (.:?))+import Data.Aeson.Key qualified as Key+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Aeson.Types (Parser, parseEither)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import Data.Yaml qualified as Yaml+import RIO hiding (view)+import RIO.Directory (doesFileExist)+import RIO.FilePath ((</>))+import RIO.Map qualified as Map+import Sqiff.Connection (failWith)+++data Config = Config+    { excludeSchemas :: [Text]+    , renameHint :: Maybe Text+    , templates :: Maybe FilePath+    , names :: Names+    , baseline :: BaselineConfig+    }+++-- | Change names by kind of object, with @{schema}@, @{name}@ and @{table}@ filled in;+-- a migration's has @{stamp}@ (formatted by 'migrationStamp') and @{slug}@.+data Names = Names+    { table :: Text+    , function :: Text+    , view :: Text+    , trigger :: Text+    , index :: Text+    , type_ :: Text+    , migration :: Text+    , migrationStamp :: Text+    }+++data BaselineConfig = BaselineConfig+    { composeFile :: FilePath+    , service :: Text+    , portVariable :: Maybe Text+    , port :: Int+    , containerPort :: Int+    , environment :: Map Text Text+    , user :: Text+    , database :: Text+    , password :: Maybe Password+    , sqitch :: SqitchPlace+    , deploy :: [DeployStep]+    , status :: [Text]+    }+++-- | The baseline's password, as written or from a variable in sqiff's environment.+data Password = PasswordText Text | PasswordVariable Text+++-- | Where the baseline's sqitch runs: on this machine against the published port, or+-- inside the compose service.+data SqitchPlace = OnHost | InService+    deriving stock (Eq)+++-- | One sqitch call that deploys the baseline; skipped when @ifExists@ is missing from+-- the checkout.+data DeployStep = DeployStep+    { args :: [Text]+    , ifExists :: Maybe FilePath+    }+++configFile :: FilePath+configFile = "sqiff.yaml"+++-- | @dir@'s @sqiff.yaml@, or the defaults when it has none.+loadConfig :: FilePath -> IO Config+loadConfig dir = do+    let path = dir </> configFile+    doesFileExist path >>= \case+        False -> either (\e -> failWith [i|the default settings: #{e}|]) pure (parseEither parseJSON (Yaml.Object mempty))+        True ->+            Yaml.decodeFileEither path >>= \case+                Left e -> failWith [i|#{path}: #{Yaml.prettyPrintParseException e}|]+                Right c -> pure c+++instance FromJSON Config where+    parseJSON = withObject "sqiff.yaml" \o -> do+        known ["exclude-schemas", "rename-hint", "templates", "names", "baseline"] o+        excludeSchemas <- o .:? "exclude-schemas" .!= []+        renameHint <- o .:? "rename-hint"+        templates <- o .:? "templates"+        names <- o .:? "names" .!= Yaml.Object mempty >>= parseJSON+        baseline <- o .:? "baseline" .!= Yaml.Object mempty >>= parseJSON+        pure Config{excludeSchemas, renameHint, templates, names, baseline}+++instance FromJSON Names where+    parseJSON = withObject "names" \o -> do+        known ["table", "function", "view", "trigger", "index", "type", "migration", "migration-stamp"] o+        table <- o .:? "table" .!= "{schema}/table/{name}"+        function <- o .:? "function" .!= "{schema}/function/{name}"+        view <- o .:? "view" .!= "{schema}/view/{name}"+        trigger <- o .:? "trigger" .!= "{schema}/trigger/{table}/{name}"+        index <- o .:? "index" .!= "{schema}/table/{table}/index/{name}"+        type_ <- o .:? "type" .!= "{schema}/type/{name}"+        migration <- o .:? "migration" .!= "migrations/{stamp}-{slug}"+        migrationStamp <- o .:? "migration-stamp" .!= "%Y/%m/%Y-%m-%d-%H%M%S"+        pure Names{table, function, view, trigger, index, type_, migration, migrationStamp}+++instance FromJSON BaselineConfig where+    parseJSON = withObject "baseline" \o -> do+        known ["compose-file", "service", "port-variable", "port", "container-port", "environment", "user", "database", "password", "password-variable", "sqitch", "deploy", "status"] o+        composeFile <- o .:? "compose-file" .!= "docker-compose.yaml"+        service <- o .:? "service" .!= "postgres"+        portVariable <- o .:? "port-variable"+        port <- o .:? "port" .!= 0+        containerPort <- o .:? "container-port" .!= 5432+        environment <- o .:? "environment" .!= Map.empty+        user <- o .:? "user" .!= "postgres"+        database <- o .:? "database" .!= "postgres"+        password <-+            (,) <$> o .:? "password" <*> o .:? "password-variable" >>= \case+                (Just _, Just _) -> fail "set password or password-variable, not both"+                (written, variable) -> pure (PasswordText <$> written <|> PasswordVariable <$> variable)+        sqitch <- o .:? "sqitch" .!= OnHost+        deploy <- o .:? "deploy" .!= [DeployStep ["deploy"] Nothing]+        status <- o .:? "status" .!= ["status"]+        pure BaselineConfig{composeFile, service, portVariable, port, containerPort, environment, user, database, password, sqitch, deploy, status}+++instance FromJSON SqitchPlace where+    parseJSON = withText "sqitch" \case+        "host" -> pure OnHost+        "service" -> pure InService+        other -> fail [i|sqitch is host or service, not #{other}|]+++instance FromJSON DeployStep where+    parseJSON = withObject "deploy step" \o -> do+        known ["sqitch", "if-exists"] o+        DeployStep <$> o .: "sqitch" <*> o .:? "if-exists"+++-- | Refuses keys this version does not read, so a misspelt setting is not ignored.+known :: [Text] -> Object -> Parser ()+known keys o = case [k | k <- map Key.toText (KeyMap.keys o), k `notElem` keys] of+    [] -> pure ()+    unknown -> let ks = T.intercalate ", " unknown in fail [i|unknown settings: #{ks}|]+++-- | @pattern@ with each @{key}@ replaced by its value, in one pass, so a value is never+-- read as a placeholder itself; a key without a value stays as written.+fill :: Text -> [(Text, Text)] -> Text+fill pattern values = T.concat (map piece (templatePieces pattern))+  where+    piece = \case+        Left text -> text+        Right key -> fromMaybe [i|{#{key}}|] (lookup key values)+++-- | The values @pattern@'s placeholders take in @text@; a placeholder matches one or more+-- characters other than @/@.+match :: Text -> Text -> Maybe [(Text, Text)]+match pattern text = go (templatePieces pattern) text+  where+    go [] rest = if T.null rest then Just [] else Nothing+    go (Left literal : ps) rest = T.stripPrefix literal rest >>= go ps+    go (Right key : ps) rest =+        let candidates = case ps of+                Left literal : _ -> [(T.take n rest, T.drop n rest) | (before, _) <- breaks literal rest, let n = T.length before]+                _ -> [(rest, "")]+         in listToMaybe+                [ (key, value) : bound+                | (value, after) <- candidates+                , not (T.null value)+                , not ("/" `T.isInfixOf` value)+                , Just bound <- [go ps after]+                ]+    breaks literal rest = [(T.dropEnd (T.length r) rest, r) | r <- T.tails rest, literal `T.isPrefixOf` r]+++-- | A template's literal text and its @{key}@ placeholders, in order.+templatePieces :: Text -> [Either Text Text]+templatePieces p = case T.breakOn "{" p of+    (literal, "") -> [Left literal | not (T.null literal)]+    (literal, rest) ->+        let (key, after) = T.breakOn "}" (T.drop 1 rest)+         in [Left literal | not (T.null literal)] <> [Right key] <> templatePieces (T.drop 1 after)
+ src/Sqiff/Connection.hs view
@@ -0,0 +1,161 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Connections to PostgreSQL, opened and released in scopes, and the one-line failures+-- the command line reports.+module Sqiff.Connection (+    UserError (..),+    failWith,+    connect,+    withConnection,+    withConnections,+    inRolledBackTransaction,+    withSharedSnapshot,+    run,+    qualifiedNames,+    errorText,+    errorPosition,+    serverError,+) where++import Data.String.Interpolate (i)+import Hasql.Connection qualified as Connection+import Hasql.Connection.Settings qualified as Settings+import Hasql.Errors qualified as Errors+import Hasql.Session qualified as Session+import Hasql.Statement qualified as Statement+import Hasql.TH (singletonStatement)+import Pqi.Ffi qualified+import RIO+import RIO.Text qualified as T+import Sqiff.ConnectionString (ConnectionString, libpqText)+++-- | A failure the command line reports as one line.+newtype UserError = UserError Text+    deriving stock (Show)+++instance Exception UserError+++failWith :: MonadIO m => Text -> m a+failWith = throwIO . UserError . T.unwords . T.words+++connect :: ConnectionString -> IO Connection.Connection+connect conninfo =+    Connection.acquire Pqi.Ffi.adapter (Settings.connectionString (libpqText conninfo))+        >>= either (\e -> failWith ("could not connect: " <> firstLine (reason e))) pure+  where+    reason = \case+        Errors.NetworkingConnectionError t -> t+        Errors.AuthenticationConnectionError t -> t+        Errors.CompatibilityConnectionError t -> t+        Errors.OtherConnectionError t -> t+    firstLine = T.takeWhile (/= '\n')+++-- | Runs @action@ in a transaction that is always rolled back; @label@ names it in errors.+-- When @action@ succeeds the rollback must too, as the connection's state is unknown+-- otherwise. When @action@ fails, its error is the one that counts.+inRolledBackTransaction :: Connection.Connection -> Text -> IO a -> IO a+inRolledBackTransaction conn label action = do+    script "begin" "could not start"+    result <- action `onException` tryAny (Connection.use conn (Session.script "rollback"))+    script "rollback" "could not be rolled back"+    pure result+  where+    script :: Text -> Text -> IO ()+    script sql failed = Connection.use conn (Session.script sql) >>= either (\e -> failWith [i|#{label} #{failed}: #{errorText e}|]) pure+++-- | Runs @action@ with every connection in one repeatable-read transaction on the same+-- snapshot, exported by the first, so reads spread over them see one state of the+-- database. The transactions are rolled back afterwards.+withSharedSnapshot :: NonEmpty Connection.Connection -> IO a -> IO a+withSharedSnapshot conns@(exporter :| rest) action = do+    -- The connections whose transaction started, to roll back if anything fails. When the+    -- thread is cancelled instead, hasql has aborted them already and the connections are+    -- about to be released.+    started <- newIORef []+    let begin c sql = do+            script c sql+            atomicModifyIORef' started (\cs -> (c : cs, ()))+        rollbackStarted e =+            unless (isAsyncException (e :: SomeException))+                $ readIORef started+                >>= traverse_ (\c -> tryAny (Connection.use c (Session.script "rollback")))+    ( do+            begin exporter "begin isolation level repeatable read"+            snapshot <-+                Connection.use exporter (Session.statement () [singletonStatement| select pg_export_snapshot()::text |])+                    >>= either (\e -> failWith [i|could not share a snapshot: #{errorText e}|]) pure+            for_ rest \c -> begin c [i|begin isolation level repeatable read; set transaction snapshot '#{snapshot}'|]+        )+        `withException` rollbackStarted+    result <- action `withException` rollbackStarted+    for_ conns (`script` "rollback")+    pure result+  where+    script :: Connection.Connection -> Text -> IO ()+    script c sql = Connection.use c (Session.script sql) >>= either (\e -> failWith [i|#{sql} failed: #{errorText e}|]) pure+++-- | Runs @action@ with a connection that is released when it returns or fails.+withConnection :: MonadUnliftIO m => ConnectionString -> (Connection.Connection -> m a) -> m a+withConnection db = bracket (liftIO (connect db)) (liftIO . Connection.release)+++-- | Runs @action@ with @n@ connections, opened at the same time, at least one; all that+-- opened are released when it returns or fails, also when another failed to open.+withConnections :: MonadUnliftIO m => ConnectionString -> Int -> (NonEmpty Connection.Connection -> m a) -> m a+withConnections db n action =+    bracket (newIORef []) (liftIO . (traverse_ Connection.release <=< readIORef)) \opened -> do+        let open = liftIO $ mask_ do+                c <- connect db+                atomicModifyIORef' opened (\cs -> (c : cs, ()))+                pure c+        (c, cs) <- concurrently open (replicateConcurrently (max 0 (n - 1)) open)+        action (c :| cs)+++run :: Connection.Connection -> params -> Statement.Statement params a -> IO a+run conn params statement =+    Connection.use conn (Session.statement params statement)+        >>= either (\e -> failWith [i|query failed: #{errorText e}|]) pure+++-- | Runs @action@ with an empty @search_path@, which schema-qualifies the names the catalog+-- functions print.+qualifiedNames :: Connection.Connection -> IO a -> IO a+qualifiedNames conn action = do+    previous <- run conn () [singletonStatement| select current_setting('search_path') :: text |]+    void (run conn "" setPath)+    action `finally` void (Connection.use conn (Session.statement previous setPath))+  where+    setPath = [singletonStatement| select set_config('search_path', $1 :: text, false) :: text |]+++-- | The message of an error the server raised; 'Nothing' for connection and client errors.+serverError :: Errors.SessionError -> Maybe Text+serverError e = case e of+    Errors.ScriptSessionError _ _ -> Just (errorText e)+    Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError _) -> Just (errorText e)+    _ -> Nothing+++errorText :: Errors.SessionError -> Text+errorText = \case+    Errors.ScriptSessionError _ (Errors.ServerError _ message detail _ _) -> message <> maybe "" ("; " <>) detail+    Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError _ message detail _ _)) -> message <> maybe "" ("; " <>) detail+    e -> tshow e+++-- | Where in the SQL the server put the error, as a 1-based character index.+errorPosition :: Errors.SessionError -> Maybe Int+errorPosition = \case+    Errors.ScriptSessionError _ (Errors.ServerError _ _ _ _ position) -> position+    Errors.StatementSessionError _ _ _ _ _ (Errors.ServerStatementError (Errors.ServerError _ _ _ _ position)) -> position+    _ -> Nothing
+ src/Sqiff/ConnectionString.hs view
@@ -0,0 +1,110 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Where a database is, as libpq takes it, with a redacted form that never shows the+-- password.+module Sqiff.ConnectionString (+    ConnectionString,+    connectionString,+    fromPairs,+    libpqText,+    redacted,+) where++import Data.Char (isSpace)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+++-- | A libpq connection string, in keyword or URI form.+data ConnectionString+    = -- | The empty string: libpq's environment (@PGHOST@, @PGDATABASE@, a service file)+      -- names the database.+      FromEnvironment+    | ConnInfo Text+    deriving stock (Eq)+++-- | Shows the redacted form, so a password cannot reach a log through 'show'.+instance Show ConnectionString where+    show = T.unpack . redacted+++instance Display ConnectionString where+    textDisplay = redacted+++connectionString :: Text -> ConnectionString+connectionString t+    | T.all isSpace t = FromEnvironment+    | otherwise = ConnInfo t+++-- | A keyword connection string from its settings, each value quoted.+fromPairs :: [(Text, Text)] -> ConnectionString+fromPairs pairs = ConnInfo (T.unwords [[i|#{k}='#{escape v}'|] | (k, v) <- pairs])+  where+    escape = T.replace "'" "\\'" . T.replace "\\" "\\\\"+++-- | The text to give libpq.+libpqText :: ConnectionString -> Text+libpqText = \case+    FromEnvironment -> ""+    ConnInfo t -> t+++-- | The connection string for messages: the password replaced by @***@.+redacted :: ConnectionString -> Text+redacted = \case+    FromEnvironment -> "the database PGHOST, PGPORT and PGDATABASE name"+    ConnInfo t+        | any (`T.isPrefixOf` t) ["postgres://", "postgresql://"] -> redactUri t+        | otherwise -> redactKeywords t+++-- | @postgresql://user:secret\@host/db?password=secret@ without either secret.+redactUri :: Text -> Text+redactUri t =+    let (scheme, rest) = T.breakOnEnd "://" t+        (authority, path) = T.break (`elem` ("/?" :: String)) rest+        authority' = case T.breakOn "@" authority of+            (userInfo, at)+                | not (T.null at)+                , (user, colon) <- T.breakOn ":" userInfo+                , not (T.null colon) ->+                    [i|#{user}:***#{at}|]+            _ -> authority+        (beforeQuery, query) = T.breakOn "?" path+        query' = case T.stripPrefix "?" query of+            Just params -> "?" <> T.intercalate "&" (map redactParam (T.split (== '&') params))+            Nothing -> query+        redactParam p = case T.breakOn "=" p of+            (key, value) | key == "password", not (T.null value) -> "password=***"+            _ -> p+     in scheme <> authority' <> beforeQuery <> query'+++-- | @host=h password='a secret'@ as @host=h password=***@; values may be quoted.+redactKeywords :: Text -> Text+redactKeywords = go+  where+    go t = case T.breakOn "password" t of+        (before, "") -> before+        (before, at) ->+            let afterKey = T.drop (T.length "password") at+                (spaces, rest) = T.span isSpace afterKey+                startsKey = T.null before || isSpace (T.last before)+             in case T.stripPrefix "=" rest of+                    Just value | startsKey -> [i|#{before}password=***#{go (dropValue (T.stripStart value))}|]+                    _ -> [i|#{before}password#{spaces}#{go rest}|]+    dropValue v = case T.uncons v of+        Just ('\'', quoted) -> closing quoted+        _ -> T.dropWhile (not . isSpace) v+    closing v = case T.uncons v of+        Nothing -> ""+        Just ('\\', rest) -> closing (T.drop 1 rest)+        Just ('\'', rest) -> rest+        Just (_, rest) -> closing rest
+ src/Sqiff/Definition.hs view
@@ -0,0 +1,801 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What the catalog says about an object's aspect. Columns and grants arrive as+-- structured data and are decoded once, where the catalog is read; every other kind is+-- kept as the text the catalog prints.+--+-- 'printed' renders any definition as text, for messages, files and line diffs.+module Sqiff.Definition (+    Definition (..),+    printed,+    mapText,+    mapNames,+    asColumn,+    asTable,+    asView,+    asIndex,+    asConstraint,+    asSequence,+    asExtension,+    asType,+    asAcl,++    -- * Columns+    ColumnDef (..),+    columnTypeChanged,+    Collation (..),+    collationSql,+    Position (..),+    positionNumber,+    Nullability (..),+    Validity (..),+    ColumnValue (..),+    IdentityKind (..),+    Storage (..),+    columnText,+    identityKindSql,+    storageSql,+    defaultExpr,+    isNotNull,+    notNullValid,+    notNullName,+    identityKindOf,+    identityOptionsOf,+    generatedOf,+    failsOnRows,++    -- * Relations+    TableDef (..),+    PartitionOf (..),+    tableText,+    ViewDef (..),+    ViewColumns (..),+    viewColumns,+    extendsColumns,+    viewText,+    withOptions,++    -- * Indexes and constraints+    IndexDef (..),+    ConstraintDef (..),+    ConstraintKind (..),+    ForeignKeyTarget (..),+    withoutValidity,++    -- * Sequences, extensions and types+    SequenceDef (..),+    sequenceOptions,+    ExtensionDef (..),+    TypeDef (..),++    -- * Privileges+    Acl (..),+    Grant (..),+    Grantor (..),+    Grantee (..),+    aclText,+    granteeSql,+) where++import Data.Aeson (FromJSON (..), Value (Null, String), withObject, (.!=), (.:), (.:?))+import Data.Aeson.Types (Parser)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import RIO.List qualified as L+import RIO.Set qualified as Set+import Sqiff.Identifier+import Sqiff.Sql (literal)+++-- | One aspect of one object.+data Definition+    = ColumnDefinition ColumnDef+    | AclDefinition Acl+    | TableDefinition TableDef+    | ViewDefinition ViewDef+    | IndexDefinition IndexDef+    | ConstraintDefinition ConstraintDef+    | SequenceDefinition SequenceDef+    | ExtensionDefinition ExtensionDef+    | TypeDefinition TypeDef+    | -- | As the catalog prints it: a @create@ statement, an expression, a comment.+      Printed Text+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | The definition as text, in the form @sqiff describe@ writes.+printed :: Definition -> Text+printed = \case+    ColumnDefinition c -> columnText c+    AclDefinition acl -> aclText acl+    TableDefinition t -> tableText t+    ViewDefinition v -> viewText v+    IndexDefinition ix -> ix.statement+    ConstraintDefinition c -> c.clause+    SequenceDefinition q -> sequenceText q+    ExtensionDefinition (ExtensionDef version schema) -> [i|version #{version} schema #{quoted schema}|]+    TypeDefinition t -> typeDefText t+    Printed t -> t+++-- | The definition with every piece of SQL text in it changed by @f@: expressions and+-- types, not names.+mapText :: (Text -> Text) -> Definition -> Definition+mapText f = \case+    ColumnDefinition c ->+        ColumnDefinition+            c+                { colType = typeName (f (typeText c.colType))+                , value = case c.value of+                    PlainColumn e -> PlainColumn (f <$> e)+                    GeneratedColumn storage e -> GeneratedColumn storage (f e)+                    identity -> identity+                }+    AclDefinition acl -> AclDefinition acl+    TableDefinition t ->+        TableDefinition+            t+                { partitionBy = f <$> t.partitionBy+                , partitionOf = (\p -> p{bound = f p.bound}) <$> t.partitionOf+                }+    ViewDefinition v -> ViewDefinition v{query = f v.query}+    IndexDefinition ix -> IndexDefinition ix{statement = f ix.statement}+    ConstraintDefinition c -> ConstraintDefinition c{clause = f c.clause}+    TypeDefinition (DomainType base notNull dflt) -> TypeDefinition (DomainType (typeName (f (typeText base))) notNull (f <$> dflt))+    def@(SequenceDefinition _) -> def+    def@(ExtensionDefinition _) -> def+    def@(TypeDefinition _) -> def+    Printed t -> Printed (f t)+++-- | The definition with each schema-qualified name in it changed by @f@: an index's+-- table, a foreign key's, a partition's parent.+mapNames :: (QName -> QName) -> Definition -> Definition+mapNames f = \case+    TableDefinition t -> TableDefinition t{partitionOf = (\p -> p{parent = f p.parent}) <$> t.partitionOf}+    IndexDefinition (IndexDef table unique partitioned statement) -> IndexDefinition (IndexDef (f table) unique partitioned statement)+    ConstraintDefinition c -> ConstraintDefinition c{references = (\(ForeignKeyTarget table columns) -> ForeignKeyTarget (f table) columns) <$> c.references}+    SequenceDefinition q -> SequenceDefinition q{ownedBy = (\(table, column) -> (f table, column)) <$> q.ownedBy}+    def -> def+++asColumn :: Definition -> Maybe ColumnDef+asColumn = \case+    ColumnDefinition c -> Just c+    _ -> Nothing+++asTable :: Definition -> Maybe TableDef+asTable = \case+    TableDefinition t -> Just t+    _ -> Nothing+++asView :: Definition -> Maybe ViewDef+asView = \case+    ViewDefinition v -> Just v+    _ -> Nothing+++asIndex :: Definition -> Maybe IndexDef+asIndex = \case+    IndexDefinition ix -> Just ix+    _ -> Nothing+++asConstraint :: Definition -> Maybe ConstraintDef+asConstraint = \case+    ConstraintDefinition c -> Just c+    _ -> Nothing+++asSequence :: Definition -> Maybe SequenceDef+asSequence = \case+    SequenceDefinition q -> Just q+    _ -> Nothing+++asExtension :: Definition -> Maybe ExtensionDef+asExtension = \case+    ExtensionDefinition e -> Just e+    _ -> Nothing+++asType :: Definition -> Maybe TypeDef+asType = \case+    TypeDefinition t -> Just t+    _ -> Nothing+++asAcl :: Definition -> Maybe Acl+asAcl = \case+    AclDefinition acl -> Just acl+    _ -> Nothing+++-- | A table column, as @alter table ... add column@ would declare it.+data ColumnDef = ColumnDef+    { colType :: TypeName+    , collation :: Maybe Collation+    -- ^ Only when it is not the type's own.+    , nullability :: Nullability+    , value :: ColumnValue+    , rewritesOnAdd :: Bool+    -- ^ Adding the column rewrites the table: its default is volatile, or its type a+    -- domain with constraints.+    , position :: Position+    , inheritedOnly :: Bool+    -- ^ The table has it only because a parent does, so it comes and goes with the parent's.+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | Whether a column's type changes from @old@ to @new@: its type or its collation.+columnTypeChanged :: ColumnDef -> ColumnDef -> Bool+columnTypeChanged old new = old.colType /= new.colType || old.collation /= new.collation+++-- | Where a column sits in its table (@attnum@), so a new table gets its columns in+-- order. It is not part of the column's definition: every position equals every other,+-- so the same column compares equal in two databases that added their columns in+-- different orders. Sort by 'positionNumber'.+newtype Position = Position Int+    deriving stock (Show)+    deriving newtype (NFData)+++instance Eq Position where+    _ == _ = True+++instance Ord Position where+    compare _ _ = EQ+++positionNumber :: Position -> Int+positionNumber (Position n) = n+++data Nullability+    = Nullable+    | -- | A not-null constraint, with its name when PostgreSQL would not give it that one.+      NotNull Validity (Maybe Identifier)+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++data Validity = Validated | NotValidated+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | Where a column's values come from; a column has at most one of these.+data ColumnValue+    = -- | Written, or the default expression when there is one.+      PlainColumn (Maybe Text)+    | -- | With its sequence options that differ from the defaults, such as @increment by 5@.+      IdentityColumn IdentityKind [Text]+    | GeneratedColumn Storage Text+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++data IdentityKind = Always | ByDefault+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++data Storage = Stored | Virtual+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++identityKindSql :: IdentityKind -> Text+identityKindSql = \case+    Always -> "always"+    ByDefault -> "by default"+++storageSql :: Storage -> Text+storageSql = \case+    Stored -> "stored"+    Virtual -> "virtual"+++defaultExpr :: ColumnDef -> Maybe Text+defaultExpr c = case c.value of+    PlainColumn e -> e+    _ -> Nothing+++isNotNull :: ColumnDef -> Bool+isNotNull c = case c.nullability of+    NotNull _ _ -> True+    Nullable -> False+++-- | Whether the not-null constraint, if there is one, is validated.+notNullValid :: ColumnDef -> Bool+notNullValid c = case c.nullability of+    NotNull NotValidated _ -> False+    _ -> True+++notNullName :: ColumnDef -> Maybe Identifier+notNullName c = case c.nullability of+    NotNull _ name -> name+    Nullable -> Nothing+++identityKindOf :: ColumnDef -> Maybe IdentityKind+identityKindOf c = case c.value of+    IdentityColumn kind _ -> Just kind+    _ -> Nothing+++identityOptionsOf :: ColumnDef -> [Text]+identityOptionsOf c = case c.value of+    IdentityColumn _ options -> options+    _ -> []+++generatedOf :: ColumnDef -> Maybe (Storage, Text)+generatedOf c = case c.value of+    GeneratedColumn storage e -> Just (storage, e)+    _ -> Nothing+++-- | Adding the column fails on a table with rows: it is not null and has no value to fill in.+failsOnRows :: ColumnDef -> Bool+failsOnRows c = isNotNull c && c.value == PlainColumn Nothing+++-- | A collation, by its schema unless it is one of pg_catalog's.+data Collation = Collation+    { schema :: Maybe Identifier+    , name :: Identifier+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++collationSql :: Collation -> Text+collationSql c = maybe "" (\s -> quoted s <> ".") c.schema <> quoted c.name+++instance FromJSON Collation where+    parseJSON v = case v of+        -- A name alone, as sqiff wrote it before it kept the schema.+        String n -> pure (Collation Nothing (identifier n))+        _ -> withObject "collation" (\o -> Collation <$> (fmap identifier <$> o .:? "schema") <*> (identifier <$> o .: "name")) v+++-- | The column as text, one fact per line.+columnText :: ColumnDef -> Text+columnText c =+    T.intercalate "\n"+        $ ["type " <> typeText c.colType]+        <> ["collate " <> collationSql co | Just co <- [c.collation]]+        <> case c.nullability of+            Nullable -> []+            NotNull validity name ->+                let notValid = if validity == NotValidated then " not valid" else "" :: Text+                    constraint = maybe "" ((" constraint " <>) . nameText) name+                 in [[i|not null#{notValid}#{constraint}|]]+        <> case c.value of+            PlainColumn e -> ["default " <> x | Just x <- [e]]+            IdentityColumn kind options ->+                ["identity " <> identityKindSql kind] <> ["identity options " <> T.intercalate ", " options | not (null options)]+            GeneratedColumn storage e -> [[i|generated #{storageSql storage} #{e}|]]+        <> ["rewrites the table when added" | c.rewritesOnAdd]+++instance FromJSON ColumnDef where+    parseJSON = withObject "column" \o -> do+        colType <- typeName <$> o .: "type"+        collation <- o .:? "collation"+        notNull <- o .:? "not_null"+        nullability <- case notNull of+            Nothing -> pure Nullable+            Just n -> withObject "not null" (\nn -> NotNull <$> (bool NotValidated Validated <$> nn .: "validated") <*> (fmap identifier <$> nn .:? "name")) n+        identity <- o .:? "identity"+        generated <- o .:? "generated"+        expression <- o .:? "expression"+        value <- case (identity, generated) of+            (Just kind, Nothing) -> IdentityColumn <$> identityKind kind <*> o .:? "identity_options" .!= []+            (Nothing, Just storage) -> GeneratedColumn <$> storageKind storage <*> maybe (fail "a generated column without an expression") pure expression+            (Nothing, Nothing) -> pure (PlainColumn expression)+            (Just _, Just _) -> fail "a column cannot be both an identity and generated"+        rewritesOnAdd <- o .:? "rewrites_on_add" .!= False+        position <- Position <$> o .:? "position" .!= 0+        inheritedOnly <- o .:? "inherited" .!= False+        pure ColumnDef{colType, collation, nullability, value, rewritesOnAdd, position, inheritedOnly}+      where+        identityKind :: Text -> Parser IdentityKind+        identityKind = \case+            "always" -> pure Always+            "by default" -> pure ByDefault+            other -> fail ("unknown identity kind " <> T.unpack other)+        storageKind :: Text -> Parser Storage+        storageKind = \case+            "stored" -> pure Stored+            "virtual" -> pure Virtual+            other -> fail ("unknown generated column kind " <> T.unpack other)+++-- | A table's settings; its columns and constraints are objects of their own.+data TableDef = TableDef+    { unlogged :: Bool+    , partitionBy :: Maybe Text+    -- ^ The partition key, as @pg_get_partkeydef@ prints it.+    , partitionOf :: Maybe PartitionOf+    , rowSecurity :: Bool+    , forceRowSecurity :: Bool+    , options :: [Text]+    -- ^ Storage options such as @fillfactor=70@; the TOAST table's with a @toast.@ prefix.+    , inherits :: [QName]+    -- ^ Parents by @inherits@, in order.+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++newtype InheritedFrom = InheritedFrom QName+++instance FromJSON InheritedFrom where+    parseJSON = withObject "parent" \p -> InheritedFrom <$> (qname <$> p .: "schema" <*> p .: "name")+++data PartitionOf = PartitionOf+    { parent :: QName+    , bound :: Text+    -- ^ As @pg_get_expr@ prints it, such as @FOR VALUES FROM (0) TO (10)@.+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | @with (a=1, b=2)@, or nothing for no options.+withOptions :: [Text] -> Maybe Text+withOptions = \case+    [] -> Nothing+    options -> let list = T.intercalate ", " options in Just [i|with (#{list})|]+++tableText :: TableDef -> Text+tableText t =+    T.intercalate "\n"+        $ ["unlogged" | t.unlogged]+        <> ["partition by " <> key | Just key <- [t.partitionBy]]+        <> [[i|partition of #{qualified parent} #{bound}|] | Just (PartitionOf parent bound) <- [t.partitionOf]]+        <> ["inherits " <> qualified p | p <- t.inherits]+        <> ["row level security" | t.rowSecurity]+        <> ["force row level security" | t.forceRowSecurity]+        <> maybeToList (withOptions t.options)+++-- | A view or materialized view.+data ViewDef = ViewDef+    { options :: Maybe [Text]+    -- ^ Nothing when the view has no options at all.+    , query :: Text+    -- ^ As @pg_get_viewdef@ prints it.+    , columns :: ViewColumns+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | A view's columns, names and types in order. They follow from its query, so they are+-- not part of its definition: every list equals every other, as a view over a retyped+-- column is not itself changed. A recipe reads them with 'viewColumns'.+newtype ViewColumns = ViewColumns [(Identifier, TypeName)]+    deriving stock (Show)+    deriving newtype (NFData)+++instance Eq ViewColumns where+    _ == _ = True+++viewColumns :: ViewDef -> [(Identifier, TypeName)]+viewColumns v = let ViewColumns cs = v.columns in cs+++-- | Whether @new@ keeps @old@'s columns as they are, adding any at the end, which is what+-- @create or replace view@ allows.+extendsColumns :: ViewDef -> ViewDef -> Bool+extendsColumns old new = viewColumns old `L.isPrefixOf` viewColumns new+++viewText :: ViewDef -> Text+viewText v = T.intercalate "\n" ([[i|with (#{T.intercalate ", " o})|] | Just o <- [v.options]] <> [v.query])+++data IndexDef = IndexDef+    { table :: QName+    , unique :: Bool+    , partitioned :: Bool+    -- ^ On a partitioned table, where it is created @ON ONLY@ the parent.+    , statement :: Text+    -- ^ As @pg_get_indexdef@ prints it.+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++data ConstraintKind = Check | ForeignKey | PrimaryKey | Unique | Exclusion+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | A table's or domain's constraint.+data ConstraintDef = ConstraintDef+    { kind :: ConstraintKind+    , validity :: Validity+    , columns :: [Identifier]+    -- ^ The table's columns it covers, in order; none for a domain's.+    , references :: Maybe ForeignKeyTarget+    , clause :: Text+    -- ^ As @pg_get_constraintdef@ prints it, @NOT VALID@ included.+    , inheritedOnly :: Bool+    -- ^ The table has it only because a parent does.+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++data ForeignKeyTarget = ForeignKeyTarget+    { table :: QName+    , columns :: [Identifier]+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | The constraint as it is once validated.+withoutValidity :: ConstraintDef -> ConstraintDef+withoutValidity c = c{validity = Validated, clause = fromMaybe c.clause (T.stripSuffix " NOT VALID" c.clause)}+++instance FromJSON TableDef where+    parseJSON = withObject "table" \o ->+        TableDef+            <$> o+            .: "unlogged"+            <*> o+            .:? "partition_by"+            <*> (o .:? "partition_of" >>= traverse (withObject "partition of" \p -> PartitionOf <$> (qname <$> p .: "schema" <*> p .: "name") <*> p .: "bound"))+            <*> o+            .: "row_security"+            <*> o+            .: "force_row_security"+            <*> o+            .:? "options"+            .!= []+            <*> (map (\(InheritedFrom q) -> q) <$> o .:? "inherits" .!= [])+++instance FromJSON ViewDef where+    parseJSON = withObject "view" \o -> do+        columns <- o .:? "columns" .!= []+        ViewDef+            <$> o+            .:? "options"+            <*> o+            .: "query"+            <*> pure (ViewColumns [(identifier n, typeName t) | (n, t) <- columns])+++instance FromJSON IndexDef where+    parseJSON = withObject "index" \o ->+        IndexDef+            <$> (qname <$> o .: "table_schema" <*> o .: "table_name")+            <*> o+            .: "unique"+            <*> o+            .: "partitioned"+            <*> o+            .: "statement"+++instance FromJSON ConstraintDef where+    parseJSON = withObject "constraint" \o -> do+        kind <-+            o .: "kind" >>= \case+                "c" -> pure Check+                "f" -> pure ForeignKey+                "p" -> pure PrimaryKey+                "u" -> pure Unique+                "x" -> pure Exclusion+                other -> fail ("unknown constraint kind " <> T.unpack other)+        validity <- bool NotValidated Validated <$> o .: "validated"+        columns <- map identifier <$> o .:? "columns" .!= []+        references <- o .:? "references" >>= traverse (withObject "references" \r -> ForeignKeyTarget <$> (qname <$> r .: "schema" <*> r .: "table") <*> (map identifier <$> r .: "columns"))+        clause <- o .: "clause"+        inheritedOnly <- o .:? "inherited" .!= False+        pure ConstraintDef{kind, validity, columns, references, clause, inheritedOnly}+++-- | A sequence that is not an identity column's.+data SequenceDef = SequenceDef+    { dataType :: TypeName+    , increment :: Integer+    , minValue :: Integer+    , maxValue :: Integer+    , start :: Integer+    , cache :: Integer+    , cycles :: Bool+    , ownedBy :: Maybe (QName, Identifier)+    -- ^ The column whose drop takes the sequence with it.+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | The options @create sequence@ and @alter sequence@ take, all of them spelled out.+sequenceOptions :: SequenceDef -> Text+sequenceOptions q =+    T.unwords+        [ "as " <> typeText q.dataType+        , "increment by " <> tshow q.increment+        , "minvalue " <> tshow q.minValue+        , "maxvalue " <> tshow q.maxValue+        , "start with " <> tshow q.start+        , "cache " <> tshow q.cache+        , if q.cycles then "cycle" else "no cycle"+        ]+++sequenceText :: SequenceDef -> Text+sequenceText q = sequenceOptions q <> foldMap (\(t, c) -> [i| owned by #{qualified t}.#{quoted c}|]) q.ownedBy+++data ExtensionDef = ExtensionDef+    { version :: Text+    , schema :: Identifier+    }+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++-- | A user-defined type; a domain's constraints are objects of their own.+data TypeDef+    = -- | The labels, in order.+      EnumType [Text]+    | -- | The base type, whether it is not null, and its default.+      DomainType TypeName Bool (Maybe Text)+    | -- | The attributes and their types.+      CompositeType [(Identifier, TypeName)]+    | -- | The options @create type ... as range@ takes, the subtype first, the defaults+      -- left out.+      RangeType [(Text, Text)]+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++typeDefText :: TypeDef -> Text+typeDefText = \case+    EnumType labels -> let list = T.intercalate ", " (map literal labels) in [i|enum (#{list})|]+    DomainType base notNull dflt -> T.unwords (["domain " <> typeText base] <> ["not null" | notNull] <> ["default " <> d | Just d <- [dflt]])+    CompositeType attributes -> let list = T.intercalate ", " [[i|#{quoted a} #{typeText t}|] | (a, t) <- attributes] in [i|composite (#{list})|]+    RangeType options -> let list = T.intercalate ", " [[i|#{k} = #{v}|] | (k, v) <- options] in [i|range (#{list})|]+++instance FromJSON SequenceDef where+    parseJSON = withObject "sequence" \o ->+        SequenceDef+            <$> (typeName <$> o .: "type")+            <*> o+            .: "increment"+            <*> o+            .: "min"+            <*> o+            .: "max"+            <*> o+            .: "start"+            <*> o+            .: "cache"+            <*> o+            .: "cycle"+            <*> (o .:? "owned_by" >>= traverse (withObject "owner" \w -> (,) <$> (qname <$> w .: "schema" <*> w .: "table") <*> (identifier <$> w .: "column")))+++instance FromJSON ExtensionDef where+    parseJSON = withObject "extension" \o -> ExtensionDef <$> o .: "version" <*> (identifier <$> o .: "schema")+++instance FromJSON TypeDef where+    parseJSON = withObject "type" \o ->+        o .: "kind" >>= \case+            "enum" -> EnumType <$> o .:? "labels" .!= []+            "domain" -> DomainType <$> (typeName <$> o .: "base") <*> o .: "not_null" <*> o .:? "default"+            "composite" -> CompositeType . map (\(a, t) -> (identifier a, typeName t)) <$> o .:? "attributes" .!= []+            "range" -> do+                subtype <- o .: "subtype"+                RangeType . filter (not . T.null . snd) <$> o .:? "options" .!= [("subtype", subtype)]+            other -> fail ("unknown kind of type " <> T.unpack other)+++-- | An object's privileges.+data Acl+    = -- | No ACL: the defaults for the kind of object and its owner.+      DefaultAcl+    | -- | These grants exactly, the owner's own included.+      ExplicitAcl (Set Grant)+    deriving stock (Eq, Show, Generic)+    deriving anyclass (NFData)+++data Grant = Grant+    { grantee :: Grantee+    , privilege :: Text+    -- ^ As @aclexplode@ names it, such as @SELECT@.+    , grantable :: Bool+    , grantor :: Grantor+    }+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++-- | Who gave a grant: the object's owner, whoever that is in each database, or another+-- role, which passes on a privilege it holds with the grant option.+data Grantor = ByOwner | ByRole Identifier+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++data Grantee = Public | Role Identifier+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++granteeSql :: Grantee -> Text+granteeSql = \case+    Public -> "public"+    Role r -> quoted r+++-- | One line per grant, in order: @role PRIVILEGE[ with grant option][ granted by role]@.+aclText :: Acl -> Text+aclText = \case+    DefaultAcl -> "default"+    ExplicitAcl grants -> T.intercalate "\n" (L.sort (map line (Set.toList grants)))+  where+    line g =+        let who = granteeText g.grantee+            option = if g.grantable then " with grant option" else "" :: Text+            by = case g.grantor of+                ByOwner -> ""+                ByRole r -> " granted by " <> nameText r+         in [i|#{who} #{g.privilege}#{option}#{by}|]+    granteeText = \case+        Public -> "public"+        Role r -> nameText r+++-- | @null@ for the defaults, else the list of grants.+instance FromJSON Acl where+    parseJSON v+        | v == Null = pure DefaultAcl+        | otherwise = ExplicitAcl . Set.fromList <$> parseJSON v+++instance FromJSON Grant where+    parseJSON = withObject "grant" \o ->+        Grant+            <$> (maybe Public (Role . identifier) <$> o .:? "grantee")+            <*> o+            .: "privilege"+            <*> o+            .: "grantable"+            <*> (maybe ByOwner (ByRole . identifier) <$> o .:? "grantor")
+ src/Sqiff/Dependencies.hs view
@@ -0,0 +1,85 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Which objects depend on which, indexed once so each question about it is a lookup.+module Sqiff.Dependencies (+    Dependencies,+    indexEdges,+    noDependencies,+    edges,+    restrictedTo,+    directDependents,+    dependentsOf,+    referencesOf,+    dependsOn,+    reachableFrom,+) where++import RIO+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Graph (reachedFrom)+import Sqiff.Identifier (QName)+import Sqiff.Model (Edge (..), ObjectId (..), isRelation)+++-- | The edges between objects, by what they reference and by what depends on them.+data Dependencies = Dependencies+    { edgeList :: [Edge]+    , dependents :: Map ObjectId (Set ObjectId)+    , references :: Map ObjectId (Set ObjectId)+    , columnsUsed :: Map QName (Set ObjectId)+    -- ^ For each relation, its columns that something depends on.+    }+++indexEdges :: [Edge] -> Dependencies+indexEdges es =+    Dependencies+        { edgeList = es+        , dependents = Map.fromListWith (<>) [(e.referenced, Set.singleton e.dependent) | e <- es]+        , references = Map.fromListWith (<>) [(e.dependent, Set.singleton e.referenced) | e <- es]+        , columnsUsed = Map.fromListWith (<>) [(t, Set.singleton e.referenced) | e <- es, Column t _ <- [e.referenced]]+        }+++-- | No object depends on another.+noDependencies :: Dependencies+noDependencies = indexEdges []+++-- | Every edge, as the catalog gave them.+edges :: Dependencies -> [Edge]+edges = (.edgeList)+++-- | Only the edges whose two ends are both in @known@.+restrictedTo :: Set ObjectId -> Dependencies -> Dependencies+restrictedTo known deps = indexEdges [e | e <- deps.edgeList, e.dependent `Set.member` known, e.referenced `Set.member` known]+++-- | What depends on the object itself.+directDependents :: Dependencies -> ObjectId -> Set ObjectId+directDependents deps object = Map.findWithDefault Set.empty object deps.dependents+++-- | What depends on the object; for a relation, also what depends on its columns.+dependentsOf :: Dependencies -> ObjectId -> Set ObjectId+dependentsOf deps object = directDependents deps object <> foldMap (directDependents deps) columns+  where+    columns = maybe Set.empty (\t -> Map.findWithDefault Set.empty t deps.columnsUsed) (isRelation object)+++-- | What the object depends on directly.+referencesOf :: Dependencies -> ObjectId -> Set ObjectId+referencesOf deps object = Map.findWithDefault Set.empty object deps.references+++-- | Whether @dependent@ depends on @referenced@ directly.+dependsOn :: Dependencies -> ObjectId -> ObjectId -> Bool+dependsOn deps dependent referenced = referenced `Set.member` referencesOf deps dependent+++-- | Everything that depends on @starts@, directly or through others, by 'dependentsOf'.+reachableFrom :: Dependencies -> Set ObjectId -> Set ObjectId+reachableFrom deps = reachedFrom (Set.toList . dependentsOf deps)
+ src/Sqiff/Diff.hs view
@@ -0,0 +1,190 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++module Sqiff.Diff (+    Change (..),+    Changes,+    invert,+    before,+    after,+    diff,+    affected,+    BodyText (..),+    bodyText,+    BodyCandidate (..),+    bodiesToAnalyse,+) where++import Data.Map.Merge.Strict qualified as Merge+import RIO+import RIO.Char (isAlphaNum)+import RIO.HashSet qualified as HS+import RIO.Map qualified as Map+import RIO.NonEmpty qualified as L+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.Definition (Definition)+import Sqiff.Dependencies (Dependencies, directDependents, reachableFrom, restrictedTo)+import Sqiff.Graph (reachedFrom)+import Sqiff.Identifier (QName (..), TypeName, nameText, typeText)+import Sqiff.Model+++-- | How one aspect of one object differs between two schemas.+data Change a+    = Added a+    | Dropped a+    | Changed a a+    deriving stock (Eq, Show, Functor, Foldable, Traversable)+++-- | What differs between two schemas.+type Changes = Map ObjectKey (Change Definition)+++-- | The change that undoes this one.+invert :: Change a -> Change a+invert = \case+    Added new -> Dropped new+    Dropped old -> Added old+    Changed old new -> Changed new old+++-- | The definition a change starts from, if there was one.+before :: Change a -> Maybe a+before = \case+    Dropped old -> Just old+    Changed old _ -> Just old+    Added _ -> Nothing+++-- | The definition a change leaves, if it leaves one.+after :: Change a -> Maybe a+after = \case+    Added new -> Just new+    Changed _ new -> Just new+    Dropped _ -> Nothing+++-- | What turns @from@ into @to@, with @same key old new@ deciding when two definitions match.+diff :: Eq a => (ObjectKey -> a -> a -> Bool) -> Map ObjectKey a -> Map ObjectKey a -> Map ObjectKey (Change a)+diff same =+    Merge.merge+        (Merge.mapMissing \_ old -> Dropped old)+        (Merge.mapMissing \_ new -> Added new)+        (Merge.zipWithMaybeMatched \k old new -> if same k old new then Nothing else Just (Changed old new))+++-- | For each dropped or changed definition, the objects in @known@ that depend on it,+-- directly or through others, and whose definitions are not in the diff themselves.+affected :: Set ObjectId -> Dependencies -> Map ObjectKey (Change a) -> Map ObjectId (Set ObjectId)+affected known deps changes =+    Map.filter (not . Set.null)+        $ Map.fromList+            [ (key.object, closure key.object `Set.difference` inDiff)+            | (key, change) <- Map.toList changes+            , key.aspect == Definition+            , removesOrChanges change+            ]+  where+    -- Objects whose own definition changes are planned by their own recipes; one whose+    -- comment or grants change still stands in the way.+    inDiff = Set.fromList [k.object | k <- Map.keys changes, k.aspect == Definition]++    amongKnown = restrictedTo known deps+    closure start = reachedFrom (Set.toList . directDependents amongKnown) (Set.singleton start)++    removesOrChanges = \case+        Added _ -> False+        Dropped _ -> True+        Changed _ _ -> True+++-- | A definition lowercased, and its words, as 'bodiesToAnalyse' compares them with names.+data BodyText = BodyText+    { lowered :: Text+    , wordSet :: HashSet Text+    }+++bodyText :: Text -> BodyText+bodyText def = BodyText lower (wordsOf lower)+  where+    lower = T.toLower def+++wordsOf :: Text -> HashSet Text+wordsOf = HS.fromList . filter (not . T.null) . T.split (not . identifierChar)+  where+    identifierChar c = isAlphaNum c || c == '_' || c == '$'+++-- | A function whose body 'bodiesToAnalyse' may pick.+data BodyCandidate a = BodyCandidate+    { value :: a+    , object :: ObjectId+    , body :: BodyText+    -- ^ The words of its definition.+    , triggerRelation :: Maybe ObjectId+    -- ^ The table it is a trigger function on, if it is one.+    }+++-- | Of @functions@, those whose body edges 'affected' can follow from @starts@: their+-- definition names a reached object, or they are a trigger function on the closure.+bodiesToAnalyse :: Dependencies -> Set ObjectId -> [BodyCandidate a] -> [a]+bodiesToAnalyse deps starts functions =+    [f.value | f <- functions, named f.body || maybe False (`Set.member` closure) f.triggerRelation]+  where+    reached = reachableFrom deps starts+    closure = starts <> reached+    counted = Set.toList reached <> filter namedInBodies (Set.toList starts)+    names = HS.toList (foldMap (wordsOf . T.toLower . bodyName) counted)+    operators = [op | Unknown a <- counted, a.objectType == "operator", [_, op] <- [a.objectNames]]+    named def = any (`HS.member` def.wordSet) names || any (`T.isInfixOf` def.lowered) operators+++-- | Whether a body names this object itself when it uses it, rather than its table or type.+namedInBodies :: ObjectId -> Bool+namedInBodies = \case+    Column{} -> False+    TableConstraint{} -> False+    DomainConstraint{} -> False+    Trigger{} -> False+    Policy{} -> False+    Index _ -> False+    Schema _ -> False+    Extension _ -> False+    _ -> True+++-- | The name a function body would use for the object: a part's table, a type's last name.+bodyName :: ObjectId -> Text+bodyName = \case+    Schema s -> nameText s+    Extension e -> nameText e+    Type t -> lastPart t+    DomainConstraint d _ -> lastPart d+    Column t _ -> tableName t+    OtherColumn _ t _ -> tableName t+    TableConstraint t _ -> tableName t+    Trigger t _ -> tableName t+    Policy t _ -> tableName t+    Table q -> tableName q+    View q -> tableName q+    MaterializedView q -> tableName q+    Index q -> tableName q+    Sequence q -> tableName q+    Routine _ q _ -> tableName q+    Unknown a -> case a.objectNames of+        [n] -> L.last ("" :| T.split (== '.') n)+        [_, n] -> n+        _ : t : _ -> t+        [] -> ""+  where+    tableName :: QName -> Text+    tableName q = nameText q.name+    lastPart :: TypeName -> Text+    lastPart t = L.last ("" :| T.split (== '.') (typeText t))
+ src/Sqiff/Folder.hs view
@@ -0,0 +1,117 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Writes a schema as one file per object, for example+-- @table-column/public/payment/amount.sql@.+module Sqiff.Folder (Existing (..), writeFolder, exportManifest) where++import Crypto.Hash qualified as Hash+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import RIO.Directory (createDirectoryIfMissing, doesDirectoryExist, doesFileExist, listDirectory, removeDirectoryRecursive, renameDirectory)+import RIO.FilePath (dropTrailingPathSeparator, joinPath, splitExtension, takeDirectory, (<.>), (</>))+import RIO.Map qualified as Map+import Sqiff.Connection (failWith)+import Sqiff.Definition (printed)+import Sqiff.Model (Address (..), Aspect (..), ObjectKey (..), Schema, toAddress)+++-- | What to do with a folder that is not empty.+data Existing = KeepExisting | ReplaceOwn+    deriving stock (Eq, Show)+++-- | Writes into an empty or new folder. With 'ReplaceOwn', replaces a folder this+-- function wrote before, which it recognises by its marker file. The new export is written+-- beside it first, so a failure leaves the old one as it was.+writeFolder :: Existing -> FilePath -> Schema -> IO ()+writeFolder existing root schema = do+    exists <- doesDirectoryExist root+    entries <- if exists then listDirectory root else pure []+    unless (null entries) do+        when (existing == KeepExisting) $ failWith (T.pack root <> " is not empty; pass --replace to rewrite it, or choose another folder")+        written <- doesFileExist (root </> marker)+        unless written $ failWith (T.pack root <> " was not written by sqiff, so --replace leaves it alone")+    let staging = dropTrailingPathSeparator root <> ".sqiff-staging"+    whenM (doesDirectoryExist staging) $ removeDirectoryRecursive staging+    ( do+            createDirectoryIfMissing True staging+            for_ (Map.toList (exportManifest schema)) \(path, text) -> do+                createDirectoryIfMissing True (takeDirectory (staging </> path))+                writeFileUtf8 (staging </> path) text+            writeFileUtf8 (staging </> marker) "Written by sqiff describe --out; --replace clears this folder.\n"+        )+        `onException` tryAny (removeDirectoryRecursive staging)+    when exists $ removeDirectoryRecursive root+    renameDirectory staging root+++-- | Each object's file and contents, relative to the folder. Paths are distinct even+-- where file names compare without case: those that would clash get a hash of the+-- object's name.+exportManifest :: Schema -> Map FilePath Text+exportManifest schema =+    Map.fromList+        [ (if clashes path then withHash key path else path, printed definition <> "\n")+        | (key, definition, path) <- files+        ]+  where+    files = [(key, definition, objectPath key) | (key, definition) <- Map.toList schema]+    folded = Map.fromListWith (+) [(T.toLower (T.pack path), 1 :: Int) | (_, _, path) <- files]+    clashes path = Map.findWithDefault 0 (T.toLower (T.pack path)) folded > 1+    withHash key path =+        let (base, extension) = splitExtension path+         in [i|#{base}~#{shortHash (tshow key)}#{extension}|]+++marker :: FilePath+marker = ".sqiff"+++objectPath :: ObjectKey -> FilePath+objectPath key = kindSegment addr.objectType </> joinPath (map segment parents) </> (segment name <> args) <.> extension+  where+    addr = toAddress key.object++    (parents, name) = case reverse addr.objectNames of+        [] -> ([], "_")+        lastName : rest -> (reverse rest, lastName)++    args+        | null addr.objectArgs = ""+        | T.length signature <= 120 = segment signature+        | otherwise = [i|(#{shortHash signature})|]+      where+        signature = [i|(#{T.intercalate ", " (objectArgs addr)})|]++    extension = case key.aspect of+        Definition -> "sql"+        Privileges -> "privileges"+        Comment -> "comment"+++-- | A kind of object as a folder name, @table column@ as @table-column@. Kinds are+-- PostgreSQL's words for them, letters and spaces only, so the dashes cannot make two+-- kinds alike.+kindSegment :: Text -> FilePath+kindSegment = T.unpack . T.replace " " "-"+++shortHash :: Text -> Text+shortHash = T.take 12 . tshow . Hash.hashWith Hash.SHA256 . encodeUtf8+++-- | A name as one path segment. Percent signs are escaped too, so different names give+-- different segments.+segment :: Text -> FilePath+segment = T.unpack . dotless . T.concatMap escape+  where+    escape = \case+        '%' -> "%25"+        '/' -> "%2F"+        ' ' -> "%20"+        c -> T.singleton c+    dotless t = if "." `T.isPrefixOf` t then "%2E" <> T.drop 1 t else t
+ src/Sqiff/Git.hs view
@@ -0,0 +1,94 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Reading revisions with git, also from a jj workspace that has no @.git@ of its own.+module Sqiff.Git (Repo (..), findRepo, showFile, resolveCommit, commonDir, git) where++import Data.String.Interpolate (i)+import RIO+import RIO.Directory (canonicalizePath, doesDirectoryExist, doesFileExist, makeAbsolute)+import RIO.FilePath (makeRelative, takeDirectory, (</>))+import RIO.Text qualified as T+import Sqiff.Connection (failWith)+import System.Process.Typed (ProcessConfig, nullStream, proc, readProcess, setStdin, setWorkingDir)+++-- | A git directory and the top of the working tree that paths are relative to.+data Repo = Repo+    { gitDir :: FilePath+    , top :: FilePath+    }+++-- | The repository @dir@ is in.+findRepo :: FilePath -> IO Repo+findRepo dir = do+    (code, out, _) <- readProcess (setStdin nullStream (setWorkingDir dir (proc "git" ["rev-parse", "--absolute-git-dir", "--show-toplevel"])))+    case (code, T.lines (decode out)) of+        (ExitSuccess, [gitDir, top]) -> pure Repo{gitDir = T.unpack gitDir, top = T.unpack top}+        _ -> makeAbsolute dir >>= jjWorkspace >>= maybe (failWith [i|#{dir} is not in a git repository|]) pure+++-- | A jj workspace's top and the git store its repo is backed by.+jjWorkspace :: FilePath -> IO (Maybe Repo)+jjWorkspace dir =+    doesDirectoryExist (dir </> ".jj") >>= \case+        True -> do+            let jjDir = dir </> ".jj"+            pointer <- doesFileExist (jjDir </> "repo")+            repoDir <- if pointer then (jjDir </>) . T.unpack . T.strip <$> readFileUtf8 (jjDir </> "repo") else pure (jjDir </> "repo")+            let store = repoDir </> "store"+            target <- T.unpack . T.strip <$> readFileUtf8 (store </> "git_target")+            gitDir <- canonicalizePath (store </> target)+            pure (Just Repo{gitDir, top = dir})+        False+            | takeDirectory dir == dir -> pure Nothing+            | otherwise -> jjWorkspace (takeDirectory dir)+++-- | A file as it is at @rev@.+showFile :: Repo -> Text -> FilePath -> IO Text+showFile repo rev path = do+    let relative = makeRelative repo.top path+        spec = [i|#{rev}:#{relative}|] :: String+    (code, out, err) <- readProcess (gitProc repo ["show", spec])+    case code of+        ExitSuccess -> pure (decodeUtf8Lenient (toStrictBytes out))+        ExitFailure _ -> failWith [i|git show #{spec}: #{decode err}|]+++-- | The commit @rev@ names.+resolveCommit :: Repo -> Text -> IO Text+resolveCommit repo rev = do+    (code, out, _) <- readProcess (gitProc repo ["rev-parse", "--verify", "--quiet", T.unpack rev <> "^{commit}"])+    case code of+        ExitSuccess -> pure (decode out)+        ExitFailure _ -> failWith [i|#{rev} names no commit|]+++-- | The git directory every worktree and jj workspace of the repository shares.+commonDir :: Repo -> IO FilePath+commonDir repo = do+    (code, out, err) <- readProcess (gitProc repo ["rev-parse", "--path-format=absolute", "--git-common-dir"])+    case code of+        ExitSuccess -> canonicalizePath (T.unpack (decode out))+        ExitFailure _ -> failWith [i|git rev-parse --git-common-dir: #{decode err}|]+++-- | Runs git on the repository; its error output goes into the failure.+git :: Repo -> [String] -> IO ()+git repo args = do+    (code, _, err) <- readProcess (gitProc repo args)+    case code of+        ExitSuccess -> pure ()+        ExitFailure n -> failWith [i|git #{unwords args} failed with exit code #{n}: #{decode err}|]+++gitProc :: Repo -> [String] -> ProcessConfig () () ()+gitProc repo args = setStdin nullStream (proc "git" (("--git-dir=" <> repo.gitDir) : args))+++decode :: LByteString -> Text+decode = T.strip . decodeUtf8Lenient . toStrictBytes
+ src/Sqiff/Graph.hs view
@@ -0,0 +1,66 @@+{-# LANGUAGE NoImplicitPrelude #-}++-- | The graph algorithms the planner and the dependency reports share.+module Sqiff.Graph (+    reachedFrom,+    topoOrder,+    schedule,+) where++import RIO+import RIO.Map qualified as Map+import RIO.Set qualified as Set+++-- | The nodes reachable from @starts@ by one step or more of @next@; a start is in it only+-- when it is reachable from a start.+reachedFrom :: Ord a => (a -> [a]) -> Set a -> Set a+reachedFrom next starts = go Set.empty (step starts)+  where+    step = Set.fromList . concatMap next . Set.toList+    go seen frontier+        | Set.null frontier = seen+        | otherwise =+            let seen' = seen <> frontier+             in go seen' (step frontier `Set.difference` seen')+++-- | The nodes with each after the ones @pairs@ name for it, as @(after, before)@. Ties go+-- to the smaller node; nodes caught in a cycle come last.+topoOrder :: Ord a => Set a -> [(a, a)] -> [a]+topoOrder nodes pairs = case schedule id id (Set.toList nodes) pairs of+    Right ordered -> ordered+    Left (placed, blocked) -> placed <> blocked+++-- | Kahn's algorithm: the items, each after the ones @pairs@ name for it, as+-- @(after, before)@ keys; pairs naming a key no item has are ignored. Among the items+-- that are ready, the one with the smallest priority goes first, then the smallest key.+-- When a cycle blocks some items, 'Left' has the ones placed and the blocked ones, in+-- priority order. Keys are distinct.+schedule :: forall k p a. (Ord k, Ord p) => (a -> k) -> (a -> p) -> [a] -> [(k, k)] -> Either ([a], [a]) [a]+schedule keyOf priorityOf items pairs = go (queue ready0) waiting0 []+  where+    byKey = Map.fromList [(keyOf x, x) | x <- items]+    relevant = Set.fromList [(x, y) | (x, y) <- pairs, x /= y, x `Map.member` byKey, y `Map.member` byKey]+    successors = Map.fromListWith (<>) [(y, [x]) | (x, y) <- Set.toList relevant]+    -- How many items each item still waits for; items waiting for none are not in it.+    waiting0 = Map.fromListWith (+) [(x, 1 :: Int) | (x, _) <- Set.toList relevant]+    ready0 = [k | k <- Map.keys byKey, k `Map.notMember` waiting0]++    -- The items with these keys, by priority.+    queue :: [k] -> Map (p, k) a+    queue ks = Map.fromList [((priorityOf x, k), x) | k <- ks, Just x <- [Map.lookup k byKey]]++    go ready waiting placed = case Map.minViewWithKey ready of+        Nothing+            | Map.null waiting -> Right (reverse placed)+            | otherwise -> Left (reverse placed, Map.elems (queue (Map.keys waiting)))+        Just (((_, k), x), rest) ->+            let (released, waiting') = foldl' release ([], waiting) (Map.findWithDefault [] k successors)+             in go (rest <> queue released) waiting' (x : placed)++    release (released, waiting) k = case Map.lookup k waiting of+        Just 1 -> (k : released, Map.delete k waiting)+        Just n -> (released, Map.insert k (n - 1) waiting)+        Nothing -> (released, waiting)
+ src/Sqiff/Identifier.hs view
@@ -0,0 +1,289 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE UndecidableInstances #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Names as PostgreSQL stores them, kept apart from SQL text: a name reaches SQL only+-- through 'quoted' or 'qualified', so it cannot be spliced in unquoted by mistake.+module Sqiff.Identifier (+    Identifier,+    identifier,+    nameText,+    quoted,+    QName (..),+    qname,+    qualified,+    dotted,+    TypeName,+    typeName,+    typeText,+    quoteIdent,+) where++import Data.Char (isAsciiLower, isDigit)+import Data.String.Interpolate (i)+import Data.String.Interpolate.Conversion (InterpSink, Interpolatable (..))+import Data.Text qualified as T+import GHC.TypeLits (ErrorMessage (..), TypeError)+import RIO+import RIO.Set qualified as Set+++-- | One name as the catalog stores it: unquoted, case and all.+newtype Identifier = Identifier Text+    deriving newtype (Eq, Ord, NFData)+++-- | Shows the name as SQL would quote it, which keeps test failures readable.+instance Show Identifier where+    show = T.unpack . quoted+++-- | Any text is a name: PostgreSQL quotes what it cannot leave bare.+identifier :: Text -> Identifier+identifier = Identifier+++-- | The name itself, for messages, file names and change names; never for SQL.+nameText :: Identifier -> Text+nameText (Identifier t) = t+++-- | The name as SQL writes it.+quoted :: Identifier -> Text+quoted (Identifier t) = quoteIdent t+++-- | Interpolating a name into SQL would splice it in unquoted: say how to render it.+instance {-# OVERLAPPING #-} (TypeError ('Text "Interpolate an Identifier with quoted (SQL) or nameText (messages, paths)"), InterpSink flag dst) => Interpolatable flag Identifier dst where+    interpolate = error "unreachable"+++instance {-# OVERLAPPING #-} (TypeError ('Text "Interpolate a QName with qualified (SQL) or dotted (messages, paths)"), InterpSink flag dst) => Interpolatable flag QName dst where+    interpolate = error "unreachable"+++instance {-# OVERLAPPING #-} (TypeError ('Text "Interpolate a TypeName with typeText"), InterpSink flag dst) => Interpolatable flag TypeName dst where+    interpolate = error "unreachable"+++-- | A name in a schema.+data QName = QName+    { schema :: Identifier+    , name :: Identifier+    }+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++qname :: Text -> Text -> QName+qname s n = QName (identifier s) (identifier n)+++-- | @schema.name@, each part quoted as needed.+qualified :: QName -> Text+qualified (QName s n) = [i|#{quoted s}.#{quoted n}|]+++-- | @schema.name@ unquoted, as pg_identify_object_as_address and messages give it.+dotted :: QName -> Text+dotted (QName s n) = [i|#{nameText s}.#{nameText n}|]+++-- | A type as @format_type@ prints it: already SQL, qualified and quoted as needed.+newtype TypeName = TypeName Text+    deriving newtype (Eq, Ord, Show, NFData)+++typeName :: Text -> TypeName+typeName = TypeName+++-- | The type's SQL text.+typeText :: TypeName -> Text+typeText (TypeName t) = t+++-- | Like PostgreSQL's @quote_ident@: quotes unless the name is lower case and not reserved.+quoteIdent :: Text -> Text+quoteIdent t+    | simple && not (t `Set.member` reserved) = t+    | otherwise = [i|"#{T.replace "\"" "\"\"" t}"|]+  where+    simple = case T.uncons t of+        Just (c, rest) -> (isAsciiLower c || c == '_') && T.all (\x -> isAsciiLower x || isDigit x || x == '_') rest+        Nothing -> False+++-- | The words @pg_get_keywords()@ lists with a category other than unreserved (PostgreSQL 18).+reserved :: Set Text+reserved =+    Set.fromList+        [ "all"+        , "analyse"+        , "analyze"+        , "and"+        , "any"+        , "array"+        , "as"+        , "asc"+        , "asymmetric"+        , "authorization"+        , "between"+        , "bigint"+        , "binary"+        , "bit"+        , "boolean"+        , "both"+        , "case"+        , "cast"+        , "char"+        , "character"+        , "check"+        , "coalesce"+        , "collate"+        , "collation"+        , "column"+        , "concurrently"+        , "constraint"+        , "create"+        , "cross"+        , "current_catalog"+        , "current_date"+        , "current_role"+        , "current_schema"+        , "current_time"+        , "current_timestamp"+        , "current_user"+        , "dec"+        , "decimal"+        , "default"+        , "deferrable"+        , "desc"+        , "distinct"+        , "do"+        , "else"+        , "end"+        , "except"+        , "exists"+        , "extract"+        , "false"+        , "fetch"+        , "float"+        , "for"+        , "foreign"+        , "freeze"+        , "from"+        , "full"+        , "grant"+        , "greatest"+        , "group"+        , "grouping"+        , "having"+        , "ilike"+        , "in"+        , "initially"+        , "inner"+        , "inout"+        , "int"+        , "integer"+        , "intersect"+        , "interval"+        , "into"+        , "is"+        , "isnull"+        , "join"+        , "json"+        , "json_array"+        , "json_arrayagg"+        , "json_exists"+        , "json_object"+        , "json_objectagg"+        , "json_query"+        , "json_scalar"+        , "json_serialize"+        , "json_table"+        , "json_value"+        , "lateral"+        , "leading"+        , "least"+        , "left"+        , "like"+        , "limit"+        , "localtime"+        , "localtimestamp"+        , "merge_action"+        , "national"+        , "natural"+        , "nchar"+        , "none"+        , "normalize"+        , "not"+        , "notnull"+        , "null"+        , "nullif"+        , "numeric"+        , "offset"+        , "on"+        , "only"+        , "or"+        , "order"+        , "out"+        , "outer"+        , "overlaps"+        , "overlay"+        , "placing"+        , "position"+        , "precision"+        , "primary"+        , "real"+        , "references"+        , "returning"+        , "right"+        , "row"+        , "select"+        , "session_user"+        , "setof"+        , "similar"+        , "smallint"+        , "some"+        , "substring"+        , "symmetric"+        , "system_user"+        , "table"+        , "tablesample"+        , "then"+        , "time"+        , "timestamp"+        , "to"+        , "trailing"+        , "treat"+        , "trim"+        , "true"+        , "union"+        , "unique"+        , "user"+        , "using"+        , "values"+        , "varchar"+        , "variadic"+        , "verbose"+        , "when"+        , "where"+        , "window"+        , "with"+        , "xmlattributes"+        , "xmlconcat"+        , "xmlelement"+        , "xmlexists"+        , "xmlforest"+        , "xmlnamespaces"+        , "xmlparse"+        , "xmlpi"+        , "xmlroot"+        , "xmlserialize"+        , "xmltable"+        ]
+ src/Sqiff/Model.hs view
@@ -0,0 +1,247 @@+{-# LANGUAGE DeriveAnyClass #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What a schema is made of: objects named one way per kind, the aspects sqiff compares,+-- and the dependencies between objects.+--+-- The catalog names an object by @pg_identify_object_as_address@: a kind as text and two+-- lists of names. That 'Address' is parsed once, where the catalog is read, into an+-- 'ObjectId'; everything after works with the parsed form, and only renders it back to an+-- 'Address' for messages, file names and catalog lookups.+module Sqiff.Model (+    -- * Objects+    ObjectId (..),+    RoutineKind (..),+    ColumnOf (..),+    owningTable,+    mapQNames,+    isRelation,+    isView,+    isRoutine,++    -- * Catalog addresses+    Address (..),+    fromAddress,+    toAddress,+    render,++    -- * Schemas+    Aspect (..),+    ObjectKey (..),+    definitionKey,+    Schema,+    Edge (..),+) where++import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import Sqiff.Definition (Definition)+import Sqiff.Identifier+++data RoutineKind = Function | Procedure | Aggregate+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++-- | What a column other than a table's belongs to; such columns only carry comments.+data ColumnOf = OfView | OfMaterializedView | OfCompositeType | OfForeignTable+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++-- | One object of the schema, named the way its kind is named.+data ObjectId+    = Schema Identifier+    | Extension Identifier+    | Table QName+    | View QName+    | MaterializedView QName+    | -- | A table's column.+      Column QName Identifier+    | -- | A column of a view, materialized view, composite type or foreign table.+      OtherColumn ColumnOf QName Identifier+    | TableConstraint QName Identifier+    | DomainConstraint TypeName Identifier+    | Index QName+    | Sequence QName+    | Type TypeName+    | Routine RoutineKind QName [TypeName]+    | Trigger QName Identifier+    | Policy QName Identifier+    | -- | A kind sqiff does not model, as the catalog addressed it. Only 'fromAddress'+      -- makes one, so it never holds an address one of the other constructors covers.+      Unknown Address+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++-- | The table a column, constraint, trigger or policy belongs to. Indexes name their+-- table only in their definition.+owningTable :: ObjectId -> Maybe QName+owningTable = \case+    Column t _ -> Just t+    TableConstraint t _ -> Just t+    Trigger t _ -> Just t+    Policy t _ -> Just t+    _ -> Nothing+++-- | The object with each schema-qualified name in its identity changed by @f@, such as+-- the table a column belongs to. Type names are SQL text and stay as they are.+mapQNames :: (QName -> QName) -> ObjectId -> ObjectId+mapQNames f = \case+    Table q -> Table (f q)+    View q -> View (f q)+    MaterializedView q -> MaterializedView (f q)+    Column t c -> Column (f t) c+    OtherColumn of_ t c -> OtherColumn of_ (f t) c+    TableConstraint t c -> TableConstraint (f t) c+    Index q -> Index (f q)+    Sequence q -> Sequence (f q)+    Routine kind q args -> Routine kind (f q) args+    Trigger t n -> Trigger (f t) n+    Policy t n -> Policy (f t) n+    other@(Schema _) -> other+    other@(Extension _) -> other+    other@(DomainConstraint _ _) -> other+    other@(Type _) -> other+    other@(Unknown _) -> other+++-- | A table, view or materialized view, with its name.+isRelation :: ObjectId -> Maybe QName+isRelation = \case+    Table q -> Just q+    View q -> Just q+    MaterializedView q -> Just q+    _ -> Nothing+++isView :: ObjectId -> Bool+isView = \case+    View _ -> True+    MaterializedView _ -> True+    _ -> False+++-- | Functions and procedures, whose bodies can use other objects.+isRoutine :: ObjectId -> Bool+isRoutine = \case+    Routine Function _ _ -> True+    Routine Procedure _ _ -> True+    _ -> False+++-- | How @pg_identify_object_as_address@ names an object.+data Address = Address+    { objectType :: Text+    , objectNames :: [Text]+    , objectArgs :: [Text]+    }+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++fromAddress :: Address -> ObjectId+fromAddress addr = case (addr.objectType, addr.objectNames, addr.objectArgs) of+    ("schema", [s], []) -> Schema (identifier s)+    ("extension", [e], []) -> Extension (identifier e)+    ("table", [s, n], []) -> Table (qname s n)+    ("view", [s, n], []) -> View (qname s n)+    ("materialized view", [s, n], []) -> MaterializedView (qname s n)+    ("table column", [s, t, c], []) -> Column (qname s t) (identifier c)+    ("view column", [s, t, c], []) -> OtherColumn OfView (qname s t) (identifier c)+    ("materialized view column", [s, t, c], []) -> OtherColumn OfMaterializedView (qname s t) (identifier c)+    ("composite type column", [s, t, c], []) -> OtherColumn OfCompositeType (qname s t) (identifier c)+    ("foreign table column", [s, t, c], []) -> OtherColumn OfForeignTable (qname s t) (identifier c)+    ("table constraint", [s, t, c], []) -> TableConstraint (qname s t) (identifier c)+    ("domain constraint", [d], [c]) -> DomainConstraint (typeName d) (identifier c)+    ("index", [s, n], []) -> Index (qname s n)+    ("sequence", [s, n], []) -> Sequence (qname s n)+    ("type", [t], []) -> Type (typeName t)+    ("function", [s, n], args) -> Routine Function (qname s n) (map typeName args)+    ("procedure", [s, n], args) -> Routine Procedure (qname s n) (map typeName args)+    ("aggregate", [s, n], args) -> Routine Aggregate (qname s n) (map typeName args)+    ("trigger", [s, t, n], []) -> Trigger (qname s t) (identifier n)+    ("policy", [s, t, n], []) -> Policy (qname s t) (identifier n)+    _ -> Unknown addr+++-- | The address 'fromAddress' parsed this object from.+toAddress :: ObjectId -> Address+toAddress = \case+    Schema s -> Address "schema" [nameText s] []+    Extension e -> Address "extension" [nameText e] []+    Table q -> Address "table" (names q) []+    View q -> Address "view" (names q) []+    MaterializedView q -> Address "materialized view" (names q) []+    Column t c -> Address "table column" (names t <> [nameText c]) []+    OtherColumn of_ t c -> Address (columnKind of_) (names t <> [nameText c]) []+    TableConstraint t c -> Address "table constraint" (names t <> [nameText c]) []+    DomainConstraint d c -> Address "domain constraint" [typeText d] [nameText c]+    Index q -> Address "index" (names q) []+    Sequence q -> Address "sequence" (names q) []+    Type t -> Address "type" [typeText t] []+    Routine kind q args -> Address (routineKind kind) (names q) (map typeText args)+    Trigger t n -> Address "trigger" (names t <> [nameText n]) []+    Policy t n -> Address "policy" (names t <> [nameText n]) []+    Unknown addr -> addr+  where+    names q = [nameText q.schema, nameText q.name]+    columnKind = \case+        OfView -> "view column"+        OfMaterializedView -> "materialized view column"+        OfCompositeType -> "composite type column"+        OfForeignTable -> "foreign table column"+    routineKind = \case+        Function -> "function"+        Procedure -> "procedure"+        Aggregate -> "aggregate"+++-- | The object as messages name it: its kind, dotted names and arguments.+render :: ObjectId -> Text+render object = [i|#{addr.objectType} #{names}#{args}|]+  where+    addr = toAddress object+    names = T.intercalate "." addr.objectNames+    args :: Text+    args+        | null addr.objectArgs = ""+        | otherwise = let list = T.intercalate ", " addr.objectArgs in [i|(#{list})|]+++-- | The parts of an object sqiff compares apart.+data Aspect = Definition | Privileges | Comment+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++data ObjectKey = ObjectKey+    { aspect :: Aspect+    , object :: ObjectId+    }+    deriving stock (Eq, Ord, Show, Generic)+    deriving anyclass (NFData)+++definitionKey :: ObjectId -> ObjectKey+definitionKey = ObjectKey Definition+++-- | Each object's aspects, as the catalog describes them.+type Schema = Map ObjectKey Definition+++-- | @dependent@ needs @referenced@ to exist, as recorded in @pg_depend@ or seen in a+-- PL/pgSQL body by plpgsql_check.+data Edge = Edge+    { dependent :: ObjectId+    , referenced :: ObjectId+    }+    deriving stock (Eq, Ord, Show)
+ src/Sqiff/Plan.hs view
@@ -0,0 +1,203 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Orders recipe steps: drops before creates, each after what it depends on.+module Sqiff.Plan (+    plan,+    planWith,+    DependencyCycle (..),+    cycleMessage,+    context,+    invert,+    renderStep,+    topoOrder,+) where++import Data.Text qualified as T+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Body (BodyCheck)+import Sqiff.Definition+import Sqiff.Dependencies (Dependencies, edges)+import Sqiff.Diff (Change (..), Changes, invert)+import Sqiff.Graph (schedule, topoOrder)+import Sqiff.Model+import Sqiff.Recipe+import Sqiff.Sql (terminator)+++-- | Objects whose steps depend on each other in a circle, so no order works.+newtype DependencyCycle = DependencyCycle (NonEmpty ObjectId)+    deriving stock (Eq, Show)+++cycleMessage :: DependencyCycle -> Text+cycleMessage (DependencyCycle objects) =+    "no order satisfies the dependencies between these objects; change them by hand: "+        <> T.intercalate ", " (map render (toList objects))+++-- | @fromDeps@ come from the database being changed; @toDeps@ and @checks@ from the desired one.+plan :: Map ObjectKey BodyCheck -> Schema -> Schema -> Dependencies -> Dependencies -> Changes -> Either DependencyCycle [Step]+plan = planWith id+++-- | 'plan' with the context adjusted first.+--+-- Drops come before creates. Within each phase a step waits for what it depends on:+-- creating an object waits for the objects it uses, and dropping one waits for its+-- dependents' drops. Among the steps that are ready, the kind of object decides (its+-- rank), then the dependency order of the objects, then the order the recipes gave.+planWith :: (Context -> Context) -> Map ObjectKey BodyCheck -> Schema -> Schema -> Dependencies -> Dependencies -> Changes -> Either DependencyCycle [Step]+planWith adjust checks fromSchema toSchema fromDeps toDeps changes = do+    drops <- inPhase DropPhase [(b, a) | (a, b) <- withOwners fromDeps, not (owns a b)]+    creates <- inPhase CreatePhase (withOwners toDeps)+    pure (drops <> creates)+  where+    ctx = adjust (context checks fromSchema toSchema fromDeps changes)+    steps = concatMap (uncurry (recipe ctx)) (Map.toList changes)+    stepObjects = Set.fromList [k.object | k <- Map.keys changes]++    withOwners deps =+        [(e.dependent, e.referenced) | e <- edges deps]+            <> [(o, Table t) | o <- Set.toList stepObjects, Just t <- [owningTable o]]++    createOrder = indexOf (topoOrder stepObjects (withOwners toDeps))+    dropOrder = indexOf (topoOrder stepObjects [(b, a) | (a, b) <- withOwners fromDeps])+    indexOf xs = Map.fromList (zip xs [0 :: Int ..])+    position s = Map.findWithDefault maxBound s.object (if s.phase == DropPhase then dropOrder else createOrder)++    -- The phase's steps in order, where @(a, b)@ in @pairs@ means a's steps wait for b's.+    -- Steps are known by their number in 'steps'.+    inPhase phase pairs =+        let numbered = [(n, s) | (n, s) <- zip [0 :: Int ..] steps, s.phase == phase]+            priority (n, s) = (s.rank, position s, n)+            byObject = Map.fromListWith (flip (<>)) [(s.object, [n]) | (n, s) <- L.sortOn priority numbered]+            stepsOf o = Map.findWithDefault [] o byObject+            -- An object's own steps keep their order.+            chained = [(later, earlier) | ns <- Map.elems byObject, (earlier, later) <- zip ns (drop 1 ns)]+            -- a's first step waits for b's main step when creating, as b exists from+            -- then on, and for b's last step when dropping, as b is gone after it. A new+            -- table's columns have no steps: the table's waits for what they use.+            waits =+                [ (waiting, waited)+                | (a, b) <- pairs+                , a /= b+                , let a' = if null (stepsOf a) then maybe a Table (owningTable a) else a+                , a' /= b+                , waiting <- waitingSteps phase a' b (stepsOf a')+                , waited <- if phase == CreatePhase then mainStep b else take 1 (reverse (stepsOf b))+                ]+            -- The first step that creates, replaces or drops the object itself, not+            -- one that sets its settings, grants or comment.+            mainStep b = take 1 [n | n <- stepsOf b, Just s <- [Map.lookup n stepAt], defines s]+         in case schedule fst priority numbered (chained <> waits) of+                Right placed -> Right (map snd placed)+                Left (_, (_, b) : bs) -> Left (DependencyCycle (b.object :| filter (/= b.object) (nubOrd (map ((.object) . snd) bs))))+                Left (placed, []) -> Right (map snd placed)++    stepAt = Map.fromList (zip [0 :: Int ..] steps)++    -- The steps of a that wait for b: its first, or, for a sequence's ownership by a+    -- column, the step that sets the owner. The sequence itself comes first, as the+    -- column's default uses it.+    waitingSteps phase a b ns+        | phase == CreatePhase, owns a b = [n | n <- ns, Just s <- [Map.lookup n stepAt], s.role == OwnsSequence]+        | otherwise = take 1 ns++    -- A sequence owned by a column: dropping the column drops the sequence.+    owns a b = case (a, b) of+        (Sequence _, Column{}) -> True+        _ -> False+++-- | @checks@ were made against @toSchema@'s definitions; @fromDeps@ come from the+-- database being changed.+context :: Map ObjectKey BodyCheck -> Schema -> Schema -> Dependencies -> Changes -> Context+context checks fromSchema toSchema fromDeps changes =+    Context+        { bodyChecks = Map.intersectionWith (,) (Map.map printed toSchema) checks+        , withDependents = Set.fromList [e.referenced | e <- edges fromDeps]+        , recreatedViews =+            Map.fromList+                [ (v, KeptOnView{keptIndexes = indexesOn v, keptGrants = (grantsKey,) <$> mfilter explicit (Map.lookup grantsKey toSchema)})+                | (k, Changed _ _) <- Map.toList changes+                , k.aspect == Definition+                , let grantsKey = k{aspect = Privileges}+                , Just v <- [case k.object of MaterializedView v -> Just v; View v -> Just v; _ -> Nothing]+                ]+        , keptComments =+            Map.fromList+                [ (k.object, printed def)+                | (k, def) <- Map.toList toSchema+                , k.aspect == Comment+                , k `Map.notMember` changes+                ]+        , newTables = tablesWith isAdded+        , droppedTables = tablesWith isDropped+        , partitionedTables =+            Set.fromList+                [ t+                | (k, TableDefinition def) <- Map.toList fromSchema <> Map.toList toSchema+                , k.aspect == Definition+                , isJust def.partitionBy+                , Table t <- [k.object]+                ]+        , droppedColumns = Set.fromList [(t, c) | (Column t c, Dropped _) <- definitions]+        , retypedColumns =+            Set.fromList+                [ (t, c)+                | (Column t c, Changed (ColumnDefinition o) (ColumnDefinition n)) <- definitions+                , columnTypeChanged o n+                ]+        , viewsAround = Map.empty+        , droppedObjects = Set.fromList [k.object | (k, Dropped _) <- Map.toList changes, k.aspect == Definition]+        , viewDependents = Map.empty+        , convertedSequences =+            Set.fromList+                [ s+                | (Sequence s, change) <- definitions+                , Just def <- [asSequence (case change of Added d -> d; Dropped d -> d; Changed _ d -> d)]+                , Just (t, c) <- [def.ownedBy]+                , Just (Changed (ColumnDefinition old) (ColumnDefinition new)) <- [lookup (Column t c) definitions]+                , isJust (identityKindOf old) /= isJust (identityKindOf new)+                ]+        , newTableColumns =+            Map.map (L.sortOn (\(_, def) -> positionNumber def.position))+                . Map.fromListWith (flip (<>))+                $ [(t, [(c, def)]) | (Column t c, Added (ColumnDefinition def)) <- definitions, t `Set.member` tablesWith isAdded]+        }+  where+    definitions = [(k.object, change) | (k, change) <- Map.toList changes, k.aspect == Definition]+    indexesOn v =+        [ (q, def.statement)+        | (k, IndexDefinition def) <- Map.toList toSchema+        , k.aspect == Definition+        , k `Map.notMember` changes+        , Index q <- [k.object]+        , def.table == v+        ]+    -- A view created again starts with the default privileges.+    explicit = \case+        AclDefinition (ExplicitAcl _) -> True+        _ -> False+    tablesWith p = Set.fromList [t | (Table t, change) <- definitions, p change]+    isAdded = \case Added _ -> True; _ -> False+    isDropped = \case Dropped _ -> True; _ -> False+++renderStep :: Step -> Text+renderStep s =+    T.unlines+        $ ["-- " <> render s.object]+        <> ["-- " <> note | note <- txnNote <> map hazardText s.hazards]+        <> [s.sql <> terminator s.sql]+  where+    txnNote = case s.txn of+        Shared -> []+        Own -> ["own transaction"]+        None -> ["outside a transaction"]
+ src/Sqiff/Recipe.hs view
@@ -0,0 +1,1144 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | One fixed recipe per kind of object and kind of change.+module Sqiff.Recipe (+    Phase (..),+    Txn (..),+    Hazard (..),+    hazardText,+    revokeGranted,+    Step (..),+    Role (..),+    defines,+    Undo (..),+    Context (..),+    Surrounding (..),+    KeptOnView (..),+    columnSql,+    recipe,+) where++import Data.ByteString qualified as B+import Data.Char (isAlphaNum)+import Data.String.Interpolate (i, __i)+import Data.Text qualified as T+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Body (BodyCheck (..))+import Sqiff.Definition+import Sqiff.Diff (Change (..))+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Sql (doBlock, literal, replaceInCode)+++data Phase = DropPhase | CreatePhase+    deriving stock (Eq, Ord, Show)+++-- | @Own@ steps must commit apart from what came before them; @None@ steps cannot run+-- inside a transaction at all.+data Txn = Shared | Own | None+    deriving stock (Eq, Ord, Show)+++data Hazard+    = DeletesData+    | MayRewriteTable+    | RewritesTable+    | -- | ACCESS EXCLUSIVE for the whole statement.+      LongLock+    | WriteLock+    | LocksOther Text+    | RechecksForeignKey Text+    | EveryPartition+    | IndexBuild+    | -- | An existing value may not convert to the column's new type.+      ConversionMayFail+    | MayFail Text+    | Manual Text+    deriving stock (Eq, Ord, Show)+++hazardText :: Hazard -> Text+hazardText = \case+    DeletesData -> "hazard: deletes data"+    MayRewriteTable -> "hazard: may rewrite the table"+    RewritesTable -> "hazard: rewrites the table and its indexes"+    LongLock -> "hazard: holds an ACCESS EXCLUSIVE lock, which blocks reads and writes, while it runs"+    WriteLock -> "hazard: holds a lock that blocks writes while it runs"+    LocksOther t -> [i|hazard: also locks #{t} while it runs|]+    RechecksForeignKey t -> [i|hazard: checks the foreign key between the table and #{t} again, reading every row|]+    EveryPartition -> "hazard: the lock and any rewrite cover every partition"+    IndexBuild -> "hazard: builds an index"+    ConversionMayFail -> "hazard: fails when an existing value does not convert to the new type"+    MayFail why -> "hazard: " <> why+    Manual why -> "manual: " <> why+++-- | Takes back from a relation every grant but its owner's, such as the ones default+-- privileges give a view created again, before its own grants are restored.+revokeGranted :: Text -> Text+revokeGranted relation =+    doBlock [i| declare g text; begin for g in select distinct case when x.grantee = 0 then 'public' else quote_ident(pg_get_userbyid(x.grantee)) end from pg_class c cross join aclexplode(c.relacl) x where c.oid = #{literal relation}::regclass and x.grantee <> c.relowner loop execute format('revoke all on table %s from %s', #{literal relation}, g); end loop; end |]+++data Step = Step+    { phase :: Phase+    , role :: Role+    , rank :: Int+    -- ^ Orders steps within a phase; dependency order breaks ties.+    , object :: ObjectId+    , sql :: Text+    , txn :: Txn+    , hazards :: [Hazard]+    , key :: ObjectKey+    , change :: Change Definition+    , undo :: Undo+    -- ^ How a migration that holds this step reverts it.+    }+    deriving stock (Eq, Show)+++-- | What a step does to its object. Planning and the sqitch output go by it, rather+-- than by a step's rank or SQL.+data Role+    = -- | Creates the object, or changes it in place.+      Creates+    | -- | Creates or replaces the object in one statement.+      Replaces+    | -- | Builds an index the object needs, concurrently.+      BuildsIndex+    | -- | Drops the object: for good, or in the create phase to create it again.+      Drops+    | -- | Renames a column, before anything else runs.+      RenamesColumn+    | -- | Sets the column that owns a sequence, once the column exists.+      OwnsSequence+    | -- | Sets something on an object that exists: a table's settings, grants, a comment.+      Configures+    deriving stock (Eq, Show)+++-- | Whether the step creates, replaces or drops the object itself, rather than renaming+-- it or setting what goes with it.+defines :: Step -> Bool+defines s = s.role `elem` [Creates, Replaces, BuildsIndex, Drops]+++-- | How a step is reverted when its object's change is split over several migrations,+-- so that reverting one migration returns to the state after the one before it.+data Undo+    = -- | By the object's inverse: as a whole when its migration holds all the change, else+      -- a drop by creating the old object again and a create by dropping the new one.+      UndoObject+    | -- | By these steps, in order.+      UndoBy [Step]+    deriving stock (Eq, Show)+++-- | What has to go before a statement and come back after it: the statements that drop+-- the objects in the way, and the ones that create them again.+data Surrounding = Surrounding+    { dropBefore :: [Text]+    , createAfter :: [Text]+    }+    deriving stock (Eq, Show)+++-- | What a view dropped and created again gets back: its indexes (name and definition)+-- and its privileges.+data KeptOnView = KeptOnView+    { keptIndexes :: [(QName, Text)]+    , keptGrants :: Maybe (ObjectKey, Definition)+    }+++data Context = Context+    { newTables :: Set QName+    , droppedTables :: Set QName+    , partitionedTables :: Set QName+    , droppedColumns :: Set (QName, Identifier)+    , retypedColumns :: Set (QName, Identifier)+    , newTableColumns :: Map QName [(Identifier, ColumnDef)]+    , bodyChecks :: Map ObjectKey (Text, BodyCheck)+    -- ^ Body checks, with the definition each was made for.+    , withDependents :: Set ObjectId+    -- ^ Objects that something else depends on, in the database being changed.+    , recreatedViews :: Map QName KeptOnView+    -- ^ Views dropped and created again, with what to restore on them.+    , keptComments :: Map ObjectId Text+    -- ^ The desired database's comments that do not change, which an object dropped and+    -- created again gets back.+    , viewsAround :: Map (QName, Identifier) Surrounding+    -- ^ For a column whose type changes, the statements that drop the views reading it+    -- and the ones that create them again, with their grants, indexes, triggers and comments.+    , droppedObjects :: Set ObjectId+    , viewDependents :: Map QName Surrounding+    -- ^ For a view whose columns change other than at the end, the statements that drop+    -- what depends on it and the ones that create those again.+    , convertedSequences :: Set QName+    -- ^ Sequences a column's change between serial and identity drops or creates, in+    -- the one step that changes the column.+    }+++recipe :: Context -> ObjectKey -> Change Definition -> [Step]+recipe ctx key change = case key.aspect of+    Privileges -> privileges key object change+    Comment -> comment ctx key change+    Definition -> definition Target{context = ctx, objectKey = key, objectChange = change}+  where+    object = key.object+++-- Ranks order steps within a phase; dependency order breaks ties.+createRank :: ObjectId -> Int+createRank = \case+    Schema _ -> 0+    Extension _ -> 1+    Type _ -> 2+    Sequence _ -> 3+    Table _ -> 4+    Column _ _ -> 5+    View _ -> 7+    MaterializedView _ -> 8+    -- After views: PostgreSQL records what a view uses, so a view on a new function waits+    -- for it, but not what a function's string body uses, which may be a new view.+    Routine{} -> 9+    TableConstraint _ _ -> 10+    DomainConstraint _ _ -> 10+    Index _ -> 11+    Trigger _ _ -> 12+    Policy _ _ -> 13+    OtherColumn{} -> 20+    Unknown _ -> 20+++dropRank :: ObjectId -> Int+dropRank = \case+    Policy _ _ -> 0+    Trigger _ _ -> 1+    Index _ -> 2+    TableConstraint _ _ -> 3+    DomainConstraint _ _ -> 3+    MaterializedView _ -> 4+    View _ -> 5+    Routine{} -> 6+    Column _ _ -> 7+    Table _ -> 8+    Sequence _ -> 9+    Type _ -> 10+    Extension _ -> 11+    Schema _ -> 12+    OtherColumn{} -> 20+    Unknown _ -> 20+++sequenceOwnerRank, tableSettingsRank, privilegesRank :: Int+sequenceOwnerRank = 9+tableSettingsRank = 14+privilegesRank = 15+++definition :: Target -> [Step]+definition this = case this.objectKey.object of+    Schema s -> case textual this of+        Added _ -> [create this (Shared, []) ("create schema " <> quoted s)]+        Dropped _ -> [remove this (Shared, []) ("drop schema " <> quoted s)]+        Changed _ _ -> []+    Extension e -> extensionRecipe this e+    Table t -> tableRecipe this t+    Column t c+        | t `Set.member` this.context.droppedTables -> []+        | t `Set.member` this.context.partitionedTables -> map onEveryPartition (columnRecipe this t c)+        | otherwise -> columnRecipe this t c+    TableConstraint t c+        | t `Set.member` this.context.droppedTables -> []+        | otherwise -> tableConstraintRecipe this t c+    DomainConstraint d c -> domainConstraintRecipe this d c+    Index ix -> indexRecipe this ix+    Sequence s -> sequenceRecipe this s+    Type t -> typeRecipe this t+    Routine kind q args -> routineRecipe this kind q args+    View v -> viewRecipe this v+    MaterializedView v -> materializedViewRecipe this v+    Trigger t n+        | t `Set.member` this.context.droppedTables -> []+        | otherwise -> triggerRecipe this t n+    Policy t n+        | t `Set.member` this.context.droppedTables -> []+        | otherwise -> policyRecipe this t n+    OtherColumn{} -> noRecipe this+    Unknown _ -> noRecipe this+++-- | The object a recipe is for, and the change to it.+data Target = Target+    { context :: Context+    , objectKey :: ObjectKey+    , objectChange :: Change Definition+    }+++-- | The definitions as the catalog prints them, for the recipes that read the text.+textual :: Target -> Change Text+textual this = printed <$> this.objectChange+++-- | A step of the create phase that creates the object or changes it, at its own rank.+create :: Target -> (Txn, [Hazard]) -> Text -> Step+create this = stepOf this CreatePhase Creates (createRank this.objectKey.object)+++-- | A step that replaces the object in one statement.+replace :: Target -> (Txn, [Hazard]) -> Text -> Step+replace this = stepOf this CreatePhase Replaces (createRank this.objectKey.object)+++-- | A step that builds an index the object needs, concurrently.+buildIndex :: Target -> (Txn, [Hazard]) -> Text -> Step+buildIndex this = stepOf this CreatePhase BuildsIndex (createRank this.objectKey.object)+++-- | A step of the drop phase that drops the object.+remove :: Target -> (Txn, [Hazard]) -> Text -> Step+remove this = stepOf this DropPhase Drops (dropRank this.objectKey.object)+++-- | A step of the create phase that drops the object, to create it again right after.+dropToRecreate :: Target -> (Txn, [Hazard]) -> Text -> Step+dropToRecreate this = stepOf this CreatePhase Drops (createRank this.objectKey.object)+++-- | A step that sets something on the object once it exists, at @rank@.+configure :: Target -> Int -> (Txn, [Hazard]) -> Text -> Step+configure this = stepOf this CreatePhase Configures+++-- | A step that sets the column owning a sequence.+ownSequence :: Target -> (Txn, [Hazard]) -> Text -> Step+ownSequence this = stepOf this CreatePhase OwnsSequence sequenceOwnerRank+++stepOf :: Target -> Phase -> Role -> Int -> (Txn, [Hazard]) -> Text -> Step+stepOf this phase role rank (txn, hazards) sql =+    Step+        { phase+        , role+        , rank+        , object = this.objectKey.object+        , sql+        , txn+        , hazards+        , key = this.objectKey+        , change = this.objectChange+        , undo = UndoObject+        }+++-- | A step left to a person, saying why.+manual :: Target -> Text -> [Step]+manual this why = [create this (Shared, [Manual why]) ("-- " <> why)]+++noRecipe :: Target -> [Step]+noRecipe this = [create this (Shared, [Manual "no recipe for this kind of object"]) ("-- " <> T.pack (show (textual this)))]+++undoneBy :: [Step] -> Step -> Step+undoneBy steps s = s{undo = UndoBy steps}+++-- | A step another recipe makes, as part of this one: what restores an object created+-- again goes with that, so its migration leaves the object whole.+asPartOfThis :: Target -> Step -> Step+asPartOfThis this s = s{rank = createRank this.objectKey.object, key = this.objectKey, change = this.objectChange, undo = UndoBy []}+++-- | A concurrent build is reverted by dropping what it built.+builds :: Target -> QName -> Step -> Step+builds this index = undoneBy [create this (None, []) ("drop index concurrently if exists " <> qualified index)]+++-- | The unchanged comments of what this step drops and creates again: they go with the+-- old object, and nothing else in the plan sets them.+restoreComments :: Target -> [ObjectId] -> [Step]+restoreComments this objects =+    [ undoneBy [] (configure this (createRank this.objectKey.object) (Shared, []) [i|comment on #{subject} is #{literal text}|])+    | o <- objects+    , Just text <- [Map.lookup o this.context.keptComments]+    , Just subject <- [commentTarget o]+    ]+++-- | The change as the kind of definition this recipe reads; a definition of another+-- kind is the catalog's mistake, left to a person. The steps keep the change as it was.+typed :: Target -> (Definition -> Maybe a) -> (Change a -> [Step]) -> [Step]+typed this as f = maybe (manual this "the catalog described this object unexpectedly") f (traverse as this.objectChange)+++notValid :: Text+notValid = " NOT VALID"+++-- | Whether @new@ is @old@ validated.+validates :: ConstraintDef -> ConstraintDef -> Bool+validates old new = old.validity == NotValidated && new.validity == Validated && withoutValidity old == new+++-- | A step on a partitioned table's column, whose lock and rewrite cover every partition.+onEveryPartition :: Step -> Step+onEveryPartition s+    | any (`elem` [DeletesData, MayRewriteTable, LongLock]) s.hazards = s{hazards = s.hazards <> [EveryPartition]}+    | otherwise = s+++-- | Whether @def@ names a column of @t@ that the plan drops or retypes.+namesAlteredColumn :: Target -> QName -> Text -> Bool+namesAlteredColumn this t = namesAlteredColumnOf this (== t)+++namesAlteredColumnOf :: Target -> (QName -> Bool) -> Text -> Bool+namesAlteredColumnOf this onTable def =+    let names = Set.fromList (T.split (\ch -> not (isAlphaNum ch || ch == '_')) def)+     in any (\(t', c) -> onTable t' && nameText c `Set.member` names) (this.context.droppedColumns <> this.context.retypedColumns)+++extensionRecipe :: Target -> Identifier -> [Step]+extensionRecipe this e = typed this asExtension \case+    Added def ->+        let schema = quoted def.schema+            version = literal def.version+         in [create this (Shared, []) [i|create extension if not exists #{quoted e} with schema #{schema} version #{version}|]]+    Dropped _ -> [remove this (Shared, []) ("drop extension " <> quoted e)]+    Changed old new+        | old.schema /= new.schema -> manual this "extension moved to another schema"+        | otherwise ->+            let version = literal new.version+             in [create this (Own, []) [i|alter extension #{quoted e} update to #{version}|]]+++tableRecipe :: Target -> QName -> [Step]+tableRecipe this t = typed this asTable \case+    Added def -> createTable this t def+    Dropped _ -> [remove this (Shared, [DeletesData]) ("drop table " <> qualified t)]+    Changed old new -> alterTable this t old new+++createTable :: Target -> QName -> TableDef -> [Step]+createTable this t def+    | Just p <- def.partitionOf =+        create this (Shared, []) [i|create table #{qualified t} partition of #{qualified p.parent} #{p.bound}|] : settings+    | otherwise =+        create+            this+            (Shared, [])+            [i|create #{unloggedKeyword}table #{qualified t} (#{columnList})#{inheritsClause}#{partitionClause}#{storageClause}|]+            : settings+  where+    unloggedKeyword, inheritsClause, partitionClause, storageClause :: Text+    unloggedKeyword = if def.unlogged then "unlogged " else ""+    inheritsClause = case map qualified def.inherits of+        [] -> ""+        parents -> [i| inherits (#{T.intercalate ", " parents})|]+    partitionClause = maybe "" (" partition by " <>) def.partitionBy+    storageClause = maybe "" (" " <>) (withOptions def.options)+    -- Columns a parent gives it are not declared again.+    columnList :: Text+    columnList = case [col | col@(_, d) <- Map.findWithDefault [] t this.context.newTableColumns, not d.inheritedOnly] of+        [] -> ""+        cols -> [i|\n#{T.intercalate ",\n" (map columnLine cols)}\n|]+    columnLine (c, col) = [i|    #{quoted c} #{columnSql col}|]+    settings =+        [configure this tableSettingsRank (Shared, []) [i|alter table #{qualified t} enable row level security|] | def.rowSecurity]+            <> [configure this tableSettingsRank (Shared, []) [i|alter table #{qualified t} force row level security|] | def.forceRowSecurity]+++alterTable :: Target -> QName -> TableDef -> TableDef -> [Step]+alterTable this t old new+    | (old.partitionBy, old.partitionOf) /= (new.partitionBy, new.partitionOf) = manual this "partitioning changed"+    | otherwise =+        toggle (.unlogged) ("set unlogged", "set logged") [MayRewriteTable, LongLock]+            <> toggle (.rowSecurity) ("enable row level security", "disable row level security") []+            <> toggle (.forceRowSecurity) ("force row level security", "no force row level security") []+            <> storageOptions+            <> [create this (Shared, []) [i|alter table #{qualified t} no inherit #{qualified p}|] | p <- old.inherits, p `notElem` new.inherits]+            <> [create this (Shared, []) [i|alter table #{qualified t} inherit #{qualified p}|] | p <- new.inherits, p `notElem` old.inherits]+  where+    toggle :: (TableDef -> Bool) -> (Text, Text) -> [Hazard] -> [Step]+    toggle setting (enable, disable) hazards+        | setting old == setting new = []+        | setting new = [configure this tableSettingsRank (Shared, hazards) [i|alter table #{qualified t} #{enable}|]]+        | otherwise = [configure this tableSettingsRank (Shared, hazards) [i|alter table #{qualified t} #{disable}|]]+    optionKey = T.takeWhile (/= '=')+    removedKeys = [k | o <- old.options, let k = optionKey o, k `notElem` map optionKey new.options]+    newOptions = T.intercalate ", " new.options+    storageOptions =+        [ configure this tableSettingsRank (Shared, []) [i|alter table #{qualified t} set (#{newOptions})|]+        | not (null new.options)+        , L.sort new.options /= L.sort old.options+        ]+            <> [ configure this tableSettingsRank (Shared, []) [i|alter table #{qualified t} reset (#{T.intercalate ", " removedKeys})|]+               | not (null removedKeys)+               ]+++columnRecipe :: Target -> QName -> Identifier -> [Step]+-- [allow:SqiffSmallWhere] pre-existing at adoption+columnRecipe this t c = case traverse asColumn this.objectChange of+    Nothing -> manual this "the catalog described the column without its column facts"+    -- The parent's change brings it, changes it or takes it away.+    Just ch | all (.inheritedOnly) ch -> []+    Just (Added parsed)+        | t `Set.member` this.context.newTables -> []+        | otherwise ->+            let rewrites = parsed.rewritesOnAdd || isJust (identityKindOf parsed) || fmap fst (generatedOf parsed) == Just Stored+                hazards =+                    [MayFail "a not null column without a default fails on a table with rows" | failsOnRows parsed]+                        <> [h | rewrites, h <- [MayRewriteTable, LongLock]]+             in [create this (Shared, hazards) [i|#{alter}add column #{quoted c} #{columnSql parsed}|]]+    Just (Dropped _) -> [remove this (Shared, [DeletesData]) [i|#{alter}drop column #{quoted c}|]]+    Just (Changed old new) -> alterColumn old new+  where+    alter = [i|alter table #{qualified t} |]+    col = [i|#{alter}alter column #{quoted c} |]+    alterColumn old new =+        let typeChanged = columnTypeChanged old new+            defaultChanged = defaultExpr old /= defaultExpr new+            serialToIdentity = isNothing (identityKindOf old) && isJust (identityKindOf new) && isJust (serialSequence old)+            identityToSerial = isJust (identityKindOf old) && isNothing (identityKindOf new) && isJust (serialSequence new)+            sequenceMoves = serialToIdentity || identityToSerial+            newType = typeText new.colType+            collate = maybe "" ((" collate " <>) . collationSql) new.collation+         in [create this (Shared, []) (col <> "drop default") | typeChanged, isJust (defaultExpr old)]+                <> [ create+                        this+                        ( Shared+                        , [MayRewriteTable, LongLock, ConversionMayFail]+                            <> [MayFail "recreating a view fails when its query relies on the old type; then edit the view" | Map.member (t, c) this.context.viewsAround]+                        )+                        (aroundViews [i|#{col}type #{newType}#{collate} using #{quoted c}::#{newType}|])+                   | typeChanged+                   ]+                <> case defaultExpr new of+                    _ | sequenceMoves -> []+                    Just e | defaultChanged || (typeChanged && isJust (defaultExpr old)) -> [create this (Shared, []) [i|#{col}set default #{e}|]]+                    Nothing | defaultChanged && not typeChanged -> [create this (Shared, []) (col <> "drop default")]+                    _ -> []+                <> notNullSteps old new+                <> case (identityKindOf old, identityKindOf new) of+                    _ | serialToIdentity, Just k <- identityKindOf new -> [create this (Shared, []) (toIdentity [i|#{identityKindSql k} as identity#{identityOptionsSql (identityOptionsOf new)}|])]+                    _ | identityToSerial -> [create this (Shared, []) (toSerial (typeText new.colType))]+                    (Nothing, Just k) -> [create this (Shared, []) [i|#{col}add generated #{identityKindSql k} as identity#{identityOptionsSql (identityOptionsOf new)}|]]+                    (Just _, Nothing) -> [create this (Shared, []) (col <> "drop identity")]+                    (Just a, Just b) ->+                        let clauses = ["set generated " <> identityKindSql b | a /= b] <> identityOptionChanges (identityOptionsOf old) (identityOptionsOf new)+                         in [create this (Shared, []) (col <> T.unwords clauses) | not (null clauses)]+                    _ -> []+                <> case (generatedOf old, generatedOf new) of+                    (Just (k, _), Just (k', e))+                        | k == k' && generatedOf old /= generatedOf new ->+                            [create this (Shared, [h | k == Stored, h <- [MayRewriteTable, LongLock]]) [i|#{col}set expression as (#{e})|]]+                    (a, b) | a /= b -> manual this "generated column added or removed"+                    _ -> []+    aroundViews statement = case Map.lookup (t, c) this.context.viewsAround of+        Just around | not (null around.dropBefore) -> T.intercalate ";\n" (around.dropBefore <> [statement] <> around.createAfter)+        _ -> statement+    serialSequence d = defaultExpr d >>= T.stripPrefix "nextval('" >>= T.stripSuffix "'::regclass)"+    tableLit = literal (qualified t)+    columnLit = literal (nameText c)+    serialName = let tableName = nameText t.name in qualified (QName t.schema (identifier [i|#{tableName}_#{nameText c}_seq|]))+    toIdentity :: Text -> Text+    toIdentity k =+        doBlock+            [i|+declare seq text := pg_get_serial_sequence(#{tableLit}, #{columnLit}); last bigint; called boolean; acl aclitem[];+begin+    execute format('select last_value, is_called from %s', seq) into last, called;+    select relacl into acl from pg_class where oid = seq::regclass;+    #{col}drop default;+    execute format('drop sequence %s', seq);+    #{col}add generated #{k};+    perform setval(pg_get_serial_sequence(#{tableLit}, #{columnLit}), last, called);+    #{grantAcl serialOf}+end |]+    toSerial colType =+        doBlock+            [i|+declare last bigint; called boolean; acl aclitem[];+begin+    execute format('select last_value, is_called from %s', pg_get_serial_sequence(#{tableLit}, #{columnLit})) into last, called;+    select relacl into acl from pg_class where oid = pg_get_serial_sequence(#{tableLit}, #{columnLit})::regclass;+    #{col}drop identity;+    create sequence #{serialName} as #{colType} owned by #{qualified t}.#{quoted c};+    perform setval(#{literal serialName}, last, called);+    #{col}set default nextval(#{literal serialName}::regclass);+    #{grantAcl (literal serialName)}+end |]+    serialOf = [i|pg_get_serial_sequence(#{tableLit}, #{columnLit})|] :: Text+    grantAcl :: Text -> Text+    grantAcl target =+        [i|execute coalesce((select string_agg(format('grant %s on sequence %s to %s', x.privilege_type, #{target}, case when x.grantee = 0 then 'public' else quote_ident(pg_get_userbyid(x.grantee)) end), '; ') from aclexplode(acl) x where x.grantee <> x.grantor), 'select');|]+    notNullSteps old new = case (isNotNull old, isNotNull new) of+        (False, True) ->+            create this (Shared, []) [i|#{alter}add #{named new}not null #{quoted c} not valid|]+                : [create this (Own, []) (onNotNull (notNullName new) "validate constraint" "") | notNullValid new]+        (True, False) -> [create this (Shared, []) (col <> "drop not null")]+        (True, True) ->+            [ create this (Shared, []) (onNotNull (notNullName old) "rename constraint" (" to " <> quoted n))+            | notNullName old /= notNullName new+            , let n = fromMaybe (identifier (T.concat [nameText t.name, "_", nameText c, "_not_null"])) (notNullName new)+            ]+                <> case (notNullValid old, notNullValid new) of+                    (False, True) -> [create this (Own, []) (onNotNull (notNullName new) "validate constraint" "")]+                    (True, False) -> manual this "a validated not null constraint cannot be made NOT VALID again"+                    _ -> []+        (False, False) -> []+    named :: ColumnDef -> Text+    named d = maybe "" (\n -> [i|constraint #{quoted n} |]) (notNullName d)+    onNotNull name action rest = case name of+        Just n -> [i|#{alter}#{action} #{quoted n}#{rest}|]+        Nothing ->+            let command = literal [i|#{T.replace "%" "%%" (alter <> action)} %I#{T.replace "%" "%%" rest}|]+                tableLiteral = literal (qualified t)+             in doBlock [i| begin execute format(#{command}, (select conname from pg_constraint where conrelid = #{tableLiteral}::regclass and contype = 'n' and conkey = array[(select attnum from pg_attribute where attrelid = #{tableLiteral}::regclass and attname = #{literal (nameText c)})])); end |]+++tableConstraintRecipe :: Target -> QName -> Identifier -> [Step]+tableConstraintRecipe this t c = typed this asConstraint \ch -> if all (.inheritedOnly) ch then [] else tableConstraintChange this t c ch+++tableConstraintChange :: Target -> QName -> Identifier -> Change ConstraintDef -> [Step]+tableConstraintChange this t c = \case+    Added def -> addConstraint def <> restoreComments this [TableConstraint t c]+    Dropped old -> [dropConstraint old]+    Changed old new+        | validates old new -> [undoneBy [] $ create this (Own, []) [i|#{alterT}validate constraint #{quoted c}|]]+        | validates new old -> manual this "a validated constraint cannot be made NOT VALID again"+        | otherwise -> dropConstraint old : addConstraint new <> restoreComments this [TableConstraint t c, Index (QName t.schema c)]+  where+    alterT :: Text+    alterT = [i|alter table #{qualified t} |]+    dropConstraint old =+        remove+            this+            (Shared, [MayFail "other objects depend on it, such as foreign keys; drop them first" | dependedOn] <> locksOther old)+            [i|#{alterT}drop constraint #{quoted c}|]+    dependedOn = any (`Set.member` this.context.withDependents) [TableConstraint t c, Index (QName t.schema c)]+    locksOther def = [LocksOther (qualified r.table) | Just r <- [def.references], r.table /= t]+    plain hazards def clause = create this (Shared, hazards <> locksOther def) [i|#{alterT}add constraint #{quoted c} #{clause}|]+    addConstraint def+        | t `Set.member` this.context.newTables = [plain [] def def.clause]+        | validatable def && def.validity == NotValidated = [plain [] def def.clause]+        | validatable def =+            [ plain [] def (def.clause <> notValid)+            , undoneBy [] $ create this (Own, []) [i|#{alterT}validate constraint #{quoted c}|]+            ]+        | Just (keyword, cols) <- simpleKey def+        , not (t `Set.member` this.context.partitionedTables) =+            let build = buildIndex this (None, [IndexBuild]) (concurrentBuild (QName t.schema c) [i|create unique index concurrently #{quoted c} on #{qualified t} (#{cols})|])+             in [ builds this (QName t.schema c) build+                , -- Dropping the constraint drops its index, which the build before made.+                  undoneBy [create this (Shared, []) [i|#{alterT}drop constraint #{quoted c}|], build]+                    $ create this (Shared, []) [i|#{alterT}add constraint #{quoted c} #{keyword} using index #{quoted c}|]+                ]+        | otherwise = [plain [LongLock, IndexBuild] def def.clause]+    validatable def = def.kind `elem` [Check, ForeignKey]+    -- A primary key or unique constraint on plain columns and nothing more, which an+    -- index built beforehand can back.+    simpleKey :: ConstraintDef -> Maybe (Text, Text)+    simpleKey def = do+        keyword <- case def.kind of+            PrimaryKey -> Just "PRIMARY KEY"+            Unique -> Just "UNIQUE"+            _ -> Nothing+        let cols = T.intercalate ", " (map quoted def.columns)+        guard (not (null def.columns) && def.clause == [i|#{keyword} (#{cols})|])+        pure (keyword, cols)+++domainConstraintRecipe :: Target -> TypeName -> Identifier -> [Step]+domainConstraintRecipe this d c = typed this asConstraint \case+    Added def -> add def <> restoreComments this [DomainConstraint d c]+    Dropped _ -> [remove this (Shared, []) [i|#{alterD}drop constraint #{quoted c}|]]+    Changed old new+        | validates old new -> [validate]+        | validates new old -> manual this "a validated constraint cannot be made NOT VALID again"+        | otherwise -> remove this (Shared, []) [i|#{alterD}drop constraint #{quoted c}|] : add new <> restoreComments this [DomainConstraint d c]+  where+    alterD :: Text+    alterD = [i|alter domain #{typeText d} |]+    validate = undoneBy [] $ create this (Own, []) [i|#{alterD}validate constraint #{quoted c}|]+    add def+        | def.validity == NotValidated = [create this (Shared, []) (addClause def.clause)]+        | otherwise = [create this (Shared, []) (addClause (def.clause <> notValid)), validate]+    addClause :: Text -> Text+    addClause clause = [i|#{alterD}add constraint #{quoted c} #{clause}|]+++indexRecipe :: Target -> QName -> [Step]+indexRecipe this ix = typed this asIndex \case+    Added def -> addIndex def <> restoreComments this [Index ix]+    Dropped def+        | def.table `Set.member` this.context.droppedTables -> []+        | def.partitioned -> [remove this (Shared, [LongLock]) ("drop index " <> qualified ix)]+        | otherwise -> [remove this (None, []) ("drop index concurrently " <> qualified ix)]+    Changed old new -> replaceIndex old new <> restoreComments this [Index ix]+  where+    replaceIndex old new+        | new.partitioned || old.partitioned = remove this (Shared, [LongLock]) ("drop index " <> qualified ix) : addIndex new+        | namesAlteredColumnOf this (== old.table) old.statement =+            remove this (None, []) ("drop index concurrently if exists " <> qualified ix) : addIndex new+        | otherwise =+            let tmp = identifier (takeBytes 59 (nameText ix.name) <> "_new")+                tmpIndex = QName ix.schema tmp+                oldName = quoted ix.name+             in [ builds this (QName ix.schema tmp)+                    $ buildIndex+                        this+                        (None, [IndexBuild])+                        (concurrentBuild (QName ix.schema tmp) (replaceInCode [i| INDEX #{oldName} ON |] [i| INDEX CONCURRENTLY #{quoted tmp} ON |] new.statement))+                , undoneBy (addIndex old <> restoreComments this [Index ix]) $ dropToRecreate this (None, []) ("drop index concurrently if exists " <> qualified ix)+                , undoneBy [create this (Shared, []) [i|alter index #{qualified ix} rename to #{quoted tmp}|]]+                    $ create this (Shared, []) [i|alter index #{qualified tmpIndex} rename to #{oldName}|]+                ]+    addIndex def+        | def.partitioned =+            [ create this (Shared, []) def.statement+            , case eachPartition ix def of+                Just query -> create this (None, [IndexBuild]) query+                Nothing ->+                    create+                        this+                        (Shared, [Manual [i|build the index on each partition with create index concurrently, then alter index #{qualified ix} attach partition each one; it stays invalid until every partition has one|]])+                        [i|-- create index concurrently and attach partition for #{qualified ix}|]+            ]+        | def.table `Set.member` this.context.newTables = [create this (Shared, []) def.statement]+        | otherwise = [builds this ix $ buildIndex this (None, [IndexBuild]) (concurrentBuild ix (replaceInCode " INDEX " " INDEX CONCURRENTLY " def.statement))]+++sequenceRecipe :: Target -> QName -> [Step]+sequenceRecipe this s = typed this asSequence \case+    -- Made by the column's change to serial; it only needs its options.+    Added def+        | s `Set.member` this.context.convertedSequences ->+            [ownSequence this (Shared, []) (alterSequence def)]+    Added def ->+        create this (Shared, []) [i|create sequence #{qualified s} #{sequenceOptions def}|]+            : [ownSequence this (Shared, []) [i|alter sequence #{qualified s} owned by #{ownerSql o}|] | Just o <- [def.ownedBy]]+    Dropped def+        | Just o <- def.ownedBy, ownedByDropped o -> []+        -- Dropped by the column's change to identity.+        | s `Set.member` this.context.convertedSequences -> []+        | otherwise -> [remove this (Shared, []) ("drop sequence " <> qualified s)]+    Changed _ new -> [ownSequence this (Shared, []) (alterSequence new)]+  where+    alterSequence def =+        let owner = maybe "none" ownerSql def.ownedBy+         in [i|alter sequence #{qualified s} #{sequenceOptions def} owned by #{owner}|]+    ownerSql :: (QName, Identifier) -> Text+    ownerSql (t, c) = [i|#{qualified t}.#{quoted c}|]+    -- Dropping the column, or its table, drops the sequence with it.+    ownedByDropped (t, c) = t `Set.member` this.context.droppedTables || (t, c) `Set.member` this.context.droppedColumns+++typeRecipe :: Target -> TypeName -> [Step]+typeRecipe this typ = typed this asType \case+    Added def -> [create this (Shared, []) (createType def)]+    Dropped (DomainType{}) -> [remove this (Shared, []) ("drop domain " <> t)]+    Dropped _ -> [remove this (Shared, []) ("drop type " <> t)]+    Changed (EnumType oldLabels) (EnumType newLabels)+        | oldLabels `L.isSubsequenceOf` newLabels ->+            [ create this (Own, []) [i|alter type #{t} add value #{literal label}#{placement}|]+            | (label, position) <- zip newLabels [0 :: Int ..]+            , label `notElem` oldLabels+            , let placement = case previous position newLabels of+                    Just before -> " after " <> literal before+                    Nothing -> maybe "" ((" before " <>) . literal) (L.headMaybe (filter (`elem` oldLabels) newLabels))+            ]+    Changed _ _ -> manual this "only adding enum values is automated"+  where+    t = typeText typ+    createType = \case+        DomainType base notNull dflt -> T.unwords ([[i|create domain #{t} as #{typeText base}|]] <> ["not null" | notNull] <> ["default " <> d | Just d <- [dflt]])+        def@(CompositeType _) ->+            let fields = fromMaybe "" (T.stripPrefix "composite " (printed (TypeDefinition def)))+             in [i|create type #{t} as #{fields}|]+        def -> [i|create type #{t} as #{printed (TypeDefinition def)}|]+    -- The label before the one at @position@, if any.+    previous position labels = if position == 0 then Nothing else L.headMaybe (L.drop (position - 1) labels)+++routineRecipe :: Target -> RoutineKind -> QName -> [TypeName] -> [Step]+routineRecipe this kind q args = case textual this of+    Added def -> replaceRoutine def []+    Changed old new+        | take 2 (T.lines old) == take 2 (T.lines new) -> replaceRoutine new []+        | otherwise -> replaceRoutine new [MayFail "fails when the return type or argument names change; then drop and create it"]+    Dropped _ -> [remove this (Shared, []) [i|drop #{keyword} #{qualified q}(#{argList args})|]]+  where+    keyword :: Text+    keyword = case kind of+        Function -> "function"+        Procedure -> "procedure"+        Aggregate -> "aggregate"+    replaceRoutine def hazards+        | kind == Aggregate = manual this "aggregates are not automated"+        | otherwise = case Map.lookup this.objectKey this.context.bodyChecks of+            Just (checked, check) | checked == def -> case check of+                DoesNotParse err -> manual this ("PostgreSQL's printed body does not parse back: " <> err)+                Repaired text -> [create this (Shared, hazards) (T.stripEnd text)]+                _ -> [create this (Shared, hazards) (T.stripEnd def)]+            _+                | "BEGIN ATOMIC" `T.isInfixOf` def || any ("RETURN " `T.isPrefixOf`) (T.lines def) ->+                    [create this (Shared, hazards <> [MayFail "a SQL-standard body that was not checked against the desired database"]) (T.stripEnd def)]+                | otherwise -> [create this (Shared, hazards) (T.stripEnd def)]+++viewRecipe :: Target -> QName -> [Step]+viewRecipe this v = typed this asView \case+    Added def -> [create this (Shared, []) ("create view " <> viewSql v def)]+    Changed old new+        | extendsColumns old new -> [create this (Shared, []) ("create or replace view " <> viewSql v new)]+        -- create or replace view keeps the columns as they were, adding any at the+        -- end; otherwise the view, and what depends on it, go and come back.+        | otherwise ->+            let dependents = Map.findWithDefault (Surrounding [] []) v this.context.viewDependents+             in map (create this (Shared, [])) dependents.dropBefore+                    <> [ create this (Shared, [MayFail "fails when other objects depend on the view; then drop them first"]) ("drop view " <> qualified v)+                       , create this (Shared, []) ("create view " <> viewSql v new)+                       ]+                    <> restoreOnView this v+                    <> restoreComments this (View v : [o | o@(OtherColumn OfView t _) <- Map.keys this.context.keptComments, t == v])+                    <> map (create this (Shared, [])) dependents.createAfter+    Dropped _ -> [remove this (Shared, []) ("drop view " <> qualified v)]+++materializedViewRecipe :: Target -> QName -> [Step]+materializedViewRecipe this v = typed this asView \case+    -- Created again by a revert, it gets back its indexes, grants and comments.+    Added def -> create this (Shared, []) ("create materialized view " <> viewSql v def) : restoreOnView this v <> restoreViewComments this v+    Changed _ new ->+        [ remove this (Shared, [MayFail "fails when other objects depend on it"]) ("drop materialized view " <> qualified v)+        , create this (Shared, [LongLock]) ("create materialized view " <> viewSql v new)+        ]+            <> restoreOnView this v+            <> restoreViewComments this v+    Dropped _ -> [remove this (Shared, []) ("drop materialized view " <> qualified v)]+++restoreViewComments :: Target -> QName -> [Step]+restoreViewComments this v = restoreComments this (MaterializedView v : [o | o@(OtherColumn OfMaterializedView t _) <- Map.keys this.context.keptComments, t == v])+++restoreOnView :: Target -> QName -> [Step]+restoreOnView this v = case Map.lookup v this.context.recreatedViews of+    Nothing -> []+    Just kept ->+        [create this (Shared, [IndexBuild]) def | (_, def) <- kept.keptIndexes]+            <> restoreComments this [Index q | (q, _) <- kept.keptIndexes]+            <> [configure this (createRank this.objectKey.object) (Shared, []) (revokeGranted (qualified v)) | isJust kept.keptGrants]+            <> maybe [] (\(k, def) -> map (asPartOfThis this) (privileges k k.object (Added def))) kept.keptGrants+++triggerRecipe :: Target -> QName -> Identifier -> [Step]+triggerRecipe this t n = case textual this of+    Added def -> create this (Shared, []) def : restoreComments this [Trigger t n]+    Changed old new+        | namesAlteredColumn this t old -> [dropTrigger DropPhase, create this (Shared, []) new] <> restoreComments this [Trigger t n]+        | Just rest <- T.stripPrefix "CREATE TRIGGER " new -> [replace this (Shared, []) ("CREATE OR REPLACE TRIGGER " <> rest)]+        | otherwise -> [dropTrigger CreatePhase, create this (Shared, []) new] <> restoreComments this [Trigger t n]+    Dropped _ -> [dropTrigger DropPhase]+  where+    dropTrigger = \case+        DropPhase -> remove this (Shared, []) dropSql+        CreatePhase -> dropToRecreate this (Shared, []) dropSql+    dropSql = [i|drop trigger #{quoted n} on #{qualified t}|]+++policyRecipe :: Target -> QName -> Identifier -> [Step]+policyRecipe this t n = case textual this of+    Added def -> createPolicy def : restoreComments this [Policy t n]+    Changed old new+        | namesAlteredColumn this t old -> [remove this (Shared, []) dropPolicy, createPolicy new] <> restoreComments this [Policy t n]+        | otherwise -> [dropToRecreate this (Shared, []) dropPolicy, createPolicy new] <> restoreComments this [Policy t n]+    Dropped _ -> [remove this (Shared, []) dropPolicy]+  where+    dropPolicy = [i|drop policy #{quoted n} on #{qualified t}|]+    createPolicy def = create this (Shared, []) [i|create policy #{quoted n} on #{qualified t}\n#{def}|]+++privileges :: ObjectKey -> ObjectId -> Change Definition -> [Step]+privileges key object change = case (target, traverse asAcl change) of+    (Nothing, _) -> []+    (Just onObject, Nothing) -> [step [Manual "the catalog described the privileges without their grants"] ("-- privileges on " <> onObject)]+    (_, Just (Dropped _)) -> []+    (Just onObject, Just (Added new)) -> reconcile onObject DefaultAcl new+    (Just onObject, Just (Changed old new)) -> reconcile onObject old new+  where+    step hazards sql =+        Step{phase = CreatePhase, role = Configures, rank = privilegesRank, object, sql, txn = Shared, hazards, key, change, undo = UndoObject}+    target = case object of+        Table t -> Just ("table " <> qualified t)+        View t -> Just ("table " <> qualified t)+        MaterializedView t -> Just ("table " <> qualified t)+        Sequence s -> Just ("sequence " <> qualified s)+        Routine Function q args -> Just [i|function #{qualified q}(#{argList args})|]+        Routine Procedure q args -> Just [i|procedure #{qualified q}(#{argList args})|]+        Schema s -> Just ("schema " <> quoted s)+        _ -> Nothing+    reconcile onObject old new = case (old, new) of+        (DefaultAcl, DefaultAcl) -> []+        (ExplicitAcl _, DefaultAcl) -> [step [Manual "privileges reset to the defaults"] ("-- reset privileges on " <> onObject)]+        _ -> grantChanges onObject (grantsOf old) (grantsOf new)+    -- What an object has when its ACL is the default, leaving out its owner's own+    -- privileges: PostgreSQL lets anyone execute a new function or procedure.+    grantsOf = \case+        ExplicitAcl grants -> grants+        DefaultAcl+            | isRoutine object -> Set.singleton (Grant Public "EXECUTE" False ByOwner)+            | otherwise -> Set.empty+    -- PostgreSQL takes no GRANTED BY but the current role's, so a grant another role+    -- gave runs as that role.+    grantChanges onObject old new = map asGrantor (grantEdits old new)+      where+        asGrantor edit = case (grantEditKey edit).grantor of+            ByOwner -> step [] (grantEditSql onObject edit)+            ByRole r -> step [] (doBlock [i| begin set local role #{quoted r}; #{grantEditSql onObject edit}; reset role; end |])+++-- | One grant of a privilege on an object: who gave it, to whom, and what.+data GrantKey = GrantKey+    { grantor :: Grantor+    , grantee :: Grantee+    , privilege :: Text+    }+    deriving stock (Eq, Ord)+++-- | A change to an object's grants.+data GrantEdit+    = RevokeGrant GrantKey+    | RevokeGrantOption GrantKey+    | -- | Grants it, with the grant option when the flag is set.+      GiveGrant GrantKey Bool+++grantEditKey :: GrantEdit -> GrantKey+grantEditKey = \case+    RevokeGrant k -> k+    RevokeGrantOption k -> k+    GiveGrant k _ -> k+++-- | What turns the grants @old@ into @new@. Grants another role gave are revoked first,+-- and given last: a role passes on only what it holds with the grant option.+grantEdits :: Set Grant -> Set Grant -> [GrantEdit]+grantEdits old new = revokes <> grants+  where+    before = grantOptions old+    now = grantOptions new+    revokes =+        L.sortOn (Down . grantDepth before . grantEditKey)+            $ [RevokeGrant k | k <- Map.keys (before `Map.difference` now)]+            <> [RevokeGrantOption k | (k, (True, False)) <- Map.toList (Map.intersectionWith (,) before now)]+    grants =+        L.sortOn+            (grantDepth now . grantEditKey)+            [GiveGrant k grantable | (k, grantable) <- Map.toList now, needsGrant grantable (Map.lookup k before)]+    -- Granted anew, or given the grant option it lacked.+    needsGrant grantable = \case+        Nothing -> True+        Just had -> grantable && not had+++-- | Each grant, with whether it has the grant option.+grantOptions :: Set Grant -> Map GrantKey Bool+grantOptions gs = Map.fromList [(GrantKey{grantor = g.grantor, grantee = g.grantee, privilege = g.privilege}, g.grantable) | g <- Set.toList gs]+++-- | How far down a chain of grants a grant is: the owner's are first; one by a role+-- comes after the grant that gave that role the privilege.+grantDepth :: Map GrantKey Bool -> GrantKey -> Int+grantDepth held = go Set.empty+  where+    go seen k = case k.grantor of+        ByOwner -> 0+        ByRole r+            | r `Set.member` seen -> 1+            | otherwise ->+                1 + fromMaybe 0 (L.maximumMaybe [go (Set.insert r seen) other | other <- Map.keys held, other.grantee == Role r, other.privilege == k.privilege])+++-- | The statement for a grant edit on @onObject@.+grantEditSql :: Text -> GrantEdit -> Text+grantEditSql onObject = \case+    RevokeGrant k -> [i|revoke #{onTarget k} from #{granteeOf k}|]+    RevokeGrantOption k -> [i|revoke grant option for #{onTarget k} from #{granteeOf k}|]+    GiveGrant k grantable -> [i|grant #{onTarget k} to #{granteeOf k}#{withGrantOption grantable}|]+  where+    onTarget, granteeOf :: GrantKey -> Text+    onTarget k = let granted = k.privilege in [i|#{granted} on #{onObject}|]+    granteeOf k = granteeSql k.grantee+    withGrantOption :: Bool -> Text+    withGrantOption grantable = if grantable then " with grant option" else ""+++comment :: Context -> ObjectKey -> Change Definition -> [Step]+comment ctx key change = case (commentTarget key.object, printed <$> change) of+    (Nothing, _) -> []+    (Just _, Dropped _) | key.object `Set.member` ctx.droppedObjects -> []+    (Just subject, Dropped _) -> [step (subject <> " is null")]+    (Just subject, Added new) -> [step [i|#{subject} is #{literal new}|]]+    (Just subject, Changed _ new) -> [step [i|#{subject} is #{literal new}|]]+  where+    step sql =+        Step{phase = CreatePhase, role = Configures, rank = commentRank, object = key.object, sql = "comment on " <> sql, txn = Shared, hazards = [], key, change, undo = UndoObject}+++-- | What @comment on@ names the object as.+commentTarget :: ObjectId -> Maybe Text+commentTarget = \case+    Table t -> Just ("table " <> qualified t)+    View t -> Just ("view " <> qualified t)+    MaterializedView t -> Just ("materialized view " <> qualified t)+    Column t c -> Just [i|column #{qualified t}.#{quoted c}|]+    OtherColumn OfView t c -> Just [i|column #{qualified t}.#{quoted c}|]+    OtherColumn OfMaterializedView t c -> Just [i|column #{qualified t}.#{quoted c}|]+    Index ix -> Just ("index " <> qualified ix)+    Sequence s -> Just ("sequence " <> qualified s)+    TableConstraint t c -> Just [i|constraint #{quoted c} on #{qualified t}|]+    DomainConstraint d c -> Just [i|constraint #{quoted c} on domain #{typeText d}|]+    Trigger t n -> Just [i|trigger #{quoted n} on #{qualified t}|]+    Policy t n -> Just [i|policy #{quoted n} on #{qualified t}|]+    Routine Function q args -> Just [i|function #{qualified q}(#{argList args})|]+    Routine Procedure q args -> Just [i|procedure #{qualified q}(#{argList args})|]+    Routine Aggregate q args -> Just [i|aggregate #{qualified q}(#{argList args})|]+    Type t -> Just ("type " <> typeText t)+    Schema s -> Just ("schema " <> quoted s)+    Extension e -> Just ("extension " <> quoted e)+    _ -> Nothing+++-- | A routine's argument types, as its signature lists them.+argList :: [TypeName] -> Text+argList = T.intercalate ", " . map typeText+++commentRank :: Int+commentRank = 16+++-- | The column's declaration after its name, as @add column@ and @create table@ take it.+columnSql :: ColumnDef -> Text+columnSql c =+    T.unwords+        $ [typeText c.colType]+        <> ["collate " <> collationSql co | Just co <- [c.collation]]+        <> [[i|generated always as (#{e}) #{storageSql storage}|] | Just (storage, e) <- [generatedOf c]]+        <> [[i|generated #{identityKindSql kind} as identity#{identityOptionsSql options}|] | IdentityColumn kind options <- [c.value]]+        <> [maybe "" (\n -> [i|constraint #{quoted n} |]) (notNullName c) <> "not null" | isNotNull c]+        <> ["default " <> e | Just e <- [defaultExpr c]]+++identityOptionsSql :: [Text] -> Text+identityOptionsSql = \case+    [] -> ""+    options -> [i| (#{T.unwords options})|]+++-- | The @set@ clauses of @alter column@ that turn the identity options @old@ into @new@.+identityOptionChanges :: [Text] -> [Text] -> [Text]+identityOptionChanges old new =+    ["set " <> o | o <- new, o `notElem` old]+        <> ["set " <> reset k | k <- nubOrd (map optionKey old), k `notElem` map optionKey new]+  where+    optionKey o = if o == "cycle" then o else T.stripEnd (fst (T.breakOnEnd " " o))+    minimum' = fromMaybe "1" (L.headMaybe [v | o <- new, Just v <- [T.stripPrefix "minvalue " o]])+    reset = \case+        "increment by" -> "increment by 1"+        "minvalue" -> "no minvalue"+        "maxvalue" -> "no maxvalue"+        "start with" -> "start with " <> minimum'+        "cache" -> "cache 1"+        "cycle" -> "no cycle"+        k -> k+++-- | A view's name, options and query, as @create view@ takes them after its keywords.+viewSql :: QName -> ViewDef -> Text+viewSql v def =+    let withClause :: Text+        withClause = foldMap (\o -> [i| with (#{T.intercalate ", " o})|]) def.options+        query = T.dropWhileEnd (\ch -> ch == ';' || ch == ' ' || ch == '\n') (T.stripStart def.query)+     in [i|#{qualified v}#{withClause} as\n#{query}|]+++-- | A concurrent index build that first fails when an invalid index of that name is left+-- from an earlier failed build.+concurrentBuild :: QName -> Text -> Text+concurrentBuild index build =+    let regclass = literal (qualified index)+        message = literal [i|index #{qualified index} is invalid from an earlier failed build; drop it first|]+        failIfInvalid =+            doBlock+                [__i|+                    \nbegin+                        if exists (+                            select from pg_index+                            where indexrelid = to_regclass(#{regclass}) and not indisvalid+                        ) then+                            raise exception using message = #{message};+                        end if;+                    end\n+                |]+     in [i|#{failIfInvalid};\n\n#{build}|]+++-- | A query whose rows psql runs with @\\gexec@: for each partition of the table with no+-- index attached to the partitioned index @ix@ yet, a concurrent build of its index and+-- the attach. It reads the partitions when it runs, so it covers those the database has+-- then. Nothing when @def@ is not the @ON ONLY@ statement it expects.+eachPartition :: QName -> IndexDef -> Maybe Text+eachPartition ix def = do+    let escape = T.replace "%" "%%"+        onOnly = escape [i| INDEX #{quoted ix.name} ON ONLY #{qualified def.table} |]+        statement = escape def.statement+        build = replaceInCode onOnly " INDEX CONCURRENTLY IF NOT EXISTS %I ON %I.%I " statement+        name = [i|left(c.relname || '_' || #{literal (nameText ix.name)}, 63)|] :: Text+    guard (build /= statement)+    pure+        [__i|+            select+                format(#{literal build}, #{name}, n.nspname, c.relname),+                format('alter index %s attach partition %I.%I', #{literal (qualified ix)}, n.nspname, #{name})+            from pg_inherits h+            join pg_class c on c.oid = h.inhrelid+            join pg_namespace n on n.oid = c.relnamespace+            where h.inhparent = #{literal (qualified def.table)}::regclass+                and not exists (+                    select from pg_inherits a+                    join pg_index x on x.indexrelid = a.inhrelid+                    where a.inhparent = #{literal (qualified ix)}::regclass and x.indrelid = c.oid+                )+            order by c.relname+            \\gexec+        |]+++-- | The longest prefix of at most @n@ bytes in UTF-8.+takeBytes :: Int -> Text -> Text+takeBytes n = T.pack . go 0 . T.unpack+  where+    go _ [] = []+    go used (ch : rest)+        | used + size ch > n = []+        | otherwise = ch : go (used + size ch) rest+    size ch = B.length (encodeUtf8 (T.singleton ch))
+ src/Sqiff/Recreate.hs view
@@ -0,0 +1,230 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What has to go and come back around a column whose type changes: PostgreSQL refuses+-- to retype a column that views, or the policies, triggers and routines bound to them,+-- still use.+module Sqiff.Recreate (+    Recreation (..),+    viewsAroundTypeChanges,+    withViewsAround,+    withViewsReplaced,+    retypedIn,+    standardBody,+) where++import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Definition+import Sqiff.Dependencies (Dependencies, dependsOn, edges, noDependencies, reachableFrom, referencesOf)+import Sqiff.Diff (Change (..), Changes, affected)+import Sqiff.Graph (topoOrder)+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Plan (context)+import Sqiff.Recipe (Context (..), Step (..), Surrounding (..), recipe, revokeGranted)+++-- | Adds to the context what to drop and create again around each retyped column, by+-- what depends on it in @schema@ by @deps@.+withViewsAround :: Schema -> Dependencies -> Changes -> Context -> Context+withViewsAround schema deps changes ctx =+    ctx{viewsAround = Map.map (.statements) (viewsAroundTypeChanges exact schema deps (retypedIn changes))}+  where+    known = Set.fromList [k.object | k <- Map.keys schema, k.aspect == Definition]+    exact = affected known deps changes+++-- | Adds to the context what to drop and create again around each view whose columns+-- change, by what depends on it in the database being changed (@deps@), as the desired+-- one (@toSchema@) has it.+withViewsReplaced :: Schema -> Dependencies -> Changes -> Context -> Context+withViewsReplaced toSchema deps changes ctx =+    ctx{viewDependents = viewsToRecreate toSchema deps changes}+++-- | The columns whose type or collation changes, with their identities.+-- [allow:SqiffNamedTuples] pre-existing at adoption+retypedIn :: Changes -> [(QName, Identifier, ObjectId)]+retypedIn changes =+    [ (t, c, k.object)+    | (k, Changed (ColumnDefinition old) (ColumnDefinition new)) <- Map.toList changes+    , k.aspect == Definition+    , Column t c <- [k.object]+    , columnTypeChanged old new+    ]+++-- | The objects dropped and created again around a retyped column.+data Recreation = Recreation+    { members :: Set ObjectId+    , statements :: Surrounding+    }+++-- | For each retyped column, the views, policies, triggers and routines that hold it,+-- with the statements that drop them and the ones that create them again.+-- [allow:SqiffNamedTuples] pre-existing at adoption+viewsAroundTypeChanges :: Map ObjectId (Set ObjectId) -> Schema -> Dependencies -> [(QName, Identifier, ObjectId)] -> Map (QName, Identifier) Recreation+viewsAroundTypeChanges exact schema deps retyped =+    Map.fromList+        [ ((t, c), Recreation{members, statements = Surrounding{dropBefore = map dropStatement (reverse order), createAfter = concatMap (createAgain attached) order}})+        | (t, c, column) <- retyped+        , let closure = Map.findWithDefault Set.empty column exact+              onColumn = Set.filter (\a -> isPolicyOrTrigger a && dependsOn deps a column) closure+              members = held schema deps column closure (Set.filter isView closure <> onColumn)+              order = inDependencyOrder deps members+        , not (Set.null members)+        ]+  where+    attached = attachedIn schema+    isPolicyOrTrigger = \case+        Policy{} -> True+        Trigger{} -> True+        _ -> False+++-- | For each view whose columns change other than by new ones at the end, which+-- @create or replace view@ refuses, the statements that drop what depends on it in the+-- database being changed, and the ones that create those again as @toSchema@ has them;+-- one the plan drops is not created again.+viewsToRecreate :: Schema -> Dependencies -> Changes -> Map QName Surrounding+viewsToRecreate toSchema deps changes =+    Map.fromList+        [ (v, Surrounding{dropBefore = map (dropWith " if exists") (reverse order), createAfter = concatMap (createAgain attached) (filter wanted order)})+        | (k, Changed (ViewDefinition old) (ViewDefinition new)) <- Map.toList changes+        , k.aspect == Definition+        , View v <- [k.object]+        , not (extendsColumns old new)+        , -- Every dependent, changed ones included: they go before the view does.+        let closure = reachableFrom deps (Set.singleton k.object)+            order = inDependencyOrder deps (held toSchema deps k.object closure (Set.filter isView closure))+        ]+  where+    attached = attachedIn toSchema+    wanted a = definitionKey a `Map.member` toSchema+++-- | The members in the order they can be created, by the relations they depend on.+inDependencyOrder :: Dependencies -> Set ObjectId -> [ObjectId]+inDependencyOrder deps members =+    topoOrder members [(d, r) | e <- edges deps, let d = relationOf e.dependent, let r = relationOf e.referenced, d `Set.member` members, r `Set.member` members]+++-- | @members@ and the routines whose definitions hold @start@ or one of them, until no+-- more do.+held :: Schema -> Dependencies -> ObjectId -> Set ObjectId -> Set ObjectId -> Set ObjectId+held schema deps start closure members =+    let views = Set.filter isView members+        holds r = case printed <$> Map.lookup (definitionKey r) schema of+            Just def+                | standardBody def -> any (\x -> x == start || relationOf x `Set.member` members) (referencesOf deps r)+                | otherwise -> any (\v -> qualifiedName v `T.isInfixOf` signature def) views+            Nothing -> False+        more = Set.filter (\r -> isRoutine r && r `Set.notMember` members && holds r) closure+     in if Set.null more then members else held schema deps start closure (members <> more)+  where+    signature = T.unlines . takeWhile (\l -> not ("AS " `T.isPrefixOf` T.stripStart l || "BEGIN ATOMIC" `T.isInfixOf` l)) . T.lines+++-- | A schema with what belongs to each relation found once, for 'createAgain'.+data Attached = Attached+    { attachedSchema :: Schema+    , indexesAndTriggers :: Map QName [Text]+    -- ^ The definitions of each relation's indexes and triggers, in key order.+    , comments :: Map ObjectId [(ObjectKey, Definition)]+    -- ^ The comments on each relation and its parts, in key order.+    }+++attachedIn :: Schema -> Attached+attachedIn schema =+    Attached+        { attachedSchema = schema+        , indexesAndTriggers =+            Map.fromListWith+                (flip (<>))+                [ (t, [printed def])+                | (k, def) <- Map.toList schema+                , k.aspect == Definition+                , Just t <- [indexedOrTriggered k.object def]+                ]+        , comments = Map.fromListWith (flip (<>)) [(relationOf k.object, [(k, def)]) | (k, def) <- Map.toList schema, k.aspect == Comment]+        }+  where+    indexedOrTriggered object def = case object of+        Index _ | IndexDefinition ix <- def -> Just ix.table+        Trigger t _ -> Just t+        _ -> Nothing+++-- | The statements that create @a@ as the schema has it, with its grants, indexes,+-- triggers and comments.+createAgain :: Attached -> ObjectId -> [Text]+createAgain attached a =+    concat+        [ [revokeGranted (qualifiedName a) | aspect == Privileges, isView a] <> stepsFor key (Added def)+        | aspect <- [Definition, Privileges]+        , let key = ObjectKey aspect a+        , Just def <- [Map.lookup key attached.attachedSchema]+        , -- A view created again starts with the default privileges.+        aspect == Definition || not (isDefault def)+        ]+        <> maybe [] (\t -> Map.findWithDefault [] t attached.indexesAndTriggers) (isRelation a)+        <> concat [stepsFor k (Added def) | (k, def) <- Map.findWithDefault [] a attached.comments]+  where+    ctx0 = context Map.empty Map.empty Map.empty noDependencies Map.empty+    stepsFor key c = map (.sql) (recipe ctx0 key c)+++-- | The relation a column belongs to; any other object is its own.+relationOf :: ObjectId -> ObjectId+relationOf = \case+    Column t _ -> Table t+    OtherColumn OfView t _ -> View t+    OtherColumn OfMaterializedView t _ -> MaterializedView t+    OtherColumn OfCompositeType t _ -> Unknown (Address "composite type" [nameText t.schema, nameText t.name] [])+    OtherColumn OfForeignTable t _ -> Unknown (Address "foreign table" [nameText t.schema, nameText t.name] [])+    object -> object+++-- | An object's name as SQL writes it after its kind.+qualifiedName :: ObjectId -> Text+qualifiedName object = case (toAddress object).objectNames of+    [s, n] -> qualified (qname s n)+    names -> T.intercalate "." names+++-- | The statement that drops a view, routine, policy or trigger around a type change.+dropStatement :: ObjectId -> Text+dropStatement = dropWith ""+++-- | 'dropStatement' with @ifExists@ after the kind of object.+dropWith :: Text -> ObjectId -> Text+dropWith ifExists object = case object of+    Routine _ q args ->+        let list = T.intercalate ", " (map typeText args)+         in [i|drop #{keyword}#{ifExists} #{qualified q}(#{list})|]+    Policy t n -> [i|drop policy#{ifExists} #{quoted n} on #{qualified t}|]+    Trigger t n -> [i|drop trigger#{ifExists} #{quoted n} on #{qualified t}|]+    _ -> [i|drop #{keyword}#{ifExists} #{qualifiedName object}|]+  where+    keyword = (toAddress object).objectType+++-- | A SQL-standard body, which PostgreSQL parses once and tracks in pg_depend.+standardBody :: Text -> Bool+standardBody def = "BEGIN ATOMIC" `T.isInfixOf` def || any ("RETURN " `T.isPrefixOf`) (T.lines def)+++isDefault :: Definition -> Bool+isDefault = \case+    AclDefinition DefaultAcl -> True+    _ -> False
+ src/Sqiff/Rewrite.hs view
@@ -0,0 +1,658 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Rewrites a table's deploy file so it creates the table as a database has it, keeping+-- the file's text wherever it already matches.+module Sqiff.Rewrite (+    Rewrite (..),+    rewriteFile,+    fileDrift,+) where++import Data.Char (isDigit, isSpace)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Definition hiding (tableText)+import Sqiff.Diff (Change (..), Changes, diff)+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Recipe (columnSql)+import Sqiff.Script (splitStatements)+import Sqiff.Sqitch.Units (tidyConstraint, tidyIndex)+import Sqiff.Sql (Region (..), codeWords, parenthesised, regions, replaceInCode, splitTopLevel, topWords)+import Sqiff.Sql qualified as Sql+++data Rewrite = Rewrite+    { text :: Text+    , unplaced :: [Text]+    -- ^ Differences the rewrite leaves for a person, one line each.+    }+++-- | What differs between the table the file creates and the one in the database, without+-- grants, validity, and the triggers, policies and indexes that live in files of their own.+fileDrift :: Set Identifier -> Schema -> Schema -> Changes+fileDrift ownFiles fromFile live = Map.filterWithKey kept (diff same fromFile live)+  where+    same k a b = a == b || normalise k a == normalise k b+    -- A file cannot say whether a constraint is validated, nor name a not-null+    -- constraint the way PostgreSQL names it after a rename.+    normalise k = \case+        ColumnDefinition c -> ColumnDefinition c{nullability = plainNotNull c.nullability}+        ConstraintDefinition c | TableConstraint{} <- k.object -> ConstraintDefinition (withoutValidity c)+        def -> def+    plainNotNull = \case+        NotNull _ name -> NotNull Validated (mfilter (not . defaultNotNullName) name)+        Nullable -> Nullable+    defaultNotNullName n = "_not_null" `T.isSuffixOf` T.dropWhileEnd isDigit (nameText n)+    kept k c = k.aspect /= Privileges && not (elsewhere k.object c)+    elsewhere o = \case+        Added _ -> case o of+            Trigger _ _ -> True+            Policy _ _ -> True+            Index q -> q.name `Set.member` ownFiles+            _ -> False+        _ -> False+++-- | The file's text changed so that it creates the table as @live@ has it. @fromFile@ is+-- what the file creates now, @order@ the live column order, @ownFiles@ the indexes with+-- deploy files of their own.+rewriteFile :: QName -> Set Identifier -> [Identifier] -> Schema -> Schema -> Text -> Either Text Rewrite+rewriteFile table ownFiles order live fromFile original = do+    parts <- pieces original+    let changes = fileDrift ownFiles fromFile live+        plan = planRewrite table order changes parts+    pure+        Rewrite+            { text = applyRewrite parts plan+            , unplaced = [describeChange k c | (k, c) <- Map.toList changes, k `Set.notMember` plan.handled]+            }+++-- | What a rewrite does to one statement of the file.+data StatementEdit+    = ReplaceStatement Text+    | RemoveStatement+++-- | A rewrite decided before any text is joined: what becomes of the file's statements,+-- what goes after them, and the differences it settles. Statements are numbered by their+-- place among the file's 'Part's.+data RewritePlan = RewritePlan+    { edits :: Map Int StatementEdit+    , insertAfter :: Map Int [Text]+    -- ^ New statements, in order, each to follow the numbered one.+    , handled :: Set ObjectKey+    }+++-- | The differences the rewrite can place, by object.+data Drift = Drift+    { definitions :: Map ObjectId (Change Definition)+    , comments :: Map ObjectId (Change Text)+    }+++-- | A statement of the file: its number among the parts, its text and what it does.+data Statement = Statement+    { at :: Int+    , text :: Text+    , kind :: Kind+    }+++-- | The file's @create table@ statement with the differences applied, and the objects it+-- now places.+data TableEdit = TableEdit+    { at :: Int+    , text :: Text+    , placed :: Set ObjectId+    }+++-- | An edit of an index's or comment's own statement, and the difference it settles.+data SettledEdit = SettledEdit+    { at :: Int+    , edit :: StatementEdit+    , settles :: ObjectKey+    }+++-- | What the file lacks of the table's settings.+data TableSettings = TableSettings+    { alters :: [Text]+    -- ^ Statements that turn them on, to follow @create table@.+    , options :: Maybe Text+    -- ^ A @with (...)@ clause for @create table@.+    }+++-- | The statements new ones go after: the last @create table@, the last index and the+-- last comment left in the file, an index falling back on the table and a comment on an+-- index. Nothing when the file has no such statement.+data Anchors = Anchors+    { table :: Maybe Int+    , index :: Maybe Int+    , comment :: Maybe Int+    }+++-- | Decides the rewrite: the edits of the file's statements, the statements to add, and+-- which of @changes@ that places.+planRewrite :: QName -> [Identifier] -> Changes -> [Part] -> RewritePlan+planRewrite table order changes parts =+    RewritePlan+        { edits =+            Map.fromList+                ( [(e.at, ReplaceStatement e.text) | Just e <- [tableEdit]]+                    <> [(e.at, e.edit) | e <- statementEdits]+                )+        , insertAfter =+            Map.fromListWith+                (flip (<>))+                ( [(a, settings.alters) | Just a <- [anchors.table], Just settings <- [missingSettings], not (null settings.alters)]+                    <> [(a, [indexCode (statementIndent parts a) def]) | Just a <- [anchors.index], (_, def) <- newIndexes]+                    <> [(a, [commentCode (statementIndent parts a) addr txt]) | Just a <- [anchors.comment], (addr, txt) <- newComments]+                )+        , handled =+            Set.unions+                [ maybe Set.empty (\e -> Set.map definitionKey (Set.filter (not . isTable) e.placed)) tableEdit+                , Set.fromList [e.settles | e <- statementEdits]+                , if isJust anchors.index then Set.fromList [definitionKey (Index q) | (q, _) <- newIndexes] else Set.empty+                , if isJust anchors.comment then Set.fromList [ObjectKey Comment a | (a, _) <- newComments] else Set.empty+                , if settingsPlaced then Set.singleton (definitionKey (Table table)) else Set.empty+                ]+        }+  where+    drift = splitDrift changes+    statements = fileStatements table parts+    missingSettings = settingsDrift table drift+    tableEdit = planTableEdit table order drift (missingSettings >>= (.options)) statements+    statementEdits = indexEdits table parts drift statements <> commentEdits drift statements+    anchors = anchorsOf statements (Set.fromList [e.at | e@SettledEdit{edit = RemoveStatement} <- statementEdits])+    newIndexes = [(q, printed def) | (Index q, Added def) <- Map.toList drift.definitions]+    newComments = [(addr, txt) | (addr, Added txt) <- Map.toList drift.comments, isJust (commentTarget addr)]+    -- The table counts as handled only when its settings are placed.+    settingsPlaced = case missingSettings of+        Just settings -> (null settings.alters || isJust anchors.table) && (isNothing settings.options || any (\e -> Table table `Set.member` e.placed) tableEdit)+        Nothing -> False+    isTable = \case+        Table _ -> True+        _ -> False+++-- | The changes to definitions and to comments; grants are not the file's.+splitDrift :: Changes -> Drift+splitDrift changes =+    Drift+        { definitions = Map.fromList [(k.object, c) | (k, c) <- Map.toList changes, k.aspect == Definition]+        , comments = Map.fromList [(k.object, printed <$> c) | (k, c) <- Map.toList changes, k.aspect == Comment]+        }+++-- | The file's statements, each with what it does to @table@.+fileStatements :: QName -> [Part] -> [Statement]+fileStatements table parts = [Statement{at, text = s, kind = classify table (snd (splitLead s))} | (at, Stmt s) <- zip [0 ..] parts]+++-- | The settings the file lacks, when the table's settings differ from the file's.+settingsDrift :: QName -> Drift -> Maybe TableSettings+settingsDrift table drift = case Map.lookup (Table table) drift.definitions of+    Just (Changed (TableDefinition fileDef) (TableDefinition liveDef)) -> tableSettings table fileDef liveDef+    _ -> Nothing+++-- | The first @create table@ statement with the table's column and constraint differences+-- applied, and @options@ added; nothing when the file has none or its column list cannot+-- be read.+planTableEdit :: QName -> [Identifier] -> Drift -> Maybe Text -> [Statement] -> Maybe TableEdit+planTableEdit table order drift options statements = do+    s <- L.find (\s -> s.kind == CreatesTable) statements+    let (lead, code) = splitLead s.text+        columns = [(c, ch') | (Column t c, ch) <- Map.toList drift.definitions, t == table, Just ch' <- [traverse asColumn ch]]+        constraints = [(c, printed <$> ch) | (TableConstraint t c, ch) <- Map.toList drift.definitions, t == table]+    (code', placed) <- editCreateTable table order columns constraints options code+    pure TableEdit{at = s.at, text = lead <> code', placed}+++-- | The table's index statements whose index changed, rewritten, or that the database+-- does not have as written, removed.+indexEdits :: QName -> [Part] -> Drift -> [Statement] -> [SettledEdit]+indexEdits table parts drift statements =+    [ SettledEdit{at = s.at, edit, settles = definitionKey (Index q)}+    | s@Statement{kind = CreatesIndex ix} <- statements+    , let q = QName table.schema ix+    , Just ch <- [Map.lookup (Index q) drift.definitions]+    , let (lead, _) = splitLead s.text+          edit = case ch of+            Changed _ def -> ReplaceStatement (lead <> indexCode (statementIndent parts s.at) (printed def))+            _ -> RemoveStatement+    ]+++-- | The comment statements whose comment changed, with the new text, or that the database+-- does not have as written, removed.+commentEdits :: Drift -> [Statement] -> [SettledEdit]+commentEdits drift statements =+    [ SettledEdit{at = s.at, edit, settles = ObjectKey Comment addr}+    | s@Statement{kind = Comments addr} <- statements+    , Just ch <- [Map.lookup addr drift.comments]+    , let (lead, code) = splitLead s.text+          edit = case ch of+            Changed _ new -> ReplaceStatement (lead <> withLiteral new code)+            _ -> RemoveStatement+    ]+++-- | Where new statements go, among the statements not in @removed@.+anchorsOf :: [Statement] -> Set Int -> Anchors+anchorsOf statements removed = Anchors{table, index, comment}+  where+    lastOf p = L.lastMaybe [s.at | s <- statements, p s.kind, s.at `Set.notMember` removed]+    table = lastOf (== CreatesTable)+    index = lastOf (\case CreatesIndex _ -> True; _ -> False) <|> table+    comment = lastOf (\case Comments _ -> True; _ -> False) <|> index+++-- | The file's text with the plan's edits made and its new statements added, each after+-- a semicolon and a blank line at its anchor's indentation.+applyRewrite :: [Part] -> RewritePlan -> Text+applyRewrite parts plan = renderOut (concat (zipWith (partOut parts plan) [0 ..] parts))+++-- | What one part of the file becomes.+partOut :: [Part] -> RewritePlan -> Int -> Part -> [Out]+partOut parts plan n = \case+    Gap g -> [Out g]+    Stmt s -> case Map.lookup n plan.edits of+        Just RemoveStatement -> [Gone]+        Just (ReplaceStatement t) -> Out t : inserted+        Nothing -> Out s : inserted+  where+    inserted = concat [[Out [i|;\n\n#{statementIndent parts n}|], Out c] | c <- Map.findWithDefault [] n plan.insertAfter]+++-- | For a table whose settings the file lacks, the statements that turn them on and the+-- storage options for @create table@; nothing when the file has a setting the table lacks,+-- or other options than it.+tableSettings :: QName -> TableDef -> TableDef -> Maybe TableSettings+tableSettings table file live = do+    let name = qualified table+        added setting = setting live && not (setting file)+        alters =+            [[i|alter table #{name} enable row level security|] | added (.rowSecurity)]+                <> [[i|alter table #{name} force row level security|] | added (.forceRowSecurity)]+    guard (file.unlogged == live.unlogged && file.partitionBy == live.partitionBy && file.partitionOf == live.partitionOf)+    -- The file may lack a setting the table has, not have one the table lacks.+    guard ((live.rowSecurity || not file.rowSecurity) && (live.forceRowSecurity || not file.forceRowSecurity))+    guard (null file.options || file.options == live.options)+    pure TableSettings{alters, options = if file.options == live.options then Nothing else withOptions live.options}+++describeChange :: ObjectKey -> Change a -> Text+describeChange k c =+    let name = render k.object <> if k.aspect == Comment then " (comment)" else ""+        what = case c of+            Added _ -> "in the database, not in the file" :: Text+            Dropped _ -> "in the file, not in the database"+            Changed _ _ -> "differs from the database"+     in [i|#{name}: #{what}|]+++-- | The text between statements, and the statements without their semicolons.+data Part = Gap Text | Stmt Text+++pieces :: Text -> Either Text [Part]+pieces original = splitStatements original >>= go original+  where+    go rest [] = Right [Gap rest]+    go rest (s : ss) = case [(stmt, found) | stmt <- [s, snd (splitLead s)], let found = T.breakOn stmt rest, not (T.null (snd found))] of+        [] -> Left "a statement cannot be found in the file's text"+        (stmt, (before, after)) : _ -> (\more -> Gap before : Stmt stmt : more) <$> go (T.drop (T.length stmt) after) ss+++data Out = Out Text | Gone+++-- | Joins the output; a removed statement takes its semicolon and line with it.+renderOut :: [Out] -> Text+renderOut = go ""+  where+    go acc = \case+        [] -> acc+        Gone : Out g : rest -> go (trimEnd acc) (Out (afterRemoved acc g) : rest)+        Gone : rest -> go acc rest+        Out t : rest -> go (acc <> t) rest+    trimEnd = T.dropWhileEnd (\c -> c == ' ' || c == '\t')+    afterRemoved acc g =+        let g1 = fromMaybe g (T.stripPrefix ";" g)+            (line, more) = T.breakOn "\n" g1+            g2 = if T.all isSpace line then T.drop 1 more else g1+         in if "\n\n" `T.isSuffixOf` trimEnd acc && "\n" `T.isPrefixOf` g2 then T.drop 1 g2 else g2+++-- | The indentation a statement's code starts with.+statementIndent :: [Part] -> Int -> Text+statementIndent parts n = case drop n parts of+    Stmt s : _+        | let (lead, _) = splitLead s+        , not (T.null lead) ->+            T.takeWhileEnd (== ' ') lead+    _ -> case drop (n - 1) parts of+        Gap g : _ | n > 0 -> T.takeWhileEnd (== ' ') g+        _ -> ""+++-- | A statement's leading comment lines and indentation, and its code.+splitLead :: Text -> (Text, Text)+splitLead = go ""+  where+    go acc t =+        let (ws, rest) = T.span isSpace t+         in if "--" `T.isPrefixOf` rest+                then let (line, more) = T.breakOn "\n" rest in go (acc <> ws <> line) more+                else (acc <> ws, rest)+++data Kind = CreatesTable | CreatesIndex Identifier | Comments ObjectId | OtherStatement+    deriving stock (Eq)+++classify :: QName -> Text -> Kind+classify table code = case dropWords ["unlogged"] (drop 1 lower) of+    "table" : _ | take 1 lower == ["create"], tableName (dropWords ["if", "not", "exists"] (dropWords ["table"] (dropWords ["unlogged"] (drop 1 ws)))) == Just table -> CreatesTable+    _ -> classifyOther+  where+    classifyOther = case lower of+        "create" : _ | Just (ix, target) <- indexOf (drop 1 ws), target == Just table -> CreatesIndex ix+        "comment" : "on" : _ | Just addr <- commentOn (drop 2 ws), belongs addr -> Comments addr+        _ -> OtherStatement+    ws = codeWords "" code+    lower = map T.toLower ws+    tableName = \case+        t : _ -> parseQName (T.takeWhile (/= '(') t)+        [] -> Nothing+    indexOf ts = do+        rest <- stripWord "index" (dropWords ["unique"] ts)+        name : more <- Just (dropWords ["if", "not", "exists"] (dropWords ["concurrently"] rest))+        guard (T.toLower name /= "on")+        target : _ <- dropWords ["only"] <$> stripWord "on" more+        pure (identifier (unquote name), parseQName (T.takeWhile (/= '(') target))+    commentOn ts = do+        kind : rest <- Just ts+        let target = takeWhile ((/= "is") . T.toLower) rest+        case (T.toLower kind, map unquote . nameParts <$> target) of+            ("table", [[s, t]]) -> Just (Table (qname s t))+            ("column", [[s, t, c]]) -> Just (Column (qname s t) (identifier c))+            ("index", [[s, n]]) -> Just (Index (qname s n))+            ("constraint", [[n], ["on"], [s, t]]) -> Just (TableConstraint (qname s t) (identifier n))+            _ -> Nothing+    belongs = \case+        Index _ -> True+        Table q -> q == table+        object -> owningTable object == Just table+    parseQName t = case map unquote (nameParts t) of+        [s, n] -> Just (qname s n)+        [n] -> Just (qname "public" n)+        _ -> Nothing+++dropWords :: [Text] -> [Text] -> [Text]+dropWords expected ts =+    let n = length expected+     in if map T.toLower (take n ts) == expected then drop n ts else ts+++stripWord :: Text -> [Text] -> Maybe [Text]+stripWord w = \case+    t : rest | T.toLower t == w -> Just rest+    _ -> Nothing+++-- | A dotted name's parts, split outside double quotes.+nameParts :: Text -> [Text]+nameParts = map T.pack . go [] False . T.unpack+  where+    go acc _ [] = [reverse acc]+    go acc inQuotes (c : rest)+        | c == '"' = go (c : acc) (not inQuotes) rest+        | c == '.' && not inQuotes = reverse acc : go [] False rest+        | otherwise = go (c : acc) inQuotes rest+++unquote :: Text -> Text+unquote p = case T.stripPrefix "\"" p >>= T.stripSuffix "\"" of+    Just q -> T.replace "\"\"" "\"" q+    Nothing -> T.toLower p+++-- | A comment statement with its text replaced, keeping how the file quotes it.+withLiteral :: Text -> Text -> Text+withLiteral new code = case [k | (k, "is") <- topWords code] of+    k : _ ->+        let (sep, old) = T.span isSpace (T.drop (k + 2) code)+            label = T.takeWhile (/= '$') (T.drop 1 old)+            tag = if "$" `T.isPrefixOf` old then Just [i|$#{label}$|] else Nothing+         in T.take (k + 2) code <> sep <> literal tag new+    [] -> code+++literal :: Maybe Text -> Text -> Text+literal tag t = case tag of+    Just q | fits q -> q <> t <> q+    _+        | "\n" `T.isInfixOf` t && fits "$comment$" -> [i|$comment$#{t}$comment$|]+        | otherwise -> Sql.literal t+  where+    fits q = not (q `T.isInfixOf` (t <> "$"))+++commentTarget :: ObjectId -> Maybe Text+commentTarget = \case+    Table t -> Just ("table " <> qualified t)+    Column t c -> Just [i|column #{qualified t}.#{quoted c}|]+    Index ix -> Just ("index " <> qualified ix)+    TableConstraint t n -> Just [i|constraint #{quoted n} on #{qualified t}|]+    _ -> Nothing+++commentCode :: Text -> ObjectId -> Text -> Text+commentCode indent addr t =+    let target = fromMaybe "" (commentTarget addr)+     in [i|comment on #{target} is\n#{indent}    #{literal Nothing t}|]+++indexCode :: Text -> Text -> Text+indexCode indent def =+    let tidied = tidyIndex def+        guarded = fromMaybe tidied (asum [(new <>) <$> T.stripPrefix old tidied | (old, new) <- [("create unique index ", "create unique index if not exists "), ("create index ", "create index if not exists ")]])+        (front, back) = T.breakOn " on " guarded+     in if T.null back then guarded else [i|#{front}\n#{indent}    #{T.drop 1 back}|]+++-- | A @create table@ statement's text up to its column list, the list's entries, and the+-- rest from the whitespace before the closing parenthesis.+data TableText = TableText+    { opening :: Text+    , elements :: [Element]+    , closing :: Text+    }+++-- | One entry of the column list: what precedes it on its own lines, its text, and a+-- comment after it on its last line.+data Element = Element+    { lead :: Text+    , body :: Text+    , trail :: Text+    }+++tableText :: Text -> Maybe TableText+tableText code = do+    let indexed = zip [0 :: Int ..] (regions code)+    open <- listToMaybe [n | (n, ('(', Code)) <- indexed]+    let step (depth, cs, close) (n, (c, r))+            | isJust close || r /= Code = (depth, cs, close)+            | c == '(' = (depth + 1, cs, close)+            | c == ')' = if depth == 1 then (depth, cs, Just n) else (depth - 1, cs, close)+            | c == ',' && depth == 1 = (depth, n : cs, close)+            | otherwise = (depth, cs, close)+        (_, commas, closeAt) = foldl' step (1 :: Int, [], Nothing) (drop (open + 1) indexed)+    close <- closeAt+    let cuts = open : reverse commas <> [close]+        raws = zipWith (\a b -> T.take (b - a - 1) (T.drop (a + 1) code)) cuts (drop 1 cuts)+        carried = map (fst . sameLineComment) (drop 1 raws) <> [""]+        rests = take 1 raws <> map (snd . sameLineComment) (drop 1 raws)+        parsed = map element rests+        closingSpace = maybe "" (\(_, _, _, ws) -> ws) (L.lastMaybe parsed)+    pure+        TableText+            { opening = T.take (open + 1) code+            , elements = [Element{lead, body, trail = own <> next} | ((lead, body, own, _), next) <- zip parsed carried]+            , closing = closingSpace <> T.drop close code+            }+  where+    sameLineComment r = case T.breakOn "\n" r of+        (line, rest) | "--" `T.isPrefixOf` T.stripStart line -> (line, rest)+        _ -> ("", r)+    element r =+        let (lead, rest) = splitLead r+            code' = T.stripEnd rest+            ws = T.drop (T.length code') rest+            (body, own) = endComment code'+         in (lead, body, own, ws)+    endComment t =+        let indexed = zip [0 :: Int ..] (regions t)+            lastLine = maybe (-1) fst (L.lastMaybe [x | x@(_, ('\n', _)) <- indexed])+         in case [n | (n, ('-', Remark)) <- indexed, n > lastLine] of+                n : _ -> let body = T.stripEnd (T.take n t) in (body, T.drop (T.length body) t)+                [] -> (t, "")+++renderTable :: TableText -> Text+renderTable tt = tt.opening <> T.concat (zipWith piece [1 :: Int ..] tt.elements) <> tt.closing+  where+    count = length tt.elements+    piece k e = e.lead <> e.body <> (if k == count then "" else ",") <> e.trail+++data ElementKind = ColumnElement Identifier [Identifier] | ConstraintElement (Maybe Identifier) | OtherElement+++elementKind :: QName -> Text -> ElementKind+elementKind table body = case ws of+    w : n : _ | T.toLower w == "constraint" -> ConstraintElement (Just (identifier (unquote n)))+    w : _ | T.toLower w == "primary" -> ConstraintElement (Just pkey)+    w : _ | T.toLower w == "unique" -> ConstraintElement (named "key" <$> columnList)+    w : _ | T.toLower w == "foreign" -> ConstraintElement (named "fkey" <$> columnList)+    w : _ | T.toLower w `elem` ["check", "exclude"] -> ConstraintElement Nothing+    w : _ | T.toLower w == "like" -> OtherElement+    w : rest ->+        let c = unquote w+            lower = map T.toLower rest+         in ColumnElement+                (identifier c)+                ( [identifier (unquote n) | (l, n) <- zip lower (drop 1 rest), l == "constraint"]+                    <> [pkey | "primary" `elem` lower]+                    <> [named "key" [c] | "unique" `elem` lower]+                    <> [named "fkey" [c] | "references" `elem` lower]+                    <> [named "check" [c] | "check" `elem` lower]+                )+    [] -> OtherElement+  where+    -- The names PostgreSQL gives constraints declared without one.+    pkey = identifier (T.intercalate "_" [nameText table.name, "pkey"])+    ws = codeWords "()," body+    columnList = case splitTopLevel ',' <$> parenthesised body of+        Nothing -> Nothing+        Just [""] -> Nothing+        Just cs -> Just (map unquote cs)+    named suffix cs = identifier (T.intercalate "_" (nameText table.name : cs <> [suffix]))+++-- | Applies the column and constraint differences to a @create table@ statement, with the+-- objects it placed; the column list keeps the file's order and gets new columns after it.+-- @options@ is a @with (...)@ clause to add.+editCreateTable :: QName -> [Identifier] -> [(Identifier, Change ColumnDef)] -> [(Identifier, Change Text)] -> Maybe Text -> Text -> Maybe (Text, Set ObjectId)+editCreateTable table order columns constraints options code = do+    tt <- tableText code+    let indent = maybe "        " (T.takeWhileEnd (== ' ') . (.lead)) (listToMaybe tt.elements)+        newLead = "\n" <> indent+        kinds = [(e, elementKind table e.body) | e <- tt.elements]+        constraintLead = case L.lastMaybe [e | (e, ConstraintElement _) <- kinds] of+            Just e | "\n\n" `T.isPrefixOf` e.lead -> "\n" <> newLead+            _ -> newLead+        (beforeParen, fromParen) = T.breakOn ")" tt.closing+        closing = case options of+            Just w | not (any ((== "with") . snd) (topWords (T.drop 1 fromParen))) -> Just [i|#{beforeParen}) #{w}#{T.drop 1 fromParen}|]+            _ -> Nothing+        inline = Set.fromList [n | (_, ColumnElement _ ns) <- kinds, n <- ns]+        edit (e, kind) = case kind of+            ColumnElement c _ -> case lookup c columns of+                Just (Changed _ def) -> (Just e{body = columnLine c def <> inlineSuffix e.body}, [Column table c])+                Just (Dropped _) -> (Nothing, [Column table c])+                _ -> (Just e, [])+            ConstraintElement (Just n) | n `Set.notMember` inline -> case lookup n constraints of+                Just (Changed _ def) -> (Just e{body = constraintLine indent n def}, [TableConstraint table n])+                Just (Dropped _) -> (Nothing, [TableConstraint table n])+                _ -> (Just e, [])+            _ -> (Just e, [])+        edited = map edit kinds+        kept = keep "" (zip edited kinds)+        keep pending = \case+            [] -> []+            ((Just e, _), (_, k)) : rest -> (e{lead = pending <> e.lead}, isColumn k) : keep "" rest+            ((Nothing, _), (e, _)) : rest -> keep (pending <> separateComments e.lead) rest+        separateComments l = case T.breakOnEnd "\n\n" l of+            (before, _) | "--" `T.isInfixOf` before -> T.dropEnd 1 before+            _ -> ""+        isColumn = \case ColumnElement _ _ -> True; _ -> False+        added = [(c, def) | c <- order, Just (Added def) <- [lookup c columns]]+        addedColumns = [Element newLead (columnLine c def) "" | (c, def) <- added]+        lastColumn = L.lastMaybe [n | (n, (_, True)) <- zip [0 :: Int ..] kept]+        withColumns = case lastColumn of+            Just n -> map fst (take (n + 1) kept) <> addedColumns <> map fst (drop (n + 1) kept)+            Nothing -> addedColumns <> map fst kept+        addedConstraints = [(n, def) | (n, Added def) <- constraints, n `Set.notMember` inline]+        elements = withColumns <> [Element constraintLead (constraintLine indent n def) "" | (n, def) <- addedConstraints]+        placed =+            Set.fromList (concatMap snd edited)+                <> Set.fromList [Column table c | (c, _) <- added]+                <> Set.fromList [TableConstraint table n | (n, _) <- addedConstraints]+                <> Set.fromList [Table table | isJust closing]+    pure (if Set.null placed then code else renderTable tt{elements, closing = fromMaybe tt.closing closing}, placed)+++-- | A column's line in @create table@, its type without the @public.@ the catalog prints.+columnLine :: Identifier -> ColumnDef -> Text+columnLine c def =+    let unqualified = typeName (fromMaybe (typeText def.colType) (T.stripPrefix "public." (typeText def.colType)))+        sql = columnSql def{colType = unqualified}+     in [i|#{quoted c} #{sql}|]+++-- | The inline constraints written after a column's type and options.+inlineSuffix :: Text -> Text+inlineSuffix body = case [k | (k, w) <- drop 1 (topWords body), w `elem` ["constraint", "primary", "unique", "check", "references"]] of+    k : _ -> " " <> T.strip (T.drop k body)+    [] -> ""+++constraintLine :: Text -> Identifier -> Text -> Text+constraintLine indent n def =+    let tidied = fromMaybe def (T.stripPrefix "add constraint " (tidyConstraint [i|add constraint #{quoted n} #{def}|]))+        keywords = ["foreign key", "references", "on delete", "on update"] :: [Text]+        broken = foldl' (\acc kw -> replaceInCode [i| #{kw} |] [i|\n#{indent}    #{kw} |] acc) tidied keywords+     in "constraint " <> if "foreign key" `T.isInfixOf` tidied then broken else tidied
+ src/Sqiff/Script.hs view
@@ -0,0 +1,171 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Splits a deploy script into statements, so it can run inside a transaction of ours.+module Sqiff.Script (splitStatements, withoutTransactionControl, withoutCommitsInDoBlock) where++import Data.Char (isAlphaNum, isAsciiUpper, isDigit, isSpace)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import RIO.List qualified as L+import Sqiff.Sql (Region (..), closed, codeOnly, regions, splitTopLevel, topWords)+++-- | Statements without their terminating semicolon, skipping psql meta-commands that only+-- affect psql's output and refusing the rest. Each statement is a slice of the script.+splitStatements :: Text -> Either Text [Text]+splitStatements script = do+    split <- firstStatement script+    more <- maybe (Right []) splitStatements split.after+    Right (maybeToList split.statement <> more)+++-- | A script's first statement and the script after it.+data FirstStatement = FirstStatement+    { statement :: Maybe Text+    -- ^ Nothing when there are only whitespace and comments before the split.+    , after :: Maybe Text+    -- ^ Nothing when the statement ends the script.+    }+++-- | What 'firstStatement' looks at in a script: its words, the semicolons and backslashes+-- in its code, and what lies between them.+data Token+    = -- | A word of code, lowercased.+      Word Text+    | Semicolon+    | Backslash+    | -- | Whitespace or a comment: the word before it stays the previous word.+      Blank+    | -- | Any other code, or a quoted character: it parts @BEGIN@ from @ATOMIC@.+      Mark+++-- | Each token of the script, with where it starts.+tokens :: Text -> [(Int, Token)]+tokens = go . zip [0 ..] . regions+  where+    go = \case+        [] -> []+        xs@((k, (c, Code)) : rest)+            | isWordChar c ->+                let (w, more) = span (\(_, (ch, r)) -> r == Code && (isWordChar ch || ch == '$')) xs+                 in (k, Word (T.toLower (T.pack (map (fst . snd) w)))) : go more+            | c == ';' -> (k, Semicolon) : go rest+            | c == '\\' -> (k, Backslash) : go rest+            | isSpace c -> (k, Blank) : go rest+            | otherwise -> (k, Mark) : go rest+        (k, (_, Remark)) : rest -> (k, Blank) : go rest+        (k, (_, Quoted)) : rest -> (k, Mark) : go rest+++-- | The script's first statement, unless it has only whitespace and comments, and the+-- script after it, unless it ends the script. A semicolon ends a statement in code, outside+-- any @BEGIN ATOMIC@ body; a backslash before any code starts a psql meta-command, which+-- runs to the end of its line.+--+-- 'splitStatements' lexes the script after a split afresh. That reads it as the lexer+-- would have read it in place: both splits are in code, after a character that is no+-- part of a word, which is where 'regions' starts.+firstStatement :: Text -> Either Text FirstStatement+firstStatement script = go (0 :: Int) Nothing False (tokens script)+  where+    -- How many @BEGIN ATOMIC@ bodies and @CASE@ blocks in them are open, the last word if+    -- only blanks came since, and whether the statement has code yet.+    go depth previous hasCode = \case+        []+            | not (closed script) -> Left "a quote, dollar quote or comment is not closed"+            | depth > 0 -> Left "a BEGIN ATOMIC body has no END"+            | otherwise -> Right (FirstStatement (statement hasCode script) Nothing)+        (k, Semicolon) : _ | depth == 0 -> Right (FirstStatement (statement hasCode (T.take k script)) (Just (T.drop (k + 1) script)))+        (k, Backslash) : _ | not hasCode -> FirstStatement Nothing . Just <$> skipPsqlCommand (T.drop (k + 1) script)+        (_, Word w) : rest -> go (atomicDepthAfter previous w depth) (Just w) True rest+        (_, Blank) : rest -> go depth previous hasCode rest+        _ : rest -> go depth Nothing True rest+    statement hasCode t = if hasCode then Just (T.strip t) else Nothing+++-- | The script after a psql meta-command's line, if the command only affects psql's+-- output; refuses the command otherwise.+skipPsqlCommand :: Text -> Either Text Text+skipPsqlCommand afterBackslash+    | command `elem` outputOnly || (command `elem` ["set", "unset"] && psqlVariable) = Right afterLine+    | otherwise = Left [i|psql's \\#{command} cannot run outside psql|]+  where+    (line, afterLine) = T.break (== '\n') afterBackslash+    command = T.takeWhile isWordChar line+    psqlVariable = case T.words (T.drop (T.length command) line) of+        name : _ -> T.all (\x -> isAsciiUpper x || isDigit x || x == '_') name+        [] -> True+    outputOnly = ["pset", "o", "out", "echo", "qecho", "timing", "x"]+++-- | The @BEGIN ATOMIC@ depth after a lowercased word, given the word before it.+atomicDepthAfter :: Maybe Text -> Text -> Int -> Int+atomicDepthAfter previous word depth+    | previous == Just "begin" && word == "atomic" && depth == 0 = 1+    | depth > 0 && word == "case" = depth + 1+    | depth > 0 && word == "end" = depth - 1+    | otherwise = depth+++isWordChar :: Char -> Bool+isWordChar c = isAlphaNum c || c == '_'+++-- | Drops @BEGIN@, @COMMIT@ and the like in all their forms, so the statements run in a+-- transaction of ours. Savepoints stay; two-phase commit commands are refused.+withoutTransactionControl :: [Text] -> Either Text [Text]+withoutTransactionControl = fmap catMaybes . traverse classify+  where+    classify s = case T.words (T.toLower (codeOnly s)) of+        "prepare" : "transaction" : _ -> Left "PREPARE TRANSACTION cannot run inside a transaction of ours"+        w : "prepared" : _ | w `elem` ["commit", "rollback"] -> Left (T.toUpper w <> " PREPARED cannot run inside a transaction of ours")+        -- ROLLBACK [WORK | TRANSACTION] TO [SAVEPOINT] name undoes to a savepoint and stays.+        "rollback" : rest | "to" : _ <- dropWhile (`elem` ["work", "transaction"]) rest -> Right (Just s)+        w : _ | w `elem` ["begin", "start", "commit", "end", "rollback", "abort"] -> Right Nothing+        _ -> Right (Just s)+++-- | A @do@ block with the @COMMIT@ and @ROLLBACK@ statements of its body left out, so it+-- runs inside a transaction of ours; any other statement unchanged. A batched backfill+-- commits between batches: against the comparison's scratch tables it has no rows to+-- batch, and without its commits it does the same work in one transaction. The body's+-- other statements keep their text, rejoined one per line. A commit nested in an @IF@ or a+-- @CASE@ is not its own statement at the top of the body, so it stays, and still fails.+withoutCommitsInDoBlock :: Text -> Text+withoutCommitsInDoBlock statement = case (topWords statement, dollarBody statement) of+    ((_, "do") : _, Just block) -> [i|#{block.leading}#{block.quote}#{withoutCommits block.body}#{block.quote}#{block.trailing}|]+    _ -> statement+  where+    withoutCommits = T.intercalate ";\n" . filter (not . transactionControl) . splitTopLevel ';'+    transactionControl s = case T.words (T.toLower (codeOnly s)) of+        w : _ -> w `elem` ["commit", "rollback"]+        [] -> False+++-- | A statement's first dollar-quoted body, and the text around it.+data DollarBody = DollarBody+    { leading :: Text+    , quote :: Text+    -- ^ The opening and closing quote, tag included: @$@ or @$tag$@.+    , body :: Text+    , trailing :: Text+    }+++dollarBody :: Text -> Maybe DollarBody+dollarBody statement = do+    start <- L.findIndex (\(c, r) -> c == '$' && r == Quoted) (regions statement)+    let (leading, rest) = T.splitAt start statement+        tag = T.takeWhile (\c -> isAlphaNum c || c == '_') (T.drop 1 rest)+        quote = [i|$#{tag}$|]+    opened <- T.stripPrefix quote rest+    let (body, closing) = T.breakOn quote opened+    trailing <- T.stripPrefix quote closing+    pure DollarBody{leading, quote, body, trailing}
+ src/Sqiff/Sqitch.hs view
@@ -0,0 +1,261 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Writes changes to a sqitch project with sqitch's own commands. Every write happens+-- inside 'withProject': sqitch runs with the project's resolved layout, the batch is+-- checked before the first write, and a failure puts the plan and the scripts back as+-- they were.+module Sqiff.Sqitch (+    PreviousFile (..),+    requireSqitch,+    Project,+    withProject,+    writeUnits,+    reworkEdited,+    moveToEnd,+    writeTracked,+) where++import Data.String.Interpolate qualified as S+import Data.Text qualified as T+import RIO+import RIO.Directory (doesDirectoryExist, doesFileExist, findExecutable, listDirectory, removeDirectory, removeFile)+import RIO.FilePath ((</>))+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Connection (UserError (..), failWith)+import Sqiff.Identifier+import Sqiff.Recipe+import Sqiff.Sqitch.Check (Tagging, batchProblems, chooseTag)+import Sqiff.Sqitch.Layout (Layout (..), Script (..), planPath, scriptDirs, scriptPath, sqitchConf)+import Sqiff.Sqitch.Plan (SqitchPlan (..), entryName, readPlan)+import Sqiff.Sqitch.Units+import Sqiff.Timing (timed)+import System.Environment (getEnvironment)+import System.Process.Typed (proc, runProcess, setEnv, setWorkingDir)+++-- | Whether the file a rework replaces can still run on the edited table, as its revert.+data PreviousFile = PreviousFileRuns | PreviousFileFails+    deriving stock (Eq, Show)+++requireSqitch :: IO ()+requireSqitch = do+    found <- findExecutable "sqitch"+    when (isNothing found) $ failWith "sqitch is not on PATH; load the nix environment (direnv) in this shell first"+++-- | A sqitch project being written, inside 'withProject'.+data Project = Project+    { layout :: Layout+    , conf :: FilePath+    -- ^ The configuration sqitch runs with, from 'sqitchConf'.+    , originals :: IORef (Map FilePath (Maybe Text))+    -- ^ What each file sqiff wrote held before, if it existed.+    }+++-- | Runs @action@ on the project. If it fails, the plan, the files sqiff wrote and the+-- scripts sqitch made are put back as they were, and the error says so.+withProject :: Layout -> (Project -> IO a) -> IO a+withProject layout action = withSystemTempDirectory "sqiff-sqitch" \tmp -> do+    let conf = tmp </> "sqitch.conf"+    writeFileUtf8 conf (sqitchConf layout)+    plan <- readFileUtf8 (planPath layout)+    before <- foldMap entriesUnder (scriptDirs layout)+    originals <- newIORef Map.empty+    let restore = do+            readIORef originals >>= traverse_ (uncurry putBack) . Map.toList+            -- The plan last: sqitch changed it, and sqiff may have rewritten it since.+            writeFileUtf8 (planPath layout) plan+            (files, dirs) <- foldMap entriesUnder (scriptDirs layout)+            traverse_ removeFile (Set.toList (files `Set.difference` fst before))+            -- Deepest first, so a new directory is empty when its turn comes.+            traverse_ removeDirectory (L.sortOn (Down . length) (Set.toList (dirs `Set.difference` snd before)))+        putBack path = maybe (removeFile path) (writeFileUtf8 path)+        rolledBack e = do+            restored <- tryAny restore+            case (restored, fromException e) of+                (Right (), Just (UserError message)) -> throwIO (UserError (message <> "; nothing was written, the project is as it was"))+                (Right (), Nothing) -> throwIO e+                (Left failure, _) -> throwIO (UserError [S.i|#{displayException e}; putting the project back failed too (#{displayException failure}), so check git status|])+    action Project{layout, conf, originals} `catchAny` rolledBack+++-- | The files and directories under @dir@, recursively.+entriesUnder :: FilePath -> IO (Set FilePath, Set FilePath)+entriesUnder dir =+    doesDirectoryExist dir >>= \case+        False -> pure mempty+        True -> do+            names <- listDirectory dir+            fold <$> for names \n -> do+                let path = dir </> n+                isDir <- doesDirectoryExist path+                if isDir+                    then (\(fs, ds) -> (fs, Set.insert path ds)) <$> entriesUnder path+                    else pure (Set.singleton path, Set.empty)+++-- | Writes a file, keeping what it held first so 'withProject' can put it back.+writeTracked :: Project -> FilePath -> Text -> IO ()+writeTracked project path text = do+    seen <- Map.member path <$> readIORef project.originals+    unless seen do+        exists <- doesFileExist path+        old <- if exists then Just <$> readFileUtf8 path else pure Nothing+        modifyIORef' project.originals (Map.insert path old)+    writeFileUtf8 path text+++-- | Runs sqitch in the project with its resolved layout.+runSqitch :: Project -> [Text] -> IO ()+runSqitch project args = do+    let command = T.unwords (take 1 args)+    inherited <- getEnvironment+    let env = ("SQITCH_CONFIG", project.conf) : filter ((/= "SQITCH_CONFIG") . fst) inherited+    code <- timed [S.i|sqitch #{command}|] $ runProcess (setEnv env (setWorkingDir project.layout.root (proc "sqitch" (map T.unpack args))))+    case code of+        ExitSuccess -> pure ()+        ExitFailure n -> failWith [S.i|sqitch #{T.unwords args} failed with exit code #{n}|]+++-- | Adds the tag a rework needs, unless @change@ already has one after it.+tagBefore :: Project -> SqitchPlan -> Tagging -> Text -> IO ()+tagBefore project plan tagging change =+    unless (change `Set.member` plan.tagged) do+        tag <- either failWith pure (chooseTag plan tagging)+        runSqitch project ["tag", tag, "-n", "sqiff: before the changes it writes"]+++-- | Writes each change with @sqitch add@ or @sqitch rework@, from create-migration's+-- templates in @templateDir@ when it is set, adding a tag first when a rework needs one.+-- Nothing is written when 'batchProblems' finds a problem.+writeUnits :: Project -> Maybe FilePath -> SqitchPlan -> Tagging -> [Unit] -> IO ()+writeUnits project templateDir' sqitchPlan tagging us = do+    requireSqitch+    case batchProblems sqitchPlan us of+        [] -> pure ()+        problems -> failWith (T.intercalate "; " problems)+    templateDir <- case (project.layout.root </>) <$> templateDir' of+        Just dir -> (\exists -> if exists then Just dir else Nothing) <$> doesDirectoryExist dir+        Nothing -> pure Nothing+    for_ (L.find (\u -> u.kind == ReworkChange && u.changeName `Set.notMember` sqitchPlan.tagged) us) \u ->+        tagBefore project sqitchPlan tagging u.changeName+    for_ us (writeUnit WriteContext{project, sqitchPlan, templateDir})+++-- | What each change of a batch is written with, in 'writeUnits'.+data WriteContext = WriteContext+    { project :: Project+    , sqitchPlan :: SqitchPlan+    , templateDir :: Maybe FilePath+    -- ^ create-migration's templates, when the project has the directory.+    }+++-- | Adds or reworks one change with sqitch, then writes its scripts over the ones sqitch made.+writeUnit :: WriteContext -> Unit -> IO ()+writeUnit ctx u = do+    let template = if isJust ctx.templateDir && u.kind == AddChange then templateOf u else Nothing+    case u.kind of+        AddChange -> runSqitch ctx.project (["add", u.changeName, "-n", u.note] <> foldMap (templateArgs ctx) template)+        ReworkChange -> runSqitch ctx.project ["rework", u.changeName, "-n", u.note]+    writeUnitScripts ctx template u+++-- | The arguments that make @sqitch add@ start from a create-migration template.+templateArgs :: WriteContext -> TemplateUse -> [Text]+templateArgs ctx template =+    ["--template", template.name]+        <> foldMap (\d -> ["--template-directory", T.pack d]) ctx.templateDir+        <> concat [["-s", [S.i|#{k}=#{v}|]] | (k, v) <- template.variables]+++-- | Writes a change's scripts once sqitch has made them. From a template, sqiff patches+-- what the template rendered or writes over it; without one, it writes the deploy, and+-- the revert and verify only for a new change, so a rework keeps the ones sqitch copied.+writeUnitScripts :: WriteContext -> Maybe TemplateUse -> Unit -> IO ()+writeUnitScripts ctx template u =+    case (template, shapeOf u) of+        (Just _, ValidateShape _ _) -> pure ()+        (Just _, AddColumnShape _ _ options) -> do+            rendered <- readFileUtf8 (path Deploy)+            let hazards = T.unlines [[S.i|-- #{hazardText h}|] | s <- u.deploy, h <- s.hazards]+            write (path Deploy)+                . T.replace "__your_type_here__ null" options+                . T.replace "\nalter table " [S.i|\n#{hazards}alter table |]+                $ rendered+        (Just use, AddIndexShape t index)+            | any (\s -> EveryPartition `elem` s.hazards) u.deploy -> do+                deploy >> revert+                write (path Verify) (verifyScript [S.i|-- Verify #{projectName}:#{name} on #{engine}|] u.deploy)+            | otherwise -> do+                deploy+                let ix = nameText index+                    templated = indexPrefix t <> fromMaybe ix (lookup "index_name" use.variables)+                for_ [Revert, Verify] \script' -> do+                    rendered <- readFileUtf8 (path script')+                    write (path script') (T.replace templated ix rendered)+        (Just _, OtherShape) -> deploy >> revert >> verify+        (Nothing, _) -> do+            deploy+            when (u.kind == AddChange) (revert >> verify)+  where+    layout = ctx.project.layout+    write = writeTracked ctx.project+    path script' = scriptPath layout script' u.changeName+    projectName = ctx.sqitchPlan.project+    engine = layout.engine+    name = u.changeName+    deploy = script Deploy [S.i|-- Deploy #{projectName}:#{name} to #{engine}|] u.deploy+    revert = script Revert [S.i|-- Revert #{projectName}:#{name} from #{engine}|] u.revert+    verify = write (path Verify) (verifyScript [S.i|-- Verify #{projectName}:#{name} on #{engine}|] u.deploy)+    script script' header steps+        | null steps = write (path script') [S.i|#{header}\n\n-- Nothing to revert.\n|]+        | otherwise = write (path script') (renderScript header u.placement steps)+++-- | Reworks a change whose deploy script was already edited in place, putting the edit+-- back whatever happens; with 'PreviousFileFails' its revert does nothing.+reworkEdited :: Project -> Tagging -> Text -> Text -> Text -> PreviousFile -> IO ()+reworkEdited project tagging changeName note original previousFile = do+    let layout = project.layout+        path = scriptPath layout Deploy changeName+        revertPath = scriptPath layout Revert changeName+        engine = layout.engine+    sqitchPlan <- readPlan (planPath layout)+    edited <- readFileUtf8 path+    ( do+            writeTracked project path original+            tagBefore project sqitchPlan tagging changeName+            runSqitch project ["rework", changeName, "-n", note]+        )+        `finally` writeTracked project path edited+    let projectName = sqitchPlan.project+    when (previousFile == PreviousFileFails)+        $ writeTracked+            project+            revertPath+            [S.i|-- Revert #{projectName}:#{changeName} from #{engine}++-- The migrations before this change revert the table; the previous file fails on the edited table.+|]+++-- | Moves the last plan entry for @name@, one the branch added, to the end of the plan.+moveToEnd :: Project -> Text -> IO ()+moveToEnd project name = do+    let path = planPath project.layout+    text <- readFileUtf8 path+    let ls = reverse (dropWhile (T.null . T.strip) (reverse (T.lines text)))+        isEntry l = entryName l == name+    case L.lastMaybe [k | (k, l) <- zip [0 :: Int ..] ls, isEntry l] of+        Just k | k < length ls - 1 -> writeTracked project path (T.unlines (take k ls <> drop (k + 1) ls <> take 1 (drop k ls)))+        _ -> pure ()
+ src/Sqiff/Sqitch/Check.hs view
@@ -0,0 +1,89 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | What sqiff checks before it writes anything to a sqitch project: every change name is+-- one sqitch accepts and stays inside the script directories, no two changes share a+-- name, and the tag a rework needs is free.+module Sqiff.Sqitch.Check (+    changeNameProblem,+    tagNameProblem,+    batchProblems,+    Tagging (..),+    chooseTag,+) where++import Data.Char (isPunctuation, isSpace, isSymbol)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import Data.Time (UTCTime, defaultTimeLocale, formatTime)+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Sqitch.Plan (SqitchPlan (..))+import Sqiff.Sqitch.Units (Unit (..), UnitKind (..))+++-- | Why sqitch, or the file system, would refuse this change name.+changeNameProblem :: Text -> Maybe Text+changeNameProblem name+    | T.null name = Just "a change name cannot be empty"+    | Just c <- T.find (\c -> isSpace c || c `elem` (":@#\\" :: String)) name = Just [i|#{shown} has #{describeChar c}, which sqitch does not allow in a change name|]+    | punct (T.head name) || punct (T.last name) = Just [i|#{shown} starts or ends with punctuation, which sqitch does not allow|]+    | endsInReference = Just [i|#{shown} ends in one of ~^/=% and digits, which sqitch reads as a reference|]+    | "/" `T.isPrefixOf` name = Just [i|#{shown} is an absolute path|]+    | any (`elem` ["", ".", ".."]) (T.splitOn "/" name) = Just [i|#{shown} has an empty, . or .. path segment, so its scripts would not stay in their directories|]+    | otherwise = Nothing+  where+    shown = tshow name+    punct c = c /= '_' && (isPunctuation c || isSymbol c)+    endsInReference =+        let digits = T.takeWhileEnd (`elem` ['0' .. '9']) name+            rest = T.dropWhileEnd (`elem` ['0' .. '9']) name+         in not (T.null digits) && maybe False (\(_, c) -> c `elem` ("~^/=%" :: String)) (T.unsnoc rest)+    describeChar c = if isSpace c then "a blank" else T.pack ['\'', c, '\'']+++-- | Why sqitch would refuse this tag name: the change name rules, and no @/@.+tagNameProblem :: Text -> Maybe Text+tagNameProblem name+    | "/" `T.isInfixOf` name = Just [i|tag #{tshow name} has '/', which sqitch does not allow in a tag|]+    | otherwise = (\p -> "tag: " <> p) <$> changeNameProblem name+++-- | Every reason the batch cannot be written to the plan as it is; none when it can.+batchProblems :: SqitchPlan -> [Unit] -> [Text]+batchProblems plan us =+    mapMaybe changeNameProblem (nubOrd names)+        <> [ [i|#{tshow n} would be written #{count} times in one run; write them as one change, or one at a time|]+           | (n, count) <- Map.toList (Map.fromListWith (+) [(n, 1 :: Int) | n <- names])+           , count > 1+           ]+        <> [[i|#{tshow n} is already in the plan, so it cannot be added again|] | u <- us, u.kind == AddChange, let n = u.changeName, n `Set.member` planned]+        <> [[i|#{tshow n} is not in the plan, so it cannot be reworked|] | u <- us, u.kind == ReworkChange, let n = u.changeName, n `Set.notMember` planned]+  where+    names = map (.changeName) us+    planned = Set.fromList plan.changes+++-- | The tag a rework needs: the one the command line names, or the day's with @_sqiff@.+data Tagging = Tagging+    { given :: Maybe Text+    , now :: UTCTime+    }+++-- | The tag to add to the plan: the given one, which must be new, or the first free one of+-- @<day>_sqiff@, @<day>_sqiff_2@, …+chooseTag :: SqitchPlan -> Tagging -> Either Text Text+chooseTag plan tagging = case tagging.given of+    Just t+        | Just problem <- tagNameProblem t -> Left problem+        | t `Set.member` plan.tags -> Left [i|the plan already has the tag @#{t}; pass a new one with --tag|]+        | otherwise -> Right t+    Nothing ->+        let day = T.pack (formatTime defaultTimeLocale "%Y-%m-%d" tagging.now)+            candidates = [day <> "_sqiff"] <> [[i|#{day}_sqiff_#{n}|] | n <- [2 :: Int ..]]+         in maybe (Left "no free tag") Right (L.find (`Set.notMember` plan.tags) candidates)
+ src/Sqiff/Sqitch/Layout.hs view
@@ -0,0 +1,174 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Where a sqitch project keeps its plan and scripts, resolved once from sqitch's+-- configuration and the command line, and the configuration file that makes every sqitch+-- command sqiff runs use exactly that layout.+module Sqiff.Sqitch.Layout (+    Layout (..),+    Script (..),+    findLayout,+    resolveLayout,+    planPath,+    scriptPath,+    scriptDirs,+    sqitchConf,+) where++import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO hiding (local)+import RIO.FilePath (normalise, (<.>), (</>))+import RIO.List qualified as L+import RIO.Map qualified as Map+import Sqiff.Connection (failWith)+import System.Process.Typed (nullStream, proc, readProcess, setStdin, setWorkingDir)+++-- | The project's layout. The directories and the plan file are relative to @root@, as+-- sqitch's configuration writes them.+data Layout = Layout+    { root :: FilePath+    , topDir :: FilePath+    , planFile :: FilePath+    , deployDir :: FilePath+    , revertDir :: FilePath+    , verifyDir :: FilePath+    , reworkedDeployDir :: FilePath+    , reworkedRevertDir :: FilePath+    , reworkedVerifyDir :: FilePath+    -- ^ Where @sqitch rework@ copies the previous scripts.+    , extension :: String+    , local :: [(Text, Text)]+    -- ^ The project's own settings, as @sqitch config --local --list@ prints them.+    , engine :: Text+    , target :: Maybe Text+    }+++data Script = Deploy | Revert | Verify+    deriving stock (Eq, Show, Enum, Bounded)+++planPath :: Layout -> FilePath+planPath l = l.root </> l.planFile+++-- | Where a change's script is.+scriptPath :: Layout -> Script -> Text -> FilePath+scriptPath l script change = l.root </> dir </> T.unpack change <.> l.extension+  where+    dir = case script of+        Deploy -> l.deployDir+        Revert -> l.revertDir+        Verify -> l.verifyDir+++-- | Every directory sqitch writes scripts to, absolute.+scriptDirs :: Layout -> [FilePath]+scriptDirs l = nubOrd (map (normalise . (l.root </>)) [l.deployDir, l.revertDir, l.verifyDir, l.reworkedDeployDir, l.reworkedRevertDir, l.reworkedVerifyDir])+++-- | The layout of the project in @root@, with @--top-dir@ and @--plan-file@ when they+-- are given, from @sqitch config@.+findLayout :: FilePath -> Maybe FilePath -> Maybe FilePath -> IO Layout+findLayout root top planFile = do+    merged <- configList ["--list"]+    local <- configList ["--local", "--list"]+    either failWith pure (resolveLayout root top planFile merged local)+  where+    configList args = do+        (code, out, err) <- readProcess (setStdin nullStream (setWorkingDir root (proc "sqitch" ("config" : args))))+        case code of+            ExitSuccess -> pure [(T.toLower k, T.drop 1 v) | l <- T.lines (decode out), let (k, v) = T.breakOn "=" l, not (T.null v)]+            -- An empty file or none: sqitch config exits 1 with nothing to list.+            ExitFailure 1 | T.null (decode err) -> pure []+            ExitFailure _ -> failWith [i|sqitch config #{T.unwords (map T.pack args)} in #{root} failed: #{decode err}|]+    decode = T.strip . decodeUtf8Lenient . toStrictBytes+++-- | The layout from sqitch's settings, all of them (@merged@) and the project's own+-- (@local@). A setting for the target wins over one for the engine, which wins over the+-- core one, as in sqitch.+resolveLayout :: FilePath -> Maybe FilePath -> Maybe FilePath -> [(Text, Text)] -> [(Text, Text)] -> Either Text Layout+resolveLayout root top planGiven merged local = do+    let settings = Map.fromList merged+        engine = fromMaybe "pg" (Map.lookup "core.engine" settings)+        target = Map.lookup [i|engine.#{engine}.target|] settings <|> Map.lookup "core.target" settings+        named :: Text -> Maybe Text+        named key =+            listToMaybe+                ( catMaybes+                    [ target >>= \t -> Map.lookup [i|target.#{t}.#{key}|] settings+                    , Map.lookup [i|engine.#{engine}.#{key}|] settings+                    , Map.lookup [i|core.#{key}|] settings+                    ]+                )+        path :: Text -> Maybe FilePath+        path = fmap T.unpack . named+        topDir = fromMaybe (fromMaybe "." (path "top_dir")) top+        dirFor key name = fromMaybe (topDir </> name) (guard (isNothing top) *> path key)+        reworked = fromMaybe topDir (path "reworked_dir")+        reworkedDirFor key name = fromMaybe (reworked </> name) (path key)+        deployDir = dirFor "deploy_dir" "deploy"+        revertDir = dirFor "revert_dir" "revert"+        verifyDir = dirFor "verify_dir" "verify"+    when (any (T.any (== '\n') . snd) local) $ Left "sqitch.conf has a multi-line value, which sqiff cannot pass on to sqitch"+    pure+        Layout+            { root+            , topDir+            , planFile = fromMaybe (fromMaybe (topDir </> "sqitch.plan") (guard (isNothing top) *> path "plan_file")) planGiven+            , deployDir+            , revertDir+            , verifyDir+            , reworkedDeployDir = reworkedDirFor "reworked_deploy_dir" "deploy"+            , reworkedRevertDir = reworkedDirFor "reworked_revert_dir" "revert"+            , reworkedVerifyDir = reworkedDirFor "reworked_verify_dir" "verify"+            , extension = maybe "sql" T.unpack (named "extension")+            , local+            , engine+            , target+            }+++-- | The project configuration sqiff gives sqitch, as @SQITCH_CONFIG@: the project's own+-- settings, with the layout set for the core, the engine and the target, so no other+-- setting can move a script or the plan.+sqitchConf :: Layout -> Text+sqitchConf l = T.unlines (concatMap section (Map.toList sections))+  where+    layoutKeys = ["top_dir", "plan_file", "deploy_dir", "revert_dir", "verify_dir", "reworked_dir", "reworked_deploy_dir", "reworked_revert_dir", "reworked_verify_dir", "extension"]+    -- sqitch puts a reworked directory left unset under top_dir, so a pinned relative+    -- deploy_dir would land in top_dir twice.+    pinned =+        [ ("top_dir", T.pack l.topDir)+        , ("plan_file", T.pack l.planFile)+        , ("deploy_dir", T.pack l.deployDir)+        , ("revert_dir", T.pack l.revertDir)+        , ("verify_dir", T.pack l.verifyDir)+        , ("reworked_deploy_dir", T.pack l.reworkedDeployDir)+        , ("reworked_revert_dir", T.pack l.reworkedRevertDir)+        , ("reworked_verify_dir", T.pack l.reworkedVerifyDir)+        , ("extension", T.pack l.extension)+        ]+    levels = [("core", Nothing), ("engine", Just l.engine)] <> [("target", Just t) | Just t <- [l.target]]+    own = [(splitKey k, v) | (k, v) <- l.local, let (_, _, name) = splitKey k, name `notElem` layoutKeys]+    sections =+        Map.fromListWith+            (flip (<>))+            ( [((s, sub), [(name, v)]) | ((s, sub, name), v) <- own]+                <> [(level, pinned) | level <- levels]+            )+    -- section.name, or section.subsection.name where the subsection may hold dots.+    splitKey k = case T.splitOn "." k of+        [s, name] -> (s, Nothing, name)+        s : rest@(_ : _ : _) -> (s, Just (T.intercalate "." (take (length rest - 1) rest)), fromMaybe "" (L.lastMaybe rest))+        _ -> (k, Nothing, "")+    section ((s, sub), entries) =+        maybe [i|[#{s}]|] (\n -> [i|[#{s} "#{escape n}"]|]) sub+            : [[i|\t#{name} = "#{escape v}"|] | (name, v) <- entries]+    escape = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"
+ src/Sqiff/Sqitch/Plan.hs view
@@ -0,0 +1,92 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | sqitch's plan file, and the changes a database's sqitch registry has deployed.+module Sqiff.Sqitch.Plan (+    SqitchPlan (..),+    readPlan,+    parsePlan,+    plannedChanges,+    deployedChanges,+    entryName,+) where++import Data.String.Interpolate qualified as S+import Data.Text qualified as T+import Hasql.Connection qualified as Connection+import Hasql.Session qualified as Session+import Hasql.TH (vectorStatement)+import RIO+import RIO.Directory (doesFileExist)+import RIO.List qualified as L+import RIO.Set qualified as Set+import Sqiff.Connection (errorText, failWith)+++data SqitchPlan = SqitchPlan+    { project :: Text+    , changes :: [Text]+    , tagged :: Set Text+    -- ^ Changes with a tag somewhere after their last entry.+    , tags :: Set Text+    -- ^ The plan's tags, without the @\@@.+    }+++readPlan :: FilePath -> IO SqitchPlan+readPlan path = do+    exists <- doesFileExist path+    unless exists $ failWith [S.i|#{path} does not exist; run from the project root or pass --project and --plan-file|]+    parsePlan <$> readFileUtf8 path+++parsePlan :: Text -> SqitchPlan+parsePlan text =+    let lines' = T.lines text+        entries = [l | l <- lines', Just (c, _) <- [T.uncons l], c `notElem` ("%#" :: String)]+        isTag = ("@" `T.isPrefixOf`)+        fromEnd _ _ [] = []+        fromEnd seenTag visited (l : ls)+            | isTag l = fromEnd True visited ls+            | entryName l `Set.member` visited = fromEnd seenTag visited ls+            | otherwise = (entryName l, seenTag) : fromEnd seenTag (Set.insert (entryName l) visited) ls+     in SqitchPlan+            { project = fromMaybe "" (listToMaybe (mapMaybe (T.stripPrefix "%project=") lines'))+            , changes = [entryName l | l <- entries, not (isTag l)]+            , tagged = Set.fromList [n | (n, True) <- fromEnd False Set.empty (reverse entries)]+            , tags = Set.fromList [entryName t | l <- entries, Just t <- [T.stripPrefix "@" l]]+            }+++-- | The plan's changes in order, each with its planned time as the plan writes it.+plannedChanges :: Text -> [(Text, Text)]+plannedChanges text =+    [ (T.takeWhile (\ch -> ch /= ' ' && ch /= '[') l, planned)+    | l <- T.lines text+    , Just (c, _) <- [T.uncons l]+    , c `notElem` ("%#@" :: String)+    , Just planned <- [L.find timestamp (T.words l)]+    ]+  where+    timestamp w = T.length w == 20 && "Z" `T.isSuffixOf` w && T.take 1 (T.drop 10 w) == "T"+++-- | The changes a database's sqitch registry has deployed for @project@, as 'plannedChanges' names them.+deployedChanges :: Connection.Connection -> Text -> IO (Set (Text, Text))+deployedChanges conn project =+    Connection.use conn (Session.statement project query)+        >>= either (\e -> failWith [S.i|could not read the sqitch registry: #{errorText e}|]) (pure . Set.fromList . toList)+  where+    query =+        [vectorStatement|+            select change::text, to_char(planned_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')::text+            from sqitch.changes+            where project = $1::text+        |]+++-- | The name a plan line starts with, a change's or a tag's.+entryName :: Text -> Text+entryName = T.takeWhile (\c -> c /= ' ' && c /= '[')
+ src/Sqiff/Sqitch/Units.hs view
@@ -0,0 +1,602 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Splits a plan into sqitch changes, and renders their deploy, revert and verify scripts.+module Sqiff.Sqitch.Units (+    UnitKind (..),+    Placement (..),+    Unit (..),+    units,+    slug,+    Shape (..),+    shapeOf,+    TemplateUse (..),+    templateOf,+    indexPrefix,+    renderScript,+    verifyScript,+    tidyConstraint,+    tidyIndex,+) where++import Data.Char (isAsciiLower, isDigit)+import Data.String.Interpolate qualified as S+import Data.Text qualified as T+import Data.Time (UTCTime, addUTCTime, defaultTimeLocale, formatTime)+import RIO+import RIO.List qualified as L+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import Sqiff.Config (Names (..), fill)+import Sqiff.Definition+import Sqiff.Diff (Change (..), Changes, after, before)+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Plan (invert)+import Sqiff.Recipe+import Sqiff.Sqitch.Plan (SqitchPlan (..))+import Sqiff.Sql (doBlock, literal, replaceAllInCode, terminator)+++data UnitKind = AddChange | ReworkChange+    deriving stock (Eq, Show)+++-- | Where a change lives: a time-stamped migration, or kronor's path for its object.+data Placement = Migration | Conventional+    deriving stock (Eq, Show)+++-- | One sqitch change. A rework keeps the revert sqitch gives it: the previous version.+data Unit = Unit+    { kind :: UnitKind+    , changeName :: Text+    , note :: Text+    , placement :: Placement+    , deploy :: [Step]+    , revert :: [Step]+    }+++-- | Groups ordered steps into changes: conventional paths for steps that pass+-- @conventional@, reworks of changes the plan has, and migrations for the rest. Each+-- gets its revert, and each migration its time-stamped name.+units :: Names -> (Step -> Bool) -> Context -> Changes -> SqitchPlan -> UTCTime -> [Step] -> [Unit]+units names conventional inverseCtx forward sqitchPlan now =+    nameMigrations names now+        . claimReverts inverseCtx forward+        . groupSteps names conventional sqitchPlan+++-- | One change per step, merged with the next where they can share one: migration+-- steps of the same table, phase and transaction, and overloads of a routine.+groupSteps :: Names -> (Step -> Bool) -> SqitchPlan -> [Step] -> [Unit]+groupSteps names conventional sqitchPlan = foldr (merge . single) []+  where+    existing = Set.fromList sqitchPlan.changes+    single s = case if conventional s then conventionalName names s else Nothing of+        Just n+            | n `Set.member` existing -> unitOf ReworkChange n (stepNote "update" s) Conventional s+            | isAdded s.change -> unitOf AddChange n (createNote s) Conventional s+        _ -> unitOf AddChange (groupKey s) (stepNote (verb s) s) Migration s+    unitOf kind changeName note placement s = Unit{kind, changeName, note, placement, deploy = [s], revert = []}+    merge u (next : rest)+        | u.placement == Migration && next.placement == Migration && u.changeName == next.changeName && all sharable both && samePhase both =+            u{deploy = both} : rest+        -- Overloads of a routine share their conventional change.+        | u.placement == Conventional && next.placement == Conventional && u.changeName == next.changeName && u.kind == next.kind =+            u{deploy = both} : rest+      where+        both = u.deploy <> next.deploy+    merge u rest = u : rest+    sharable s = s.txn == Shared+    samePhase ss = length (nubOrd (map (.phase) ss)) <= 1+++createNote :: Step -> Text+createNote s = case (s.object, s.change) of+    (Index ix, Added (IndexDefinition def))+        | Just t <- plainTable def ->+            let table = dotted (QName ix.schema t)+                name = nameText ix.name+             in [S.i|add_index: add index #{table}.#{name}|]+    _ -> stepNote "create" s+++stepNote :: Text -> Step -> Text+stepNote v s = let what = render s.object in [S.i|sqiff: #{v} #{what}|]+++-- | The migration a step goes in: its table's, or its own.+groupKey :: Step -> Text+groupKey s = case owningTable s.object of+    Just t -> dotted t+    Nothing -> T.intercalate "." (toAddress s.object).objectNames+++verb :: Step -> Text+verb s+    | s.key.aspect == Privileges = "grant"+    | s.key.aspect == Comment = "comment"+    | s.role == RenamesColumn = "rename"+    | s.phase == DropPhase = "drop"+    | isAdded s.change = "add"+    | otherwise = "alter"+++isAdded :: Change a -> Bool+isAdded = \case+    Added _ -> True+    _ -> False+++-- | Where the steps of each object change sit among the migrations, numbered in order,+-- for deciding which migration reverts which part of it.+data RevertIndex = RevertIndex+    { withSteps :: Set ObjectKey+    -- ^ The object changes that have steps of their own.+    , objectUnits :: Map ObjectKey (Set Int)+    -- ^ The migrations holding steps of each object change that its inverse undoes.+    , mainUnits :: Map ObjectKey Int+    -- ^ The first migration with a step that creates, replaces or drops the object itself.+    , dropThenCreate :: Map ObjectKey Bool+    -- ^ Whether an object's change drops the old object in the drop phase and creates+    -- the new one in the create phase, so each part has its own inverse.+    }+++revertIndex :: [Unit] -> RevertIndex+revertIndex us =+    RevertIndex+        { withSteps = Set.fromList [s.key | (_, s) <- numbered]+        , objectUnits = Map.fromListWith (<>) [(s.key, Set.singleton n) | (n, s) <- undoneByObject]+        , mainUnits = Map.fromListWith min [(s.key, n) | (n, s) <- undoneByObject, defines s]+        , dropThenCreate = Map.map (== Set.fromList [DropPhase, CreatePhase]) $ Map.fromListWith (<>) [(s.key, Set.singleton s.phase) | (_, s) <- undoneByObject]+        }+  where+    numbered = [(n, s) | (n, u) <- zip [0 :: Int ..] us, s <- u.deploy]+    undoneByObject = [(n, s) | (n, s) <- numbered, s.undo == UndoObject]+++-- | Each migration reverts its own steps, so reverting it returns to the state after+-- the one before. A rework keeps the revert sqitch gives it: the previous version.+claimReverts :: Context -> Changes -> [Unit] -> [Unit]+claimReverts inverseCtx forward us =+    [ u{revert = if u.kind == ReworkChange then [] else map refill (revertOf index ctx n u <> withTables index ctx forward u)}+    | (n, u) <- zip [0 :: Int ..] us+    , let ctx = unitContext inverseCtx u+    ]+  where+    index = revertIndex us+++-- | A migration's revert creates or drops only its own tables; another migration's+-- revert sees to the rest.+unitContext :: Context -> Unit -> Context+unitContext inverseCtx u =+    inverseCtx{droppedTables = Set.intersection inverseCtx.droppedTables own, newTables = Set.intersection inverseCtx.newTables own}+  where+    own = Set.fromList [t | s <- u.deploy, s.key.aspect == Definition, Table t <- [s.object]]+++-- | What went with a table the migration drops, which has no steps of its own: its+-- constraints, indexes, triggers, policies, comments and grants.+withTables :: RevertIndex -> Context -> Changes -> Unit -> [Step]+withTables index ctx forward u =+    L.sortOn (.rank)+        $ concat+            [ recipe ctx k (Added d)+            | not (Set.null dropped)+            , (k, Dropped d) <- Map.toList forward+            , k `Set.notMember` index.withSteps+            , belongs k d+            ]+  where+    dropped = Set.fromList [t | s <- u.deploy, s.key.aspect == Definition, Table t <- [s.object], Dropped _ <- [s.change]]+    belongs k d = case k.object of+        Table t -> k.aspect /= Definition && t `Set.member` dropped+        Index _ | Just ix <- asIndex d -> ix.table `Set.member` dropped+        o -> maybe False (`Set.member` dropped) (owningTable o) && not (isColumn o)+    isColumn = \case+        Column{} -> True+        _ -> False+++-- | The revert of migration @n@'s own steps, object change by object change, last first.+revertOf :: RevertIndex -> Context -> Int -> Unit -> [Step]+revertOf index ctx n u =+    concat [undoKey k (filter ((== k) . (.key)) u.deploy) | k <- reverse (nubOrd (map (.key) u.deploy))]+  where+    -- The key's steps here, undone last to first; a run of steps the object's inverse+    -- undoes gets it once.+    undoKey k here = go False (reverse here)+      where+        go _ [] = []+        go done (s : rest) = case s.undo of+            UndoBy undoing -> undoing <> go done rest+            UndoObject+                | done -> go done rest+                | otherwise -> objectPart index ctx n k s.change [x | x <- here, x.undo == UndoObject] <> go True rest+++-- | The part of an object change's inverse that migration @n@ reverts, given its own+-- steps of it (@mine@).+objectPart :: RevertIndex -> Context -> Int -> ObjectKey -> Change Definition -> [Step] -> [Step]+objectPart index ctx n k change mine+    | Map.lookup k index.objectUnits == Just (Set.singleton n) = recipe ctx k (invert change)+    -- The migration with the object's own drop, or create, reverts it; one that only sets+    -- its grants, indexes or comments can be deployed again as it is.+    | dropsThenCreates+    , Changed old _ <- change+    , all ((== DropPhase) . (.phase)) mine =+        if any defines mine then recipe ctx k (Added old) else []+    | dropsThenCreates+    , Changed _ new <- change+    , all ((== CreatePhase) . (.phase)) mine =+        if any defines mine then recipe ctx k (Dropped new) else []+    -- Otherwise the migration with its main step reverts it all, or the last with a part+    -- of it when none has one.+    | Just n == (Map.lookup k index.mainUnits <|> (Map.lookup k index.objectUnits >>= Set.lookupMax)) = recipe ctx k (invert change)+    | otherwise = []+  where+    dropsThenCreates = Map.findWithDefault False k index.dropThenCreate+++-- | A column that fails on a table with rows comes back nullable: its values were+-- dropped with it.+refill :: Step -> Step+refill s+    | Column t c <- s.object+    , Added (ColumnDefinition p) <- s.change+    , failsOnRows p =+        let table = qualified t+            column = quoted c+            definition = columnSql p{nullability = Nullable}+         in s+                { sql = [S.i|alter table #{table} add column #{column} #{definition}|]+                , hazards = [MayFail "the column comes back nullable and empty, since its values were dropped"]+                }+    | otherwise = s+++-- | Names each migration by its stamp, one second apart from the one before, and its+-- description.+nameMigrations :: Names -> UTCTime -> [Unit] -> [Unit]+nameMigrations names now = go 0+  where+    go :: Int -> [Unit] -> [Unit]+    go _ [] = []+    go i (u : rest)+        | u.placement == Migration =+            let stamp = T.pack (formatTime defaultTimeLocale (T.unpack names.migrationStamp) (addUTCTime (fromIntegral i) now))+                description = describe u+                template = maybe "migration" (.name) (templateOf u)+             in u{changeName = fill names.migration [("stamp", stamp), ("slug", slug description)], note = [S.i|#{template}: #{description}|]} : go (i + 1) rest+        | otherwise = u : go i rest+++describe :: Unit -> Text+describe u = case shapeOf u of+    AddColumnShape t c _ -> let table = dotted t; column = nameText c in [S.i|add column #{table}.#{column}|]+    ValidateShape t c -> let table = dotted t; constraint = nameText c in [S.i|validate constraint #{table}.#{constraint}|]+    _ ->+        let objects = nubOrd [fromMaybe (render s.object) (L.lastMaybe (toAddress s.object).objectNames) | s <- u.deploy]+            joined = T.intercalate "-" objects+            suffix = if objects == maybeToList (L.lastMaybe (T.split (== '.') u.changeName)) then "" else [S.i|.#{joined}|] :: Text+            v = maybe "alter" verb (listToMaybe u.deploy)+            name = u.changeName+         in [S.i|#{v} #{name}#{suffix}|] :: Text+++-- | Where the project keeps a new object of this kind, for the steps that create or replace one.+conventionalName :: Names -> Step -> Maybe Text+conventionalName names s+    | s.key.aspect /= Definition = Nothing+    | otherwise = case (s.object, s.change) of+        (Table t, Added _) | s.role == Creates -> Just (path names.table t)+        (Routine Aggregate _ _, _) -> Nothing+        (Routine _ q _, Added _) -> Just (path names.function q)+        (Routine _ q _, Changed _ _) -> Just (path names.function q)+        (View v, Added _) -> Just (path names.view v)+        (View v, Changed _ _) -> Just (path names.view v)+        (MaterializedView v, Added _) | s.phase == CreatePhase -> Just (path names.view v)+        (Trigger t n, Added _) -> Just (triggerPath t n)+        (Trigger t n, Changed _ _) | s.role == Replaces -> Just (triggerPath t n)+        (Index ix, Added (IndexDefinition def)) | Just t <- plainTable def -> Just (fill names.index [("schema", nameText ix.schema), ("table", nameText t), ("name", nameText ix.name)])+        (Type t, Added _) | [schema, name] <- T.splitOn "." (typeText t) -> Just (fill names.type_ [("schema", schema), ("name", name)])+        _ -> Nothing+  where+    path pattern q = fill pattern [("schema", nameText q.schema), ("name", nameText q.name)]+    triggerPath t n = fill names.trigger [("schema", nameText t.schema), ("table", nameText t.name), ("name", nameText n)]+++-- | The name of the table an index is on, when SQL writes it without quotes.+plainTable :: IndexDef -> Maybe Identifier+plainTable def = do+    let t = def.table.name+    guard (quoted t == nameText t)+    pure t+++-- | The changes create-migration's templates cover.+data Shape+    = -- | The table, the column, and the column's type and options.+      AddColumnShape QName Identifier Text+    | ValidateShape QName Identifier+    | AddIndexShape QName Identifier+    | OtherShape+++shapeOf :: Unit -> Shape+shapeOf u = case u.deploy of+    [s]+        | u.placement == Conventional+        , Index ix <- s.object+        , Added (IndexDefinition def) <- s.change+        , Just t <- plainTable def ->+            AddIndexShape (QName ix.schema t) ix.name+        | u.placement == Migration+        , Column t c <- s.object+        , Added _ <- s.change+        , plain t+        , quoted c == nameText c+        , -- [allow:SqiffStepRole] reads a template variable back out of the SQL; steps do not carry it yet+          Just options <- T.stripPrefix [S.i|alter table #{qualified t} add column #{quoted c} |] s.sql+        , not (any (`elem` [MayRewriteTable, RewritesTable, LongLock]) s.hazards) ->+            AddColumnShape t c options+        | u.placement == Migration+        , Just t <- owningTable s.object+        , plain t+        , -- [allow:SqiffStepRole] reads a template variable back out of the SQL; steps do not carry it yet+          Just c <- T.stripPrefix [S.i|alter table #{qualified t} validate constraint |] s.sql+        , quoteIdent c == c ->+            ValidateShape t (identifier c)+    _ -> OtherShape+  where+    plain t = qualified t == dotted t+++-- | The add_index template names an index idx_<table>_<index_name>.+indexPrefix :: QName -> Text+indexPrefix t = let name = nameText t.name in [S.i|idx_#{name}_|]+++-- | A create-migration template and the variables it is filled with.+data TemplateUse = TemplateUse+    { name :: Text+    , variables :: [(Text, Text)]+    }+++-- | The template and its variables, as create-migration would pass them.+templateOf :: Unit -> Maybe TemplateUse+templateOf u = case shapeOf u of+    AddColumnShape t c _ -> Just (TemplateUse "add_column" [("schema", nameText t.schema), ("table_name", nameText t.name), ("column_name", nameText c)])+    ValidateShape t c -> Just (TemplateUse "validate_constraint" [("schema", nameText t.schema), ("table_name", nameText t.name), ("constraint_name", nameText c)])+    AddIndexShape t ix -> Just (TemplateUse "add_index" [("schema", nameText t.schema), ("table_name", nameText t.name), ("index_name", fromMaybe (nameText ix) (T.stripPrefix (indexPrefix t) (nameText ix)))])+    OtherShape | u.placement == Migration -> Just (TemplateUse "migration" [])+    OtherShape -> Nothing+++slug :: Text -> Text+slug = T.take 80 . T.intercalate "-" . filter (not . T.null) . T.split (not . allowed) . T.toLower+  where+    allowed c = isAsciiLower c || isDigit c || c == '_' || c == '.'+++-- | A script: shared steps in one transaction, others in their own or none.+renderScript :: Text -> Placement -> [Step] -> Text+renderScript header placement steps =+    T.intercalate "\n\n" (header : ["set lock_timeout to '50ms';" | placement == Conventional] <> map block (L.groupBy together steps)) <> "\n"+  where+    together a b = a.txn == Shared && b.txn == Shared+    block group' = case group' of+        [s] | s.txn == None -> statement (idempotent s.sql) s+        _ ->+            T.intercalate "\n\n"+                $ ["BEGIN;"]+                <> ["  -- Do not remove this line\n  select set_config('lock_timeout', '50ms', false);" | placement == Migration]+                <> map (\s -> if safeToIndent s.sql then indent (statement s.sql s) else statement s.sql s) group'+                <> ["COMMIT;"]+    statement sql s =+        T.intercalate "\n" (map ("-- " <>) (hazardNotes s) <> [tidy s sql <> terminator sql] <> stopUntilWritten s)+    -- A step sqiff cannot write stops the deploy until someone writes it, rather than+    -- deploying as a change that does nothing.+    stopUntilWritten s =+        [ doBlock [S.i| begin raise exception using message = #{literal message}; end |] <> ";"+        | placeholder s+        , why <- take 1 [w | Manual w <- s.hazards]+        , let what = render s.object+              message = [S.i|sqiff could not write this step for #{what}: #{why}; write it here and remove this block|] :: Text+        ]+    -- A step left to a person: its SQL is a "--" note saying what to write.+    -- [allow:SqiffStepRole] such a step has no role of its own yet+    placeholder s = "--" `T.isPrefixOf` s.sql+    indent = T.intercalate "\n" . map (\l -> if T.null l then l else "  " <> l) . T.lines+    safeToIndent sql = not ("$" `T.isInfixOf` sql) && all (even . T.count "'") (T.lines sql)+    tidy s sql = case T.lines sql of+        [l]+            | Just rest <- T.stripPrefix "alter table " l+            , (name, more) <- T.breakOn " " rest+            , not ("\"" `T.isInfixOf` name)+            , not (T.null more) ->+                let clause = tidyConstraint (T.stripStart more) in [S.i|alter table #{name}\n    #{clause}|]+        ls+            | indexLike s.object -> T.intercalate "\n" (map tidyIndex ls)+            | otherwise -> sql+    indexLike = \case Index _ -> True; TableConstraint _ _ -> True; _ -> False+    idempotent sql =+        replaceAllInCode+            [ ("drop index concurrently if exists ", "drop index concurrently ")+            , ("drop index concurrently ", "drop index concurrently if exists ")+            , ("create unique index concurrently ", "create unique index concurrently if not exists ")+            , ("CREATE INDEX CONCURRENTLY ", "CREATE INDEX CONCURRENTLY IF NOT EXISTS ")+            , ("CREATE UNIQUE INDEX CONCURRENTLY ", "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ")+            ]+            sql+    hazardNotes s = map hazardText s.hazards+++-- | pg_get_constraintdef's keywords in lower case, leaving a check's expression alone.+tidyConstraint :: Text -> Text+tidyConstraint clause = case T.stripPrefix "add constraint " clause of+    Just rest ->+        let (name, def) = T.breakOn " " rest+            lowered+                | "FOREIGN KEY " `T.isPrefixOf` T.stripStart def = replaceAllInCode foreignKey def+                | otherwise = fromMaybe def (asum [(new <>) <$> T.stripPrefix old def | (old, new) <- leading])+            rest' = replaceSuffixes lowered+         in [S.i|add constraint #{name}#{rest'}|]+    Nothing -> clause+  where+    leading = [(" CHECK ", " check "), (" UNIQUE ", " unique "), (" PRIMARY KEY ", " primary key "), (" EXCLUDE USING ", " exclude using "), (" NOT NULL ", " not null ")]+    foreignKey =+        [ (" FOREIGN KEY ", " foreign key ")+        , (" REFERENCES ", " references ")+        , (" ON DELETE ", " on delete ")+        , (" ON UPDATE ", " on update ")+        , (" CASCADE", " cascade")+        , (" SET NULL", " set null")+        , (" SET DEFAULT", " set default")+        , (" RESTRICT", " restrict")+        , (" NO ACTION", " no action")+        , (" MATCH FULL", " match full")+        , (" DEFERRABLE", " deferrable")+        , (" INITIALLY DEFERRED", " initially deferred")+        , (" INITIALLY IMMEDIATE", " initially immediate")+        ]+    replaceSuffixes t = foldl' (\acc (old, new) -> maybe acc (<> new) (T.stripSuffix old acc)) t [(" NO INHERIT", " no inherit"), (" NOT VALID", " not valid")]+++-- | pg_get_indexdef's keywords in lower case, without the default @USING btree@.+tidyIndex :: Text -> Text+tidyIndex line+    | "CREATE " `T.isPrefixOf` line && " INDEX " `T.isInfixOf` line =+        let (front, back) = T.breakOn " USING " line+            method = T.drop 7 back+            (name, columns) = T.breakOn " " method+            using = if name == "btree" then "" else [S.i| using #{name}|]+         in replaceAllInCode keywords front <> using <> replaceAllInCode tail' columns+    | otherwise = line+  where+    keywords =+        [ ("CREATE UNIQUE INDEX ", "create unique index ")+        , ("CREATE INDEX ", "create index ")+        , ("CONCURRENTLY ", "concurrently ")+        , ("IF NOT EXISTS ", "if not exists ")+        , (" ON ONLY ", " on only ")+        , (" ON ", " on ")+        ]+    tail' = [(" INCLUDE (", " include ("), (" NULLS NOT DISTINCT", " nulls not distinct"), (" WITH (", " with ("), (" WHERE ", " where ")]+++-- | A verify script that checks in the catalog what a migration's statements leave+-- behind. It runs with an empty @search_path@, as sqiff reads the catalog, so names and+-- types print as the plan has them.+verifyScript :: Text -> [Step] -> Text+verifyScript header steps =+    T.intercalate "\n\n" ([header, "BEGIN;", "    set local search_path = '';"] <> map ("    " <>) selects <> assertBlock <> ["ROLLBACK;"]) <> "\n"+  where+    final = Map.elems (Map.fromList [(s.object, s) | s <- steps, s.key.aspect == Definition])+    gone :: Step -> Bool+    gone s = case s.change of+        Dropped _ -> True+        _ -> s.role == Drops+    selects :: [Text]+    selects =+        [ [S.i|select #{columns} from #{table} where false;|]+        | (t, cs) <- Map.toList (Map.fromListWith (flip (<>)) [(t, [c]) | s <- final, not (gone s), Column t c <- [s.object]])+        , let columns = T.intercalate ", " (map quoted cs)+              table = qualified t+        ]+    asserts = concatMap check final+    check :: Step -> [Text]+    check s+        -- Dropped to be created again by a later change: sqitch verify runs every+        -- change's script on the final database, where it exists again.+        | gone s, Changed _ _ <- s.change = []+        | otherwise = checkObject s+    checkObject :: Step -> [Text]+    checkObject s = case s.object of+        Column t col+            | gone s -> [notExists [S.i|select from pg_attribute where attrelid = #{reg t} and attname = #{literal c} and not attisdropped|] [S.i|column #{c} is still on #{qualified t}|]]+            | Just new <- asColumn =<< after s.change ->+                let old = asColumn =<< before s.change+                    differs f = fmap f old /= Just (f new)+                    ty = typeText new.colType+                    attribute :: Text -> Text+                    attribute what = [S.i|(select #{what} from pg_attribute where attrelid = #{reg t} and attname = #{literal c})|]+                 in [ [S.i|assert #{attribute "format_type(atttypid, atttypmod)"} = #{literal ty}, #{literal (c <> " is not " <> ty)};|]+                    | differs (.colType)+                    ]+                        <> [ let notNull = if isNotNull new then "true" else "false" :: Text+                                 message = c <> (if isNotNull new then " is nullable" else " is not null")+                              in [S.i|assert #{attribute "attnotnull"} = #{notNull}, #{literal message};|]+                           | differs isNotNull+                           ]+                        <> [ let name = collationSql co+                              in [S.i|assert #{attribute "attcollation"} = #{literal name}::regcollation, #{literal (c <> " is not collated " <> name)};|]+                           | differs (.collation)+                           , Just co <- [new.collation]+                           ]+          where+            c = nameText col+        TableConstraint t con | s.role == BuildsIndex -> [relation s (QName t.schema con)]+        TableConstraint t con -> let c = nameText con in [presence s [S.i|select from pg_constraint where conrelid = #{reg t} and conname = #{literal c}|] [S.i|constraint #{c} on #{qualified t}|]]+        Policy t name -> let n = nameText name in [presence s [S.i|select from pg_policy where polrelid = #{reg t} and polname = #{literal n}|] [S.i|policy #{n} on #{qualified t}|]]+        Trigger t name -> let n = nameText name in [presence s [S.i|select from pg_trigger where tgrelid = #{reg t} and tgname = #{literal n} and not tgisinternal|] [S.i|trigger #{n} on #{qualified t}|]]+        DomainConstraint d con ->+            let c = nameText con+                domain = literal (typeText d)+             in [presence s [S.i|select from pg_constraint where contypid = to_regtype(#{domain}) and conname = #{literal c}|] [S.i|constraint #{c} on domain #{typeText d}|]]+        Index q ->+            relation s q+                : [ [S.i|assert (select indisvalid from pg_index where indexrelid = #{reg q}), #{literal message};|]+                  | not (gone s)+                  , Just (IndexDefinition def) <- [after s.change]+                  , def.partitioned+                  , let message = [S.i|#{qualified q} is invalid: a partition has no index attached to it|] :: Text+                  ]+        Table q -> [relation s q]+        View q -> [relation s q]+        MaterializedView q -> [relation s q]+        Sequence q -> [relation s q]+        Routine _ q args ->+            let signature = [S.i|#{qualified q}(#{T.intercalate ", " (map typeText args)})|]+             in [lookupBy s "to_regprocedure" signature]+        Type t ->+            lookupBy s "to_regtype" (typeText t)+                : [ [S.i|assert exists (select from pg_enum where enumtypid = to_regtype(#{literal (typeText t)}) and enumlabel = #{literal label}), #{literal ("label " <> label <> " is missing from " <> typeText t)};|]+                  | not (gone s)+                  , Just (TypeDefinition (EnumType labels)) <- [after s.change]+                  , label <- labels+                  ]+        Schema n -> let name = nameText n in [presence s [S.i|select from pg_namespace where nspname = #{literal name}|] [S.i|schema #{name}|]]+        Extension e -> let name = nameText e in [presence s [S.i|select from pg_extension where extname = #{literal name}|] [S.i|extension #{name}|]]+        _ -> []+    -- Whether a regclass-like lookup finds the object, as it should.+    lookupBy :: Step -> Text -> Text -> Text+    lookupBy s function name =+        let stillThere = literal [S.i|#{name} still exists|]+            missing = literal [S.i|#{name} is missing|]+         in if gone s+                then [S.i|assert #{function}(#{literal name}) is null, #{stillThere};|]+                else [S.i|assert #{function}(#{literal name}) is not null, #{missing};|]+    relation :: Step -> QName -> Text+    relation s q = lookupBy s "to_regclass" (qualified q)+    presence :: Step -> Text -> Text -> Text+    presence s query what =+        let missing = literal [S.i|#{what} is missing|]+         in if gone s then notExists query [S.i|#{what} still exists|] else [S.i|assert exists (#{query}), #{missing};|]+    notExists :: Text -> Text -> Text+    notExists query message = [S.i|assert not exists (#{query}), #{literal message};|]+    reg :: QName -> Text+    reg t = let name = literal (qualified t) in [S.i|#{name}::regclass|]+    assertBlock+        | null asserts = []+        | otherwise =+            let block = doBlock (T.intercalate "\n" ([""] <> ["    begin"] <> map ("        " <>) asserts <> ["    end", "    "]))+             in [[S.i|    #{block};|]]
+ src/Sqiff/Sql.hs view
@@ -0,0 +1,198 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | SQL text: which parts of it are code, quoted or comment, and how sqiff writes+-- literals and dollar-quoted bodies into it. Everything that edits SQL text by its words+-- goes through 'replaceInCode', so a string literal, quoted name or comment that happens+-- to contain the words is left alone.+module Sqiff.Sql (+    Region (..),+    regions,+    closed,+    codeOnly,+    topWords,+    codeWords,+    parenthesised,+    splitTopLevel,+    replaceInCode,+    replaceAllInCode,+    literal,+    dollarQuoted,+    doBlock,+    terminator,+) where++import Data.Char (isAlpha, isAlphaNum, isDigit, isSpace)+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import RIO.List qualified as L+import RIO.Vector qualified as V+++data Region = Code | Quoted | Remark+    deriving stock (Eq)+++-- | Each character with whether it is code, inside quotes, or inside a comment.+regions :: Text -> [(Char, Region)]+regions = code ' ' . T.unpack+  where+    code prev = \case+        [] -> []+        '-' : '-' : rest -> let (c, more) = break (== '\n') rest in map (,Remark) ('-' : '-' : c) <> code ' ' more+        '/' : '*' : rest -> ('/', Remark) : ('*', Remark) : block (1 :: Int) rest+        e : '\'' : rest | e `elem` ("eE" :: String), not (wordChar prev) -> (e, Quoted) : ('\'', Quoted) : escaped rest+        '$' : rest+            | not (wordChar prev)+            , Just tag <- dollarTag rest ->+                map (,Quoted) ('$' : tag) <> dollar ('$' : tag) (drop (length tag) rest)+        q : rest | q == '\'' || q == '"' -> (q, Quoted) : inQuote q rest+        c : rest -> (c, Code) : code c rest+    inQuote q = \case+        [] -> []+        c : d : more | c == q && d == q -> (c, Quoted) : (d, Quoted) : inQuote q more+        c : more | c == q -> (c, Quoted) : code c more+        c : more -> (c, Quoted) : inQuote q more+    escaped = \case+        [] -> []+        '\\' : x : more -> ('\\', Quoted) : (x, Quoted) : escaped more+        '\'' : '\'' : more -> ('\'', Quoted) : ('\'', Quoted) : escaped more+        '\'' : more -> ('\'', Quoted) : code '\'' more+        c : more -> (c, Quoted) : escaped more+    dollar tag s = case L.stripPrefix tag s of+        Just after -> map (,Quoted) tag <> code '$' after+        Nothing -> case s of+            [] -> []+            c : more -> (c, Quoted) : dollar tag more+    dollarTag more = case span (\c -> isAlphaNum c || c == '_') more of+        (tag, '$' : _) | maybe True (not . isDigit) (listToMaybe tag) -> Just (tag <> "$")+        _ -> Nothing+    wordChar c = isAlphaNum c || c == '_' || c == '$'+    block depth = \case+        [] -> []+        '*' : '/' : more -> ('*', Remark) : ('/', Remark) : if depth == 1 then code '/' more else block (depth - 1) more+        '/' : '*' : more -> ('/', Remark) : ('*', Remark) : block (depth + 1) more+        c : more -> (c, Remark) : block depth more+++-- | Whether every quote, dollar quote and block comment in the text is closed: a newline+-- after it is code, not inside one of them.+closed :: Text -> Bool+closed t = fmap snd (L.lastMaybe (regions (t <> "\n"))) == Just Code+++-- | The text with its comments blanked out.+codeOnly :: Text -> Text+codeOnly t = T.pack [if r == Remark then ' ' else c | (c, r) <- regions t]+++-- | The words outside quotes, comments and parentheses, lower case, with where they start.+topWords :: Text -> [(Int, Text)]+topWords t = go (0 :: Int) (zip [0 ..] (regions t))+  where+    go _ [] = []+    go depth xs@((k, (c, r)) : rest)+        | r /= Code = go depth rest+        | c == '(' = go (depth + 1) rest+        | c == ')' = go (depth - 1) rest+        | depth == 0 && (isAlpha c || c == '_') =+            let (w, more) = span (\(_, (ch, rr)) -> rr == Code && (isAlphaNum ch || ch == '_' || ch == '$')) xs+             in (k, T.toLower (T.pack (map (fst . snd) w))) : go depth more+        | otherwise = go depth rest+++-- | The words, split at whitespace and at the characters in @separators@ where they are+-- code; a quoted name or literal stays inside its word, whatever it holds, and comments+-- separate words.+codeWords :: String -> Text -> [Text]+codeWords separators t = map T.pack (go [] (regions t))+  where+    go acc [] = done acc []+    go acc ((c, r) : rest)+        | r == Remark || (r == Code && (isSpace c || c `elem` separators)) = done acc (go [] rest)+        | otherwise = go (c : acc) rest+    done acc more = if null acc then more else reverse acc : more+++-- | What the first parentheses in code hold, without them.+parenthesised :: Text -> Maybe Text+parenthesised t = case dropWhile (\(c, r) -> not (r == Code && c == '(')) (regions t) of+    [] -> Nothing+    _ : rest -> T.pack . map fst <$> inside (0 :: Int) [] rest+  where+    inside _ _ [] = Nothing+    inside depth acc ((c, r) : more)+        | r == Code && c == ')' && depth == 0 = Just (reverse acc)+        | r == Code && c == ')' = inside (depth - 1) ((c, r) : acc) more+        | r == Code && c == '(' = inside (depth + 1) ((c, r) : acc) more+        | otherwise = inside depth ((c, r) : acc) more+++-- | The parts between @separator@s in code at the top level, outside quotes and+-- parentheses, stripped.+splitTopLevel :: Char -> Text -> [Text]+splitTopLevel separator t = map (T.strip . T.pack) (go (0 :: Int) [] (regions t))+  where+    go _ acc [] = [reverse acc]+    go depth acc ((c, r) : rest)+        | r == Code && c == separator && depth == 0 = reverse acc : go depth [] rest+        | r == Code && c == '(' = go (depth + 1) (c : acc) rest+        | r == Code && c == ')' = go (depth - 1) (c : acc) rest+        | otherwise = go depth (c : acc) rest+++-- | @old@ replaced by @new@ where all of it is code, outside quotes and comments.+replaceInCode :: Text -> Text -> Text -> Text+replaceInCode old new t+    | T.null old = t+    | otherwise = go 0 t+  where+    kinds = V.fromList (map snd (regions t)) :: Vector Region+    inCode at = all (\k -> kinds V.!? k == Just Code) [at .. at + T.length old - 1]+    go offset rest = case T.breakOn old rest of+        (before, "") -> before+        (before, match) ->+            let at = offset + T.length before+             in if inCode at+                    then before <> new <> go (at + T.length old) (T.drop (T.length old) match)+                    else before <> T.take 1 match <> go (at + 1) (T.drop 1 match)+++-- | Each pair's replacement, in order, in code only.+replaceAllInCode :: [(Text, Text)] -> Text -> Text+replaceAllInCode pairs t = foldl' (\acc (old, new) -> replaceInCode old new acc) t pairs+++-- | A string literal, like PostgreSQL's @quote_literal@: quotes doubled, and an @E@+-- string with backslashes doubled when there is one, so it reads the same whatever+-- @standard_conforming_strings@ is.+literal :: Text -> Text+literal t+    | "\\" `T.isInfixOf` t = let escaped = T.replace "\\" "\\\\" doubled in [i|E'#{escaped}'|]+    | otherwise = [i|'#{doubled}'|]+  where+    doubled = T.replace "'" "''" t+++-- | @body@ between dollar quotes whose tag it does not contain.+dollarQuoted :: Text -> Text+dollarQuoted body = quote <> body <> quote+  where+    -- The candidates never run out, so the fallback is never taken.+    quote = fromMaybe "$$" (L.find (\q -> not (q `T.isInfixOf` (body <> "$"))) candidates)+    candidates = "$$" : [[i|$sqiff#{suffix}$|] | suffix <- "" : map tshow [1 :: Int ..]]+++-- | An anonymous PL/pgSQL block.+doBlock :: Text -> Text+doBlock body = "do " <> dollarQuoted body+++-- | What ends a statement in a psql script: nothing after a "--" note or a query psql+-- runs with @\\gexec@, a semicolon otherwise.+terminator :: Text -> Text+terminator sql+    | "--" `T.isPrefixOf` sql || "\\gexec" `T.isSuffixOf` sql = ""+    | otherwise = ";"
+ src/Sqiff/TableEdit.hs view
@@ -0,0 +1,385 @@+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Compares the table a deploy file creates with the one before the edit, or with the+-- live table, in a transaction that is always rolled back.+module Sqiff.TableEdit (+    TableEdit (..),+    Baseline (..),+    Live (..),+    Drops (..),+    compareTable,+    compareTableWith,+    withEditedTable,+    foreignKeyError,+    firstFailure,+    typeChangeFacts,+    TypeChange (..),+    TableRewrite (..),+    TargetType (..),+    aside,+    columnOrder,+    requireScratch,+    readOnly,+) where++import Data.String.Interpolate (i)+import Data.Text qualified as T+import Hasql.Connection qualified as Connection+import Hasql.Session qualified as Session+import Hasql.TH (singletonStatement, vectorStatement)+import RIO+import RIO.Char (isAlphaNum, isSpace)+import RIO.List (scanl)+import RIO.List qualified as L+import RIO.Map qualified as Map+import Sqiff.Catalog (Partitions (..), describeOn)+import Sqiff.Connection (errorPosition, errorText, failWith, inRolledBackTransaction, serverError)+import Sqiff.Definition (Definition (..), IndexDef (..), TableDef (..), mapNames, mapText)+import Sqiff.Diff (Change (..), Changes, diff)+import Sqiff.Identifier+import Sqiff.Model+import Sqiff.Timing (timed)+++-- | Fails when @conn@ is a standby or streams to standbys: the comparison holds an+-- exclusive lock on the table for the whole run.+requireScratch :: Text -> Connection.Connection -> IO ()+requireScratch name conn = do+    (standby, standbys) <-+        Connection.use conn (Session.statement () [singletonStatement| select pg_is_in_recovery() :: bool, (select count(*) from pg_stat_replication) :: int8 |])+            >>= either (\e -> failWith [i|could not inspect #{name}: #{errorText e}|]) pure+    when standby $ failWith [i|#{name} is a standby; --db needs a scratch database|]+    when (standbys > 0) $ failWith [i|#{name} streams to #{standbys} standbys; --db needs a scratch database, since the comparison locks the table exclusively while it runs|]+++-- | Makes every later transaction on @conn@ read-only.+readOnly :: Connection.Connection -> IO ()+readOnly conn =+    Connection.use conn (Session.script "set default_transaction_read_only = on")+        >>= either (\e -> failWith [i|could not make the connection read-only: #{errorText e}|]) pure+++-- | The error PostgreSQL gives for a foreign key from columns of the first types to columns+-- of the second, tried on temporary tables in a transaction that is rolled back.+foreignKeyError :: Connection.Connection -> [(Text, Text)] -> IO (Maybe Text)+foreignKeyError conn types =+    rolledBack conn "the foreign key check" do+        result <- Connection.use conn (Session.script [i|create temp table sqiff_pk (#{columns snd}, primary key (#{names})); create temp table sqiff_fk (#{columns fst}, foreign key (#{names}) references sqiff_pk (#{names}))|])+        case result of+            Right () -> pure Nothing+            Left e -> maybe (failWith [i|the foreign key check failed: #{errorText e}|]) (pure . Just . tidy) (serverError e)+  where+    tidy e = case T.breakOn "are of incompatible types" e of+        (_, "") -> e+        (_, rest) -> [i|the key columns #{rest}|]+    names = T.intercalate ", " [[i|c#{n}|] | n <- [1 .. length types]]+    columns side = T.intercalate ", " [[i|c#{n} #{side ty}|] | (n, ty) <- zip [1 :: Int ..] types]+++-- | Whether a column type change rewrites the table's files.+data TableRewrite = RewritesFiles | KeepsFiles+    deriving stock (Eq)+++-- | Whether a column's new type is a domain.+data TargetType = DomainType | PlainType+    deriving stock (Eq)+++data TypeChange = TypeChange TableRewrite TargetType+++-- | What changing a column from @old@ to @new@ does, found on a temporary table in a+-- transaction that is rolled back.+typeChangeFacts :: Connection.Connection -> Text -> Text -> IO (Maybe TypeChange)+typeChangeFacts conn old new =+    rolledBack conn "the type change check" do+        made <- Connection.use conn (Session.script [i|create temp table sqiff_retype (c #{old})|])+        before <- fileNode+        altered <- Connection.use conn (Session.script [i|alter table pg_temp.sqiff_retype alter column c type #{new} using c::#{new}|])+        after <- fileNode+        domain <- Connection.use conn (Session.statement new isDomain)+        case (made, before, altered, after, domain) of+            (Right (), Right b, Right (), Right a, Right d) -> pure (Just (TypeChange (if a /= b then RewritesFiles else KeepsFiles) (if d then DomainType else PlainType)))+            results -> do+                -- PostgreSQL refusing the probe means the facts are unknown; losing the+                -- connection is an error.+                let errors = lefts' results+                for_ (L.find (isNothing . serverError) errors) \e -> failWith [i|the type change check failed: #{errorText e}|]+                pure Nothing+  where+    lefts' (a, b, c, d, e) = catMaybes [leftOf a, leftOf b, leftOf c, leftOf d, leftOf e]+    leftOf = either Just (const Nothing)+    fileNode =+        Connection.use conn+            $ Session.statement+                ()+                [singletonStatement|+                    select relfilenode::int8+                    from pg_class+                    where oid = to_regclass('pg_temp.sqiff_retype')+                |]+    isDomain =+        [singletonStatement|+            select coalesce((select typtype = 'd' from pg_type where oid = to_regtype($1::text)), false)::bool+        |]+++-- | Runs @action@ in a transaction that is always rolled back.+rolledBack :: Connection.Connection -> Text -> IO a -> IO a+rolledBack = inRolledBackTransaction+++-- | The table's column names in the table's order.+columnOrder :: Connection.Connection -> QName -> IO [Identifier]+columnOrder conn table =+    Connection.use conn (Session.statement (qualified table) query)+        >>= either (\e -> failWith [i|could not read the columns of #{qualified table}: #{errorText e}|]) (pure . map identifier . toList)+  where+    query =+        [vectorStatement|+            select attname::text+            from pg_attribute+            where attrelid = to_regclass($1::text)+              and attnum > 0+              and not attisdropped+            order by attnum+        |]+++-- | The first of @statements@ that fails, with its error. Runs inside the caller's+-- transaction under a savepoint that is rolled back.+firstFailure :: Connection.Connection -> [Text] -> IO (Maybe Text)+firstFailure conn statements = do+    _ <- Connection.use conn (Session.script "savepoint sqiff_first_failure")+    result <- go (zip [1 :: Int ..] statements)+    _ <- Connection.use conn (Session.script "rollback to savepoint sqiff_first_failure")+    pure result+  where+    go [] = pure Nothing+    go ((n, s) : rest) = Connection.use conn (Session.script s) >>= either (\e -> pure (Just [i|statement #{n}: #{errorText e}|])) (const (go rest))+++data TableEdit = TableEdit+    { current :: Schema+    , desired :: Schema+    , changes :: Changes+    , ignored :: [(ObjectKey, Text)]+    -- ^ Differences left out, with the reason.+    }+++-- | The schema the table moves to while the file builds it again.+aside :: Identifier+aside = identifier "sqiff_aside"+++-- | What the edited file is compared with.+data Baseline+    = -- | The statements of the file before the edit. Drift between the files and the+      -- database cancels out, and everything the edit removes is meant.+      BaseFile [Text]+    | -- | The table as it is.+      LiveTable Live Drops+++-- | Where the live table is read.+data Live+    = SameDatabase+    | -- | Another database, read-only; the file is still built in the comparison's database.+      OtherDatabase Connection.Connection+++-- | What happens to columns and constraints the live table has and the file does not.+data Drops = ReportDrops | AllowDrops+    deriving stock (Eq, Show)+++-- | Whether a pass over the edit describes the table.+data Describing = DescribeTable | SkipDescribe+    deriving stock (Eq)+++compareTable :: Connection.Connection -> Baseline -> QName -> [Text] -> IO TableEdit+compareTable conn baseline table statements = fst <$> compareTableWith conn baseline table statements (pure ()) (const (pure ()))+++-- | 'compareTable' that also runs @before@ in the transaction before anything changes,+-- and @after@ once the table is what the edited file creates.+compareTableWith :: Connection.Connection -> Baseline -> QName -> [Text] -> IO b -> (b -> IO a) -> IO (TableEdit, a)+compareTableWith = editTable DescribeTable+++-- | 'compareTableWith' for the result of @after@ alone: the table is neither built from+-- the file before the edit nor described.+withEditedTable :: Connection.Connection -> Baseline -> QName -> [Text] -> IO b -> (b -> IO a) -> IO a+withEditedTable conn baseline table statements beforeEdit afterEdit = snd <$> editTable SkipDescribe conn baseline table statements beforeEdit afterEdit+++editTable :: Describing -> Connection.Connection -> Baseline -> QName -> [Text] -> IO b -> (b -> IO a) -> IO (TableEdit, a)+-- [allow:SqiffSmallWhere] pre-existing at adoption+editTable describing conn baseline table statements beforeEdit afterEdit = do+    (current, desired, afterResult) <-+        inRolledBackTransaction conn "the table comparison" do+            xact <- currentXact+            script "set local lock_timeout = '5s'"+            exists <-+                Connection.use conn (Session.statement (qualified table) [singletonStatement| select (to_regclass($1::text) is not null)::bool |])+                    >>= either setupFailed pure+            unless exists $ failWith [i|#{qualified table} does not exist yet; a new table only needs its own change|]+            beforeResult <- timed "tableEdit.before" beforeEdit+            owned <-+                Connection.use conn (Session.statement (qualified table) ownedSequences)+                    >>= either setupFailed (pure . toList)+            for_ (filter (\s -> any ((s `T.isInfixOf`) . withoutLineComments) (statements <> baseStatements)) owned) \s ->+                script [i|alter sequence #{tableSchemaRef}#{quoteIdent s} owned by none|]+            script [i|create schema #{quoted aside}|]+            script [i|alter table #{qualified table} set schema #{quoted aside}|]+            current <- timed "tableEdit.current" case baseline of+                _ | describing == SkipDescribe -> pure Map.empty+                BaseFile base -> do+                    script "savepoint sqiff_base"+                    built <- build xact " at --base" base+                    script "rollback to savepoint sqiff_base"+                    pure built+                LiveTable SameDatabase _ -> do+                    schema <- describeTable (QName aside table.name)+                    pure (Map.fromList [(moveBack k, restore def) | (k, def) <- Map.toList schema, belongsTo (QName aside table.name) k def])+                LiveTable (OtherDatabase other) _ -> do+                    schema <- timed "tableEdit.describeOther" $ fst <$> describeOn [other] [] SkipPartitions (Just (qualified table))+                    pure (Map.filterWithKey (belongsTo table) schema)+            desired <- timed "tableEdit.desired" $ build xact "" statements+            afterResult <- timed "tableEdit.after" $ afterEdit beforeResult+            pure (current, desired, afterResult)+    pure (compareTableSchemas baseline current desired, afterResult)+  where+    script sql = Connection.use conn (Session.script sql) >>= either setupFailed pure++    setupFailed e = failWith [i|could not set up the comparison: #{errorText e}|]++    baseStatements = case baseline of+        BaseFile base -> base+        LiveTable _ _ -> []++    build :: Text -> Text -> [Text] -> IO Schema+    build xact label stmts = do+        for_ (zip [1 :: Int ..] stmts) \(n, statement) -> do+            Connection.use conn (Session.script statement)+                >>= either (failWith . statementFailed label n statement) pure+            after <- currentXact+            when (after /= xact)+                $ failWith [i|statement #{n} of the deploy file#{label} ended the transaction the comparison runs in|]+        if describing == DescribeTable+            then do+                schema <- describeTable table+                pure (Map.fromList [(k, def) | (k, def) <- Map.toList schema, belongsTo table k def])+            else pure Map.empty++    currentXact =+        Connection.use conn (Session.statement () [singletonStatement| select pg_current_xact_id() :: text |])+            >>= either setupFailed pure++    describeTable q = timed "tableEdit.describeTable" $ fst <$> describeOn [conn] [] SkipPartitions (Just (qualified q))++    ownedSequences =+        [vectorStatement|+            select s.relname::text+            from pg_class s+            join pg_depend d+              on d.classid = 'pg_class'::regclass+             and d.objid = s.oid+             and d.deptype = 'a'+            join pg_class t+              on t.oid = d.refobjid+            where s.relkind = 'S'+              and t.oid = to_regclass($1::text)+        |]++    withoutLineComments = T.unlines . map (fst . T.breakOn "--") . T.lines++    statementFailed label n statement e =+        let within = maybe "" (\c -> [i|, in constraint #{c}|]) (constraintAt statement =<< errorPosition e) :: Text+         in [i|the deploy file#{label} failed on --db at statement #{n}#{within}: #{errorText e}|]++    asideRef = quoted aside <> "."+    tableSchemaRef = quoted table.schema <> "."++    fromAside q = if q.schema == aside then q{schema = table.schema} else q++    moveBack k = k{object = mapQNames fromAside k.object}++    restore = mapNames fromAside . mapText (T.replace asideRef tableSchemaRef)++    belongsTo q k def = case k.object of+        Table t -> t == q+        Index _ | IndexDefinition ix <- def -> ix.table == q+        Sequence _ -> False+        o -> owningTable o == Just q+++-- | The edit from the table as it is, @current@, to the one the file builds, @desired@.+-- Against a live table, settings the file leaves out stay as they are, and some+-- differences are left out, with the reason; @desired@ is kept as the file builds it.+compareTableSchemas :: Baseline -> Schema -> Schema -> TableEdit+compareTableSchemas baseline current desired =+    TableEdit+        { current+        , desired+        , changes = all' `Map.difference` reasons+        , ignored = Map.toList reasons+        }+  where+    kept = case baseline of+        BaseFile _ -> desired+        LiveTable _ _ -> Map.mapWithKey (keepLiveSettings current) desired+    all' = diff (\_ a b -> a == b) current kept+    reasons = Map.mapMaybeWithKey (ignoredChangeReason baseline) all'+++-- | Settings the file leaves out stay as the table has them.+keepLiveSettings :: Schema -> ObjectKey -> Definition -> Definition+keepLiveSettings current k def = case (k.object, k.aspect, Map.lookup k current) of+    (Table _, Definition, Just (TableDefinition old))+        | TableDefinition new <- def ->+            TableDefinition+                new+                    { rowSecurity = new.rowSecurity || old.rowSecurity+                    , forceRowSecurity = new.forceRowSecurity || old.forceRowSecurity+                    , options = if null new.options then old.options else new.options+                    }+    _ -> def+++-- | Why a difference from a live table is left out of the edit, if it is: what table+-- files do not hold, and drops the options do not allow.+ignoredChangeReason :: Baseline -> ObjectKey -> Change Definition -> Maybe Text+ignoredChangeReason baseline k c+    | BaseFile _ <- baseline = Nothing+    | k.aspect == Privileges = Just "grants are kept outside table files"+    | otherwise = case (k.object, c) of+        (Index _, Dropped _) -> Just "not in the file; indexes are often kept in their own files"+        (Trigger _ _, Dropped _) -> Just "not in the file; triggers are kept in their own files"+        (Policy _ _, Dropped _) -> Just "not in the file; policies may be kept in other files"+        (_, Dropped _) | LiveTable _ ReportDrops <- baseline -> Just "in the database but not in the file; --allow-drops drops it"+        _ -> Nothing+++-- | The name in the @constraint name ...@ clause that holds a 1-based character+-- position of the statement, when the position is inside one.+constraintAt :: Text -> Int -> Maybe Text+constraintAt statement position = do+    let before = T.take (position - 1) statement+        lower = T.toLower before+    guard (T.length lower == T.length before)+    let identChar c = isAlphaNum c || c == '_'+        keyword b = maybe True (not . identChar . snd) (T.unsnoc b) && maybe False (isSpace . fst) (T.uncons (T.drop (T.length b + 10) lower))+    start <- listToMaybe (reverse [T.length b | (b, _) <- T.breakOnAll "constraint" lower, keyword b])+    let clause = T.drop (start + 10) before+        name = T.dropAround (== '"') (T.takeWhile (\c -> identChar c || c == '"') (T.stripStart clause))+        depths = scanl (\d c -> d + (if c == '(' then 1 else if c == ')' then -1 else 0)) (0 :: Int) (T.unpack clause)+        leftClause = or [d < 0 || (c == ',' && d == 0) | (d, c) <- zip depths (T.unpack clause)]+    guard (not (T.null name) && not leftClause)+    pure name
+ src/Sqiff/Timing.hs view
@@ -0,0 +1,37 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Phase timings on stderr, when @SQIFF_TIMING@ is set.+module Sqiff.Timing (timed, measure) where++import Data.ByteString (hPut)+import Data.String.Interpolate (i)+import GHC.Clock qualified as Clock+import RIO+import System.Environment (lookupEnv)+import Text.Printf (printf)+++-- | Runs @action@; with @SQIFF_TIMING@ set, prints its label, start and duration in+-- milliseconds to stderr.+timed :: MonadIO m => Text -> m a -> m a+timed label action =+    liftIO (lookupEnv "SQIFF_TIMING") >>= \case+        Nothing -> action+        Just _ -> do+            start <- liftIO Clock.getMonotonicTimeNSec+            result <- action+            end <- liftIO Clock.getMonotonicTimeNSec+            let ms :: Word64 -> String+                ms n = printf "%.1f" (fromIntegral n / 1e6 :: Double)+            liftIO (hPut stderr (encodeUtf8 [i|timing\t#{label}\t#{ms start}\t#{ms (end - start)}\n|]))+            pure result+++-- | With @SQIFF_TIMING@ set, evaluates @x@ and prints how long that took.+measure :: MonadIO m => Text -> Int -> m ()+measure label x =+    liftIO (lookupEnv "SQIFF_TIMING") >>= \case+        Nothing -> pure ()+        Just _ -> timed label (void (evaluate x))
+ test/Integration.hs view
@@ -0,0 +1,365 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | End-to-end tests against a throwaway PostgreSQL cluster, one per directory under+-- @test/fixtures@:+--+-- * @from.sql@ and @to.sql@ build the two databases;+-- * @diff.golden@ and @plan.golden@ hold what @sqiff diff@ and @sqiff plan@ print, as a+--   record of the current behaviour (refresh with @--accept@);+-- * the round trip has psql run the plan on @from@, and expects+--   @sqiff diff@ to find nothing left;+-- * the sqitch round trip writes the plan as sqitch changes into a new project, has+--   sqitch deploy and verify them on a fresh copy of @from@, and expects the same;+-- * after its round trip, each migration is reverted, deployed again and reverted again,+--   last first, and reverting them all must give back @from@;+-- * a @known-bug@ file marks a fixture whose round trips fail today, and says why;+-- * a @revert-gap@ file marks one whose changes PostgreSQL cannot fully revert, and why.+module Integration (tests) where++import Data.String.Interpolate (i)+import Hasql.Connection qualified as Connection+import Hasql.Session qualified as Session+import Hasql.TH (singletonStatement)+import Postgres+import RIO+import RIO.ByteString.Lazy qualified as BL+import RIO.Char (isAlphaNum)+import RIO.Directory (doesFileExist, listDirectory)+import RIO.FilePath ((<.>), (</>))+import RIO.List (sort)+import RIO.Text qualified as T+import Sqiff.Connection (withConnections, withSharedSnapshot)+import Sqiff.ConnectionString (connectionString)+import Sqiff.Sqitch.Plan (SqitchPlan (..), readPlan)+import System.Environment (lookupEnv, setEnv)+import System.Process.Typed (byteStringInput, proc, readProcess, setStdin, setWorkingDir)+import Test.Tasty (TestTree, testGroup, withResource)+import Test.Tasty.ExpectedFailure (expectFailBecause)+import Test.Tasty.Golden (goldenVsStringDiff)+import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))+++fixturesDir :: FilePath+fixturesDir = "test/fixtures"+++tests :: Bool -> IO TestTree+tests sqitchFound = do+    names <- sort <$> listDirectory fixturesDir+    fixtures <- traverse readFixture names+    findBinaries >>= \case+        Left why -> pure (testGroup "integration" [testCase "PostgreSQL is available" (assertFailure (T.unpack why))])+        Right bin -> do+            -- sqitch runs psql from PATH.+            path <- fromMaybe "" <$> lookupEnv "PATH"+            setEnv "PATH" [i|#{bin}:#{path}|]+            pure $ withResource (startCluster bin) stopCluster \getCluster ->+                let shared = Shared{getCluster, sqitchFound}+                 in testGroup "integration" (sharedSnapshot getCluster : deepViewChains getCluster : map (fixture shared) fixtures)+++-- | Connections that share a snapshot do not see what another commits after it.+sharedSnapshot :: IO Cluster -> TestTree+sharedSnapshot getCluster = testCase "connections in a shared snapshot see one state" do+    cluster <- getCluster+    createDatabase cluster "snapshot"+    let db = connectionString (conninfo cluster "snapshot")+        tableCount c = Connection.use c (Session.statement () [singletonStatement| select count(*)::int8 from pg_class where relname = 'late' |]) >>= either (assertFailure . show) pure+    withConnections db 2 \conns@(a :| bs) -> do+        seen <- withSharedSnapshot conns do+            runScript cluster "snapshot" "create table late ()" >>= either (assertFailure . T.unpack) pure+            (,) <$> tableCount a <*> traverse tableCount bs+        seen @?= (0, [0])+        after <- tableCount a+        after @?= 1+++-- | Finding what depends on a retyped column takes time in proportion to what it+-- reaches, not to the size of the catalog at every step: three chains of 100 nested+-- views over 300 tables used to take several seconds.+deepViewChains :: IO Cluster -> TestTree+deepViewChains getCluster = testCase "deep view chains are planned in reasonable time" do+    cluster <- getCluster+    for_ [("deep_from", "int"), ("deep_to", "bigint")] \(db, retyped) -> do+        createDatabase cluster db+        runScript cluster db (schema retyped) >>= either (assertFailure . T.unpack) pure+    started <- getMonotonicTime+    (code, out, err) <- runSqiff cluster ["plan"] "deep_from" "deep_to"+    elapsed <- subtract started <$> getMonotonicTime+    assertBool (T.unpack err) (code == ExitSuccess)+    length (filter ("drop view" `T.isPrefixOf`) (T.lines out)) @?= chains * depth+    assertBool [i|sqiff plan took #{elapsed} s|] (elapsed < 3)+  where+    chains, depth, tables :: Int+    chains = 3+    depth = 100+    tables = 300+    schema :: Text -> Text+    schema retyped =+        T.unlines+            $ [ [i|create table t#{n} (id int primary key, a #{if n < chains then retyped else "int"}, b text#{reference n});|]+              | n <- [0 .. tables - 1]+              ]+            <> [ [i|create view c#{c}_v#{j} as #{viewBody c j};|]+               | c <- [0 .. chains - 1]+               , j <- [0 .. depth - 1]+               ]+    reference :: Int -> Text+    reference n = if n == 0 then "" else [i|, p int references t#{n - 1}(id)|]+    viewBody :: Int -> Int -> Text+    viewBody c j+        | j == 0 = [i|select id, a, b from t#{c}|]+        | otherwise = [i|select v.id, v.a, v.b from c#{c}_v#{j - 1} v join t#{chains + (c * depth + j) `mod` (tables - chains)} t on t.id = v.id|]+++-- | Runs sqiff's @command@ from @fromDb@ to @toDb@, outside the repository so no+-- sqiff.yaml is read.+-- [allow:SqiffNamedTuples] pre-existing at adoption+runSqiff :: Cluster -> [String] -> Text -> Text -> IO (ExitCode, Text, Text)+runSqiff cluster command fromDb toDb = do+    exe <- fromMaybe "sqiff" <$> lookupEnv "SQIFF_EXE"+    let args = command <> ["--from", T.unpack (conninfo cluster fromDb), "--to", T.unpack (conninfo cluster toDb)]+    (code, out, err) <- readProcess (setWorkingDir "/" (proc exe args))+    pure (code, decodeOutput out, decodeOutput err)+++-- | What a process printed, as text.+decodeOutput :: BL.ByteString -> Text+decodeOutput = decodeUtf8Lenient . BL.toStrict+++-- | What every fixture's tests share.+data Shared = Shared+    { getCluster :: IO Cluster+    , sqitchFound :: Bool+    -- ^ Whether sqitch is available: without it, every sqitch round trip fails.+    }+++-- | One directory under @test/fixtures@, with the reasons its marker files give.+data Fixture = Fixture+    { name :: FilePath+    , knownBug :: Maybe Text+    -- ^ Why its round trips fail today, so they are expected to.+    , revertGap :: Maybe Text+    -- ^ Why PostgreSQL cannot fully revert its changes, so they are not reverted.+    }+++-- | The fixture in the directory @name@.+readFixture :: FilePath -> IO Fixture+readFixture name = do+    knownBug <- reasonIn name "known-bug"+    revertGap <- reasonIn name "revert-gap"+    pure Fixture{name, knownBug, revertGap}+++-- | The reason in one of a fixture's marker files, if it has it.+reasonIn :: FilePath -> FilePath -> IO (Maybe Text)+reasonIn name file = do+    let path = fixturesDir </> name </> file+    doesFileExist path >>= \case+        True -> Just . T.strip <$> readFileUtf8 path+        False -> pure Nothing+++-- | Where the fixture's files are.+fixtureDir :: Fixture -> FilePath+fixtureDir f = fixturesDir </> f.name+++-- | The databases of one fixture's tests, named after it so fixtures do not collide.+data Databases = Databases+    { from :: Text+    -- ^ Built from @from.sql@; the round trip applies the plan to it.+    , to :: Text+    -- ^ Built from @to.sql@.+    , sqitch :: Text+    -- ^ A fresh copy of @from@ for sqitch to deploy to.+    , original :: Text+    -- ^ Another copy of @from@, to compare with once sqitch has reverted every change.+    }+++-- | The fixture's databases.+fixtureDatabases :: Fixture -> Databases+fixtureDatabases f =+    Databases+        { from = base <> "_from"+        , to = base <> "_to"+        , sqitch = base <> "_sqitch"+        , original = base <> "_original"+        }+  where+    base = "f_" <> T.map (\c -> if isAlphaNum c then c else '_') (T.pack f.name)+++-- | What sqiff printed for one fixture before the round trip changed @from@.+data Before = Before+    { diffOut :: Text+    , planOut :: Text+    }+++-- | The fixture's goldens and round trips, which share one run of 'prepare'.+fixture :: Shared -> Fixture -> TestTree+fixture shared f = withResource (prepare shared f) (const (pure ())) \getBefore ->+    testGroup+        f.name+        [ golden f "diff" (.diffOut) getBefore+        , golden f "plan" (.planOut) getBefore+        , withKnownBug f (roundTrip shared f getBefore)+        , withKnownBug f (sqitchRoundTrip shared f getBefore)+        ]+++-- | Expects @test@ to fail while the fixture has a known bug.+withKnownBug :: Fixture -> TestTree -> TestTree+withKnownBug f test = maybe test (\why -> expectFailBecause (T.unpack why) test) f.knownBug+++-- | Builds the fixture's @from@ and @to@, and records what sqiff prints for them.+prepare :: Shared -> Fixture -> IO Before+prepare shared f = do+    cluster <- shared.getCluster+    let databases = fixtureDatabases f+    for_ [(databases.from, "from.sql"), (databases.to, "to.sql")] \(db, file) -> do+        createDatabase cluster db+        sql <- readFileUtf8 (fixtureDir f </> file)+        runScript cluster db sql >>= either (\e -> throwString [i|#{file}: #{e}|]) pure+    (_, diffOut, _) <- runSqiff cluster ["diff"] databases.from databases.to+    (planCode, planOut, planErr) <- runSqiff cluster ["plan"] databases.from databases.to+    unless (planCode == ExitSuccess) $ throwString [i|sqiff plan failed: #{planErr}|]+    pure Before{diffOut, planOut}+++-- | Compares one of sqiff's outputs with the fixture's @label.golden@.+golden :: Fixture -> String -> (Before -> Text) -> IO Before -> TestTree+golden f label field getBefore =+    goldenVsStringDiff label (\ref new -> ["diff", "-u", ref, new]) (fixtureDir f </> label <.> "golden")+        $ BL.fromStrict+        . encodeUtf8+        . field+        <$> getBefore+++-- | The plan, run by psql on @from@, leaves nothing for diff to find.+roundTrip :: Shared -> Fixture -> IO Before -> TestTree+roundTrip shared f getBefore = testCase "round trip" do+    before <- getBefore+    cluster <- shared.getCluster+    let databases = fixtureDatabases f+        psql = proc "psql" ["-X", "-q", "-v", "ON_ERROR_STOP=1", "-d", T.unpack (conninfo cluster databases.from), "-f", "-"]+    (applied, psqlOut, psqlErr) <- readProcess (setStdin (byteStringInput (BL.fromStrict (encodeUtf8 before.planOut))) psql)+    unless (applied == ExitSuccess)+        $ assertFailure (T.unpack [i|the plan did not apply:\n#{decodeOutput psqlOut}#{decodeOutput psqlErr}|])+    (code, out, err) <- runSqiff cluster ["diff"] databases.from databases.to+    unless (code == ExitSuccess)+        $ assertFailure (T.unpack [i|after the plan, diff still finds:\n#{out}#{err}|])+++-- | The plan written as sqitch changes, deployed and verified by sqitch on a fresh copy+-- of from, leaves nothing for diff to find.+sqitchRoundTrip :: Shared -> Fixture -> IO Before -> TestTree+sqitchRoundTrip shared f getBefore = testCase "sqitch round trip" do+    unless shared.sqitchFound $ assertFailure "sqitch is neither on PATH nor in SQIFF_TEST_SQITCH_BIN"+    before <- getBefore+    cluster <- shared.getCluster+    let databases = fixtureDatabases f+    createDatabase cluster databases.sqitch+    fromSql <- readFileUtf8 (fixtureDir f </> "from.sql")+    runScript cluster databases.sqitch fromSql >>= either (assertFailure . T.unpack) pure+    withSystemTempDirectory "sqiff-sqitch-round-trip" \project -> do+        let env = SqitchProject{cluster, databases, fromSql, project}+        runSqitch env "sqitch init" ["init", "proj", "--engine", "pg"]+        writeChanges env+        -- Nothing to write leaves sqitch an empty plan, which it refuses to deploy.+        unless (T.null (T.strip before.planOut)) do+            assertDeployedMatches env+            -- Each migration's revert returns to the state after the one before: it can+            -- be deployed again from there, and reverting them all gives back from.+            changes <- (.changes) <$> readPlan (project </> "sqitch.plan")+            manual <- hasManualReverts project changes+            unless (manual || isJust f.revertGap) do+                exerciseReverts env changes+                assertFullyReverted env+++-- | Where a fixture's sqitch round trip runs: the project sqiff writes the plan into,+-- and the databases sqitch deploys it to.+data SqitchProject = SqitchProject+    { cluster :: Cluster+    , databases :: Databases+    , fromSql :: Text+    -- ^ The fixture's @from.sql@.+    , project :: FilePath+    }+++-- | Runs sqitch in the project; if it fails, so does the test, with what it printed.+runSqitch :: SqitchProject -> Text -> [String] -> Assertion+runSqitch env what args = do+    (code, out, err) <- readProcess (setWorkingDir env.project (proc "sqitch" args))+    unless (code == ExitSuccess)+        $ assertFailure (T.unpack [i|#{what} failed:\n#{decodeOutput out}#{decodeOutput err}|])+++-- | The sqitch target of the database sqitch deploys to.+target :: SqitchProject -> String+target env = T.unpack (sqitchTarget env.cluster env.databases.sqitch)+++-- | Has sqiff write the plan from sqitch's copy of @from@ to @to@ into the project.+writeChanges :: SqitchProject -> Assertion+writeChanges env = do+    (code, out, err) <- runSqiff env.cluster ["sqitch", "--project", env.project] env.databases.sqitch env.databases.to+    unless (code == ExitSuccess) $ assertFailure (T.unpack [i|sqiff sqitch failed:\n#{out}#{err}|])+++-- | sqitch deploys and verifies every change, after which diff finds nothing left.+assertDeployedMatches :: SqitchProject -> Assertion+assertDeployedMatches env = do+    runSqitch env "sqitch deploy" ["deploy", "--verify", target env]+    runSqitch env "sqitch verify" ["verify", target env]+    (code, out, err) <- runSqiff env.cluster ["diff", "--exclude-schema", "sqitch"] env.databases.sqitch env.databases.to+    unless (code == ExitSuccess)+        $ assertFailure (T.unpack [i|after sqitch deploy, diff still finds:\n#{out}#{err}|])+++-- | Whether the revert of one of the project's @changes@ stops at a step sqiff cannot+-- write, which is left to a person.+hasManualReverts :: FilePath -> [Text] -> IO Bool+hasManualReverts project changes = do+    reverts <- for changes \name -> readFileUtf8 (project </> "revert" </> T.unpack name <> ".sql")+    pure (any ("sqiff could not write this step" `T.isInfixOf`) reverts)+++-- | Reverts each of the deployed @changes@, last first, deploys it again and reverts it+-- again.+exerciseReverts :: SqitchProject -> [Text] -> Assertion+exerciseReverts env changes = for_ (reverse (zip [0 ..] changes)) \(k, name) -> do+    runSqitch env [i|sqitch revert of #{name}|] (["revert", "-y"] <> revertTo k <> [target env])+    runSqitch env [i|sqitch deploy of #{name} after its revert|] ["deploy", "--verify", "--to", T.unpack name, target env]+    runSqitch env [i|sqitch revert of #{name} again|] (["revert", "-y"] <> revertTo k <> [target env])+  where+    -- Reverting the @k@th change goes back to the one before it, or to nothing.+    revertTo :: Int -> [String]+    revertTo k = case drop (k - 1) changes of+        previous : _ | k > 0 -> ["--to", T.unpack previous]+        _ -> []+++-- | With every change reverted, diff finds nothing between sqitch's database and a fresh+-- copy of @from@.+assertFullyReverted :: SqitchProject -> Assertion+assertFullyReverted env = do+    createDatabase env.cluster env.databases.original+    runScript env.cluster env.databases.original env.fromSql >>= either (assertFailure . T.unpack) pure+    (code, out, err) <- runSqiff env.cluster ["diff", "--exclude-schema", "sqitch"] env.databases.sqitch env.databases.original+    unless (code == ExitSuccess)+        $ assertFailure (T.unpack [i|after reverting every change, diff with from finds:\n#{out}#{err}|])
+ test/Main.hs view
@@ -0,0 +1,14 @@+module Main (main) where++import Integration qualified+import Rewriting qualified+import Test.Tasty (defaultMain, testGroup)+import Unit qualified+import Writing qualified+++main :: IO ()+main = do+    sqitch <- Writing.setUpSqitch+    integration <- Integration.tests sqitch+    defaultMain (testGroup "sqiff" [Unit.tests, Rewriting.tests, integration, Writing.tests sqitch])
+ test/Postgres.hs view
@@ -0,0 +1,110 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | A throwaway PostgreSQL cluster for the integration tests: initdb in a temporary+-- directory, listening on a Unix socket only, removed when the tests end.+--+-- The binaries come from @SQIFF_TEST_PG_BIN@ when it is set, else from @PATH@.+module Postgres (+    Cluster,+    findBinaries,+    startCluster,+    stopCluster,+    conninfo,+    sqitchTarget,+    createDatabase,+    runScript,+) where++import Data.String.Interpolate (i)+import Hasql.Connection qualified as Connection+import Hasql.Session qualified as Session+import RIO+import RIO.Directory (createDirectory, findExecutable, removeDirectoryRecursive)+import RIO.FilePath ((</>))+import RIO.Text qualified as T+import Sqiff.Connection (connect, errorText)+import Sqiff.ConnectionString (connectionString)+import System.Environment (lookupEnv)+import System.IO.Temp (createTempDirectory)+import System.Process.Typed (proc, readProcess)+++data Cluster = Cluster+    { binDir :: FilePath+    , root :: FilePath+    }+++-- | The directory with @initdb@ and @pg_ctl@, or why there is none.+findBinaries :: IO (Either Text FilePath)+findBinaries =+    lookupEnv "SQIFF_TEST_PG_BIN" >>= \case+        Just dir -> pure (Right dir)+        Nothing ->+            findExecutable "initdb" <&> \case+                Just path -> Right (takeDirectoryOf path)+                Nothing -> Left "initdb is neither on PATH nor in SQIFF_TEST_PG_BIN"+  where+    takeDirectoryOf = reverse . drop 1 . dropWhile (/= '/') . reverse+++-- | Makes and starts a cluster. The socket lives under /tmp: a Unix socket path must stay+-- under about 100 bytes, which a nested temporary directory can exceed.+startCluster :: FilePath -> IO Cluster+startCluster binDir = do+    root <- createTempDirectory "/tmp" "sqiff-test"+    let cluster = Cluster{binDir, root}+    createDirectory (root </> "socket")+    run cluster "initdb" ["-D", root </> "data", "-U", "sqiff", "--auth=trust", "--no-sync", "-E", "UTF8", "--locale=C"]+    run+        cluster+        "pg_ctl"+        [ "-D"+        , root </> "data"+        , "-l"+        , root </> "log"+        , "-w"+        , "-o"+        , [i|-k #{root </> "socket"} -c listen_addresses='' -c fsync=off -c synchronous_commit=off -c full_page_writes=off -c max_connections=300|]+        , "start"+        ]+    pure cluster+++stopCluster :: Cluster -> IO ()+stopCluster cluster = do+    run cluster "pg_ctl" ["-D", root cluster </> "data", "-m", "immediate", "-w", "stop"]+    removeDirectoryRecursive (root cluster)+++run :: Cluster -> FilePath -> [String] -> IO ()+run cluster program args = do+    (code, out, err) <- readProcess (proc (binDir cluster </> program) args)+    unless (code == ExitSuccess)+        $ throwString [i|#{program} failed: #{decodeUtf8Lenient (toStrictBytes out)}#{decodeUtf8Lenient (toStrictBytes err)}|]+++-- | The connection string for one of the cluster's databases.+conninfo :: Cluster -> Text -> Text+conninfo cluster db = [i|host=#{root cluster </> "socket"} user=sqiff dbname=#{db}|]+++-- | The sqitch target for one of the cluster's databases.+sqitchTarget :: Cluster -> Text -> Text+sqitchTarget cluster db = [i|db:pg://sqiff@/#{db}?host=#{root cluster </> "socket"}|]+++-- | Drops @db@ if it is there and creates it again, empty.+createDatabase :: Cluster -> Text -> IO ()+createDatabase cluster db = do+    _ <- runScript cluster "postgres" [i|drop database if exists #{db} with (force)|]+    runScript cluster "postgres" [i|create database #{db}|] >>= either (throwString . T.unpack) pure+++-- | Runs @sql@ on @db@ as one simple-protocol script, so in one implicit transaction.+runScript :: Cluster -> Text -> Text -> IO (Either Text ())+runScript cluster db sql =+    bracket (connect (connectionString (conninfo cluster db))) Connection.release \conn ->+        first errorText <$> Connection.use conn (Session.script sql)
+ test/Rewriting.hs view
@@ -0,0 +1,424 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Byte-for-byte tests of rewriting a table's deploy file: the text it keeps, where it+-- puts what it adds, what it removes with a statement, and the differences it leaves.+module Rewriting (tests) where++import Data.String.Interpolate (__i)+import RIO+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.Definition+import Sqiff.Identifier (QName, identifier, qname, typeName)+import Sqiff.Model (Aspect (..), ObjectId (..), ObjectKey (..), Schema, definitionKey)+import Sqiff.Rewrite (Rewrite (..), rewriteFile)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (Assertion, testCase, (@?=))+++tests :: TestTree+tests =+    testGroup+        "rewriting a deploy file"+        [ testCase "an unchanged file comes back as it was" unchanged+        , testCase "column, constraint, index and comment edits together" mixed+        , testCase "a removed statement or column takes its own comments with it" removals+        , testCase "new indexes and comments go after the table when the file keeps none" anchoredOnTable+        , testCase "new objects stay unplaced when the file does not create the table" noTable+        , testCase "table settings become alter statements and a with clause" settings+        ]+++-- | The table every test rewrites.+widgets :: QName+widgets = qname "app" "widgets"+++-- | Rewrites @file@, which creates @fromFile@, to create @live@: the new text, or the+-- error in its place, and the differences left unplaced.+rewrite :: Schema -> Schema -> Text -> (Text, [Text])+rewrite fromFile live file = case rewriteFile widgets Set.empty liveOrder live fromFile file of+    Left e -> ("error: " <> e, [])+    Right r -> (r.text, r.unplaced)+  where+    liveOrder = [c | k <- Map.keys live, k.aspect == Definition, Column _ c <- [k.object]]+++-- | Asserts the rewrite's text line by line, so a failure points at the line.+rewritesTo :: (Text, [Text]) -> (Text, [Text]) -> Assertion+rewritesTo (actual, actualUnplaced) (expected, expectedUnplaced) = do+    T.lines actual @?= T.lines expected+    actual @?= expected+    actualUnplaced @?= expectedUnplaced+++columnRow :: Text -> Text -> Nullability -> (ObjectKey, Definition)+columnRow c ty nullability =+    ( definitionKey (Column widgets (identifier c))+    , ColumnDefinition+        ColumnDef+            { colType = typeName ty+            , collation = Nothing+            , nullability+            , value = PlainColumn Nothing+            , rewritesOnAdd = False+            , position = Position 0+            , inheritedOnly = False+            }+    )+++tableRow :: TableDef -> (ObjectKey, Definition)+tableRow def = (definitionKey (Table widgets), TableDefinition def)+++plainTable :: TableDef+plainTable =+    TableDef+        { unlogged = False+        , partitionBy = Nothing+        , partitionOf = Nothing+        , rowSecurity = False+        , forceRowSecurity = False+        , options = []+        , inherits = []+        }+++checkRow :: Text -> [Text] -> Text -> (ObjectKey, Definition)+checkRow n cs clause =+    ( definitionKey (TableConstraint widgets (identifier n))+    , ConstraintDefinition ConstraintDef{kind = Check, validity = Validated, columns = map identifier cs, references = Nothing, clause, inheritedOnly = False}+    )+++indexRow :: Text -> Text -> (ObjectKey, Definition)+indexRow n statement =+    ( definitionKey (Index (qname "app" n))+    , IndexDefinition IndexDef{table = widgets, unique = False, partitioned = False, statement}+    )+++commentRow :: ObjectId -> Text -> (ObjectKey, Definition)+commentRow o t = (ObjectKey Comment o, Printed t)+++notNull :: Nullability+notNull = NotNull Validated Nothing+++unchanged :: Assertion+unchanged = do+    let file =+            [__i|+                -- Deploy app:widgets to pg++                begin;++                create table app.widgets (+                    id bigint not null,+                    -- what it is called+                    name text, -- shown to people+                    qty integer,+                    constraint widgets_qty_check check (qty > 0)+                );++                create index widgets_name_idx+                    on app.widgets (name);++                comment on table app.widgets is 'Things';++                commit;\n+            |]+        schema =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , columnRow "name" "text" Nullable+                , columnRow "qty" "integer" Nullable+                , checkRow "widgets_qty_check" ["qty"] "CHECK ((qty > 0))"+                , indexRow "widgets_name_idx" "CREATE INDEX widgets_name_idx ON app.widgets USING btree (name)"+                , commentRow (Table widgets) "Things"+                ]+    rewrite schema schema file `rewritesTo` (file, [])+++mixed :: Assertion+mixed = do+    let file =+            [__i|+                -- Deploy app:widgets to pg++                begin;++                create table app.widgets (+                    id bigint not null,+                    -- the old name+                    label text,+                    qty integer, -- how many+                    constraint widgets_qty_check check (qty > 0)+                );++                create index widgets_label_idx+                    on app.widgets (label);++                create index widgets_qty_idx on app.widgets (qty);++                comment on table app.widgets is 'Things';++                comment on column app.widgets.label is 'Old label';++                commit;\n+            |]+        fromFile =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , columnRow "label" "text" Nullable+                , columnRow "qty" "integer" Nullable+                , checkRow "widgets_qty_check" ["qty"] "CHECK ((qty > 0))"+                , indexRow "widgets_label_idx" "CREATE INDEX widgets_label_idx ON app.widgets USING btree (label)"+                , indexRow "widgets_qty_idx" "CREATE INDEX widgets_qty_idx ON app.widgets USING btree (qty)"+                , commentRow (Table widgets) "Things"+                , commentRow (Column widgets (identifier "label")) "Old label"+                ]+        live =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , columnRow "qty" "bigint" Nullable+                , columnRow "title" "text" notNull+                , checkRow "widgets_qty_check" ["qty"] "CHECK ((qty >= 0))"+                , indexRow "widgets_qty_idx" "CREATE INDEX widgets_qty_idx ON app.widgets USING btree (qty DESC)"+                , indexRow "widgets_title_idx" "CREATE UNIQUE INDEX widgets_title_idx ON app.widgets USING btree (title)"+                , commentRow (Table widgets) "Widgets, it's said"+                , commentRow (Column widgets (identifier "title")) "What it is called"+                ]+    rewrite fromFile live file+        `rewritesTo` ( [__i|+                           -- Deploy app:widgets to pg++                           begin;++                           create table app.widgets (+                               id bigint not null,+                               qty bigint, -- how many+                               title text not null,+                               constraint widgets_qty_check check ((qty >= 0))+                           );++                           create index if not exists widgets_qty_idx+                               on app.widgets (qty DESC);++                           create unique index if not exists widgets_title_idx+                               on app.widgets (title);++                           comment on table app.widgets is 'Widgets, it''s said';++                           comment on column app.widgets.title is+                               'What it is called';++                           commit;\n+                       |]+                     , []+                     )+++removals :: Assertion+removals = do+    let file =+            [__i|+                begin;++                create table app.widgets (+                    id bigint not null,++                    -- Kept for old clients.+                    -- Remove after the migration.+                    legacy text,+                    -- Details++                    notes text,+                    name text+                );++                -- Lookups by name.+                create index widgets_name_idx on app.widgets (name);++                -- The legacy column's comment.+                comment on column app.widgets.legacy is 'Old';+                comment on column app.widgets.name is 'Name';++                commit;\n+            |]+        fromFile =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , columnRow "legacy" "text" Nullable+                , columnRow "notes" "text" Nullable+                , columnRow "name" "text" Nullable+                , indexRow "widgets_name_idx" "CREATE INDEX widgets_name_idx ON app.widgets USING btree (name)"+                , commentRow (Column widgets (identifier "legacy")) "Old"+                , commentRow (Column widgets (identifier "name")) "Name"+                ]+        live =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , columnRow "name" "text" Nullable+                , commentRow (Column widgets (identifier "name")) "Name"+                ]+    rewrite fromFile live file+        `rewritesTo` ( [__i|+                           begin;++                           create table app.widgets (+                               id bigint not null,+                               -- Details++                               name text+                           );++                           comment on column app.widgets.name is 'Name';++                           commit;\n+                       |]+                     , []+                     )+++anchoredOnTable :: Assertion+anchoredOnTable = do+    let file =+            [__i|+                begin;++                create table app.widgets (+                    id bigint not null+                );++                create index widgets_old_idx on app.widgets (id);++                commit;\n+            |]+        fromFile =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , indexRow "widgets_old_idx" "CREATE INDEX widgets_old_idx ON app.widgets USING btree (id)"+                ]+        live =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , indexRow "widgets_id_idx" "CREATE INDEX widgets_id_idx ON app.widgets USING hash (id)"+                , commentRow (Table widgets) "Things"+                , commentRow (Column widgets (identifier "id")) "Line one\nline two"+                ]+    rewrite fromFile live file+        `rewritesTo` ( [__i|+                           begin;++                           create table app.widgets (+                               id bigint not null+                           );++                           create index if not exists widgets_id_idx+                               on app.widgets using hash (id);++                           comment on table app.widgets is+                               'Things';++                           comment on column app.widgets.id is+                               $comment$Line one+                           line two$comment$;++                           commit;\n+                       |]+                     , []+                     )+++noTable :: Assertion+noTable = do+    let file =+            [__i|+                begin;++                select 1;++                commit;\n+            |]+        fromFile =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                ]+        live =+            Map.fromList+                [ tableRow plainTable{rowSecurity = True}+                , columnRow "id" "integer" notNull+                , indexRow "widgets_id_idx" "CREATE INDEX widgets_id_idx ON app.widgets USING btree (id)"+                , commentRow (Table widgets) "Things"+                ]+    rewrite fromFile live file+        `rewritesTo` ( file+                     ,+                         [ "table app.widgets: differs from the database"+                         , "table column app.widgets.id: differs from the database"+                         , "index app.widgets_id_idx: in the database, not in the file"+                         , "table app.widgets (comment): in the database, not in the file"+                         ]+                     )+++settings :: Assertion+settings = do+    let file =+            [__i|+                begin;++                create table app.widgets (+                    id bigint not null+                );++                create index widgets_id_idx on app.widgets (id);++                commit;\n+            |]+        fromFile =+            Map.fromList+                [ tableRow plainTable+                , columnRow "id" "bigint" notNull+                , indexRow "widgets_id_idx" "CREATE INDEX widgets_id_idx ON app.widgets USING btree (id)"+                ]+        live =+            Map.fromList+                [ tableRow plainTable{rowSecurity = True, forceRowSecurity = True, options = ["fillfactor=70"]}+                , columnRow "id" "bigint" notNull+                , indexRow "widgets_id_idx" "CREATE INDEX widgets_id_idx ON app.widgets USING btree (id)"+                ]+    rewrite fromFile live file+        `rewritesTo` ( [__i|+                           begin;++                           create table app.widgets (+                               id bigint not null+                           ) with (fillfactor=70);++                           alter table app.widgets enable row level security;++                           alter table app.widgets force row level security;++                           create index widgets_id_idx on app.widgets (id);++                           commit;\n+                       |]+                     , []+                     )
+ test/Unit.hs view
@@ -0,0 +1,779 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Tests of the pure parts: quoting, name templates, script splitting, plan parsing,+-- ordering and diffing. A known defect that is not fixed yet is a test wrapped in+-- @expectFailBecause@, named @known bug:@.+module Unit (tests) where++import Data.Aeson (FromJSON)+import Data.Aeson qualified as Aeson+import Data.String.Interpolate (i, __i)+import Data.Time (UTCTime (..), fromGregorian)+import Hedgehog (Gen, forAll, property, (===))+import Hedgehog.Gen qualified as Gen+import Hedgehog.Range qualified as Range+import RIO+import RIO.Directory (doesFileExist, listDirectory)+import RIO.FilePath ((</>))+import RIO.Map qualified as Map+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.App.Options (Comparison (..), MigrateOptions (..), Output (..), SameTypeSwap (..), TableFlags (..), TableMode (..), TableOptions (..), tableOptions)+import Sqiff.App.Table (forTable)+import Sqiff.App.Table.Rewrite (changesTableIn)+import Sqiff.Config (fill, match)+import Sqiff.ConnectionString (connectionString, fromPairs, libpqText, redacted)+import Sqiff.Definition hiding (columns)+import Sqiff.Dependencies (indexEdges, noDependencies)+import Sqiff.Diff (Change (..), affected, diff)+import Sqiff.Folder (Existing (..), exportManifest, writeFolder)+import Sqiff.Graph (schedule)+import Sqiff.Identifier (identifier, qname, quoteIdent, typeName)+import Sqiff.Model (Address (..), Aspect (..), Edge (..), ObjectId (..), ObjectKey (..), RoutineKind (..), fromAddress, toAddress)+import Sqiff.Plan (context, invert, topoOrder)+import Sqiff.Recipe (Hazard (..), Phase (..), Role (..), Step (..), Txn (..), Undo (..))+import Sqiff.Rewrite (fileDrift)+import Sqiff.Script (splitStatements, withoutCommitsInDoBlock, withoutTransactionControl)+import Sqiff.Sqitch.Check (Tagging (..), batchProblems, changeNameProblem, chooseTag, tagNameProblem)+import Sqiff.Sqitch.Layout (Layout (..), resolveLayout, sqitchConf)+import Sqiff.Sqitch.Plan (SqitchPlan (..), parsePlan)+import Sqiff.Sqitch.Units (Placement (..), Unit (..), UnitKind (..), renderScript, tidyIndex, units, verifyScript)+import Sqiff.Sql qualified as Sql+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (assertFailure, testCase, (@?=))+import Test.Tasty.Hedgehog (testProperty)+++tests :: TestTree+tests =+    testGroup+        "unit"+        [ quoting+        , sqlText+        , connections+        , addresses+        , templates+        , scripts+        , statementScanner+        , plans+        , ordering+        , diffing+        , columns+        , formatting+        , tableFlags+        , sqitchChecks+        , folderExport+        ]+++sqlText :: TestTree+sqlText =+    testGroup+        "SQL text"+        [ testCase "replaceInCode leaves literals, quoted names and comments alone"+            $ Sql.replaceInCode " WHERE " " where " "x WHERE y = ' WHERE ' -- WHERE \n and \" WHERE \" WHERE z"+            @?= "x where y = ' WHERE ' -- WHERE \n and \" WHERE \" where z"+        , testCase "replaceInCode leaves dollar-quoted bodies alone"+            $ Sql.replaceInCode "concurrently " "" "create index concurrently i on t (x) where f($$concurrently $$)"+            @?= "create index i on t (x) where f($$concurrently $$)"+        , testCase "dollarQuoted picks a tag the body lacks" do+            Sql.dollarQuoted "select 1" @?= "$$select 1$$"+            Sql.dollarQuoted "a $$ b" @?= "$sqiff$a $$ b$sqiff$"+            Sql.dollarQuoted "$$ $sqiff$" @?= "$sqiff1$$$ $sqiff$$sqiff1$"+        , testCase "a body ending in a dollar does not close the quote early"+            $ Sql.dollarQuoted "x$"+            @?= "$sqiff$x$$sqiff$"+        ]+++quoting :: TestTree+quoting =+    testGroup+        "quoteIdent"+        [ testCase "lower case stays bare" $ quoteIdent "payment_2" @?= "payment_2"+        , testCase "upper case is quoted" $ quoteIdent "Payment" @?= "\"Payment\""+        , testCase "reserved words are quoted" $ quoteIdent "user" @?= "\"user\""+        , testCase "unreserved keywords stay bare" $ quoteIdent "name" @?= "name"+        , testCase "a leading digit is quoted" $ quoteIdent "1a" @?= "\"1a\""+        , testCase "embedded quotes are doubled" $ quoteIdent "a\"b" @?= "\"a\"\"b\""+        , testCase "the empty name is quoted" $ quoteIdent "" @?= "\"\""+        ]+++connections :: TestTree+connections =+    testGroup+        "connection strings"+        [ testCase "keyword form"+            $ redacted (connectionString "host=h password=s3cret dbname=d")+            @?= "host=h password=*** dbname=d"+        , testCase "quoted keyword value"+            $ redacted (connectionString "password='a \\' b' host=h")+            @?= "password=*** host=h"+        , testCase "spaces around the equals sign"+            $ redacted (connectionString "host=h password = s3cret")+            @?= "host=h password=***"+        , testCase "a key that only ends in password stays"+            $ redacted (connectionString "host=h xpassword=x")+            @?= "host=h xpassword=x"+        , testCase "URI user info"+            $ redacted (connectionString "postgresql://me:s3cret@h:5432/d")+            @?= "postgresql://me:***@h:5432/d"+        , testCase "URI query parameter"+            $ redacted (connectionString "postgres://h/d?sslmode=require&password=s3cret")+            @?= "postgres://h/d?sslmode=require&password=***"+        , testCase "the empty string is libpq's environment"+            $ libpqText (connectionString "")+            @?= ""+        , testCase "fromPairs quotes values"+            $ libpqText (fromPairs [("host", "h"), ("password", "it's")])+            @?= "host='h' password='it\\'s'"+        , testCase "show never prints the password"+            $ T.isInfixOf "s3cret" (T.pack (show (fromPairs [("password", "s3cret")])))+            @?= False+        ]+++addresses :: TestTree+addresses =+    testGroup+        "catalog addresses"+        [ testProperty "toAddress inverts fromAddress" $ property do+            addr <- forAll address+            toAddress (fromAddress addr) === addr+        , testProperty "only unknown kinds stay unparsed" $ property do+            addr <- forAll address+            let parsed = fromAddress addr+                known = addr.objectType `elem` map fst kinds && shapeFits addr+            known === not (isUnknown parsed)+        , testCase "a column"+            $ fromAddress (Address "table column" ["s", "T", "c"] [])+            @?= Column (qname "s" "T") (identifier "c")+        , testCase "a function keeps its argument types"+            $ toAddress (fromAddress (Address "function" ["s", "f"] ["integer", "text"]))+            @?= Address "function" ["s", "f"] ["integer", "text"]+        ]+  where+    -- Each kind sqiff models, with how many names and arguments it has (Nothing: any).+    kinds :: [(Text, (Int, Maybe Int))]+    kinds =+        [ ("schema", (1, Just 0))+        , ("extension", (1, Just 0))+        , ("table", (2, Just 0))+        , ("view", (2, Just 0))+        , ("materialized view", (2, Just 0))+        , ("table column", (3, Just 0))+        , ("view column", (3, Just 0))+        , ("materialized view column", (3, Just 0))+        , ("composite type column", (3, Just 0))+        , ("foreign table column", (3, Just 0))+        , ("table constraint", (3, Just 0))+        , ("domain constraint", (1, Just 1))+        , ("index", (2, Just 0))+        , ("sequence", (2, Just 0))+        , ("type", (1, Just 0))+        , ("function", (2, Nothing))+        , ("procedure", (2, Nothing))+        , ("aggregate", (2, Nothing))+        , ("trigger", (3, Just 0))+        , ("policy", (3, Just 0))+        ]+    shapeFits addr = case lookup addr.objectType kinds of+        Just (names, args) -> length addr.objectNames == names && maybe True (== length addr.objectArgs) args+        Nothing -> False+    isUnknown = \case+        Unknown _ -> True+        _ -> False+    address :: Gen Address+    address = do+        kind <- Gen.choice [Gen.element (map fst kinds), Gen.element ["operator", "cast", "rule", "foreign table"]]+        names <- Gen.list (Range.linear 0 4) name+        args <- Gen.list (Range.linear 0 2) name+        pure (Address kind names args)+    name = Gen.text (Range.linear 0 6) (Gen.element ("aZ_.\" 1" :: String))+++templates :: TestTree+templates =+    testGroup+        "name templates"+        [ testCase "fill" $ fill "{schema}/table/{name}" [("schema", "s"), ("name", "t")] @?= "s/table/t"+        , testCase "match" $ match "{schema}/table/{name}" "s/table/t" @?= Just [("schema", "s"), ("name", "t")]+        , testCase "a placeholder does not span a slash" $ match "{schema}/table/{name}" "s/table/a/b" @?= Nothing+        , testCase "a placeholder is not empty" $ match "{schema}/table/{name}" "/table/t" @?= Nothing+        , testProperty "match inverts fill" $ property do+            pattern <- forAll (Gen.element ["{schema}/table/{name}", "{schema}/trigger/{table}/{name}", "{schema}/table/{table}/index/{name}"])+            let keys = placeholders pattern+            values <- forAll (traverse (\k -> (k,) <$> segment) keys)+            match pattern (fill pattern values) === Just values+        , testCase "a value is not expanded again"+            $ fill "{schema}/{name}" [("schema", "{name}"), ("name", "t")]+            @?= "{name}/t"+        ]+  where+    placeholders p = [T.takeWhile (/= '}') rest | rest <- drop 1 (T.split (== '{') p)]+    segment :: Gen Text+    -- [allow:SqiffInterpolate] a set of characters to draw from, not text+    segment = Gen.text (Range.linear 1 12) (Gen.element (['a' .. 'z'] <> ['0' .. '9'] <> "_-."))+++scripts :: TestTree+scripts =+    testGroup+        "scripts"+        [ testCase "splits on top-level semicolons"+            $ splitStatements "create table a (x int);\ncreate table b (y int);\n"+            @?= Right ["create table a (x int)", "create table b (y int)"]+        , testCase "keeps semicolons in quotes and comments"+            $ splitStatements "select ';' as \"a;b\"; -- c;\n/* d; */ select 1;"+            @?= Right ["select ';' as \"a;b\"", "-- c;\n/* d; */ select 1"]+        , testCase "keeps a dollar-quoted body whole"+            $ fmap length (splitStatements "create function f() returns int language plpgsql as $f$ begin return 1; end $f$;")+            @?= Right 1+        , testCase "keeps a BEGIN ATOMIC body whole"+            $ fmap length (splitStatements "create function f() returns int language sql begin atomic select 1; select 2; end;")+            @?= Right 1+        , testCase "an unclosed quote is an error"+            $ isLeft (splitStatements "select 'x")+            @?= True+        , testCase "a comment-only tail is no statement"+            $ splitStatements "select 1;\n-- the end\n"+            @?= Right ["select 1"]+        , testCase "drops transaction control"+            $ withoutTransactionControl ["begin", "create table a ()", "commit"]+            @?= Right ["create table a ()"]+        , testCase "keeps ROLLBACK TO"+            $ withoutTransactionControl ["rollback to sp"]+            @?= Right ["rollback to sp"]+        , testCase "refuses PREPARE TRANSACTION"+            $ isLeft (withoutTransactionControl ["prepare transaction 'x'"])+            @?= True+        , testCase "keeps ROLLBACK WORK TO"+            $ withoutTransactionControl ["rollback work to sp"]+            @?= Right ["rollback work to sp"]+        , testCase "leaves out the commits of a batched do block"+            $ withoutCommitsInDoBlock "do $$\nbegin\n  loop\n    update t set a = 1;\n    commit; -- between batches\n    exit;\n  end loop;\nend\n$$"+            @?= "do $$begin\n  loop\n    update t set a = 1;\n-- between batches\n    exit;\nend loop;\nend$$"+        , testCase "keeps a do block's tagged quote and what follows it"+            $ withoutCommitsInDoBlock "do language plpgsql $body$ begin perform 1; rollback; end $body$"+            @?= "do language plpgsql $body$begin perform 1;\nend$body$"+        , testCase "keeps commit in a string and in a nested IF"+            $ withoutCommitsInDoBlock "do $$ begin raise notice 'commit'; if true then commit; end if; end $$"+            @?= "do $$begin raise notice 'commit';\nif true then commit;\nend if;\nend$$"+        , testCase "leaves statements that are not do blocks alone"+            $ withoutCommitsInDoBlock "create function f() returns void language plpgsql as $$ begin commit; end $$"+            @?= "create function f() returns void language plpgsql as $$ begin commit; end $$"+        ]+++-- | Exact outputs of 'splitStatements' for each construct its scanner tracks.+statementScanner :: TestTree+statementScanner =+    testGroup+        "statement scanner"+        [ testCase "a nested block comment closes at its outer end"+            $ splitStatements "select 1 /* a /* b; */ c; */; select 2;"+            @?= Right ["select 1 /* a /* b; */ c; */", "select 2"]+        , testCase "a dollar quote closes only at its own tag"+            $ splitStatements "do $f$ begin perform $$;$$; end $f$; select $a$x;$a$;"+            @?= Right ["do $f$ begin perform $$;$$; end $f$", "select $a$x;$a$"]+        , testCase "a positional parameter and a dollar inside a name are no dollar quote"+            $ splitStatements "select a$b$c, $1; select 2"+            @?= Right ["select a$b$c, $1", "select 2"]+        , testCase "an escape string keeps backslash-escaped and doubled quotes"+            $ splitStatements "select E'a\\';b', e'c'';d'; select 2;"+            @?= Right ["select E'a\\';b', e'c'';d'", "select 2"]+        , testCase "a backslash ends a standard string"+            $ splitStatements "select 'a\\'; select 2;"+            @?= Right ["select 'a\\'", "select 2"]+        , testCase "doubled quotes stay inside a string and a quoted name"+            $ splitStatements "select 'a'';b' as \"c\"\";d\"; select 2;"+            @?= Right ["select 'a'';b' as \"c\"\";d\"", "select 2"]+        , testCase "a BEGIN ATOMIC body ends at its END, past CASE ... END"+            $ splitStatements "create function f() returns int language sql BEGIN ATOMIC select case when true then 1 end; end; select 2;"+            @?= Right ["create function f() returns int language sql BEGIN ATOMIC select case when true then 1 end; end", "select 2"]+        , testCase "CASE ... END outside BEGIN ATOMIC does not hold the statement open"+            $ splitStatements "select case when true then 1 end; select 2;"+            @?= Right ["select case when true then 1 end", "select 2"]+        , testCase "a comment between BEGIN and ATOMIC still starts a body"+            $ splitStatements "begin/**/atomic select 1; end; select 2;"+            @?= Right ["begin/**/atomic select 1; end", "select 2"]+        , testCase "a quote between BEGIN and ATOMIC starts no body"+            $ splitStatements "begin 'x' atomic; select 2;"+            @?= Right ["begin 'x' atomic", "select 2"]+        , testCase "psql output commands are skipped"+            $ splitStatements "\\set ON_ERROR_STOP on\n\\pset pager off\n\\unset QUIET\nselect 1;"+            @?= Right ["select 1"]+        , testCase "a quote in a skipped psql command opens no string"+            $ splitStatements "\\echo it's done\nselect 1; select 2;"+            @?= Right ["select 1", "select 2"]+        , testCase "each statement is a slice of the script"+            $ splitStatements "-- setup\n\\set QUIET on\n-- the table\ncreate table a ();"+            @?= Right ["-- the table\ncreate table a ()"]+        , testCase "other psql commands are refused"+            $ splitStatements "\\i other.sql\nselect 1;"+            @?= Left "psql's \\i cannot run outside psql"+        , testCase "\\set of a lowercase variable is refused"+            $ splitStatements "\\set foo bar\nselect 1;"+            @?= Left "psql's \\set cannot run outside psql"+        , testCase "a backslash after code is part of the statement"+            $ splitStatements "select 1 \\x\n;"+            @?= Right ["select 1 \\x"]+        , testCase "an unterminated last statement is kept"+            $ splitStatements "select 1; select 2 -- done"+            @?= Right ["select 1", "select 2 -- done"]+        , testCase "an unclosed dollar quote is an error"+            $ splitStatements "select $$x;"+            @?= Left "a quote, dollar quote or comment is not closed"+        , testCase "an unclosed nested comment is an error"+            $ splitStatements "select 1; /* a /* b */"+            @?= Left "a quote, dollar quote or comment is not closed"+        , testCase "an unclosed escape string is an error"+            $ splitStatements "select E'a\\'"+            @?= Left "a quote, dollar quote or comment is not closed"+        , testCase "a BEGIN ATOMIC body without END is an error"+            $ splitStatements "create function f() returns int language sql begin atomic select 1;"+            @?= Left "a BEGIN ATOMIC body has no END"+        , testCase "a BEGIN ATOMIC body whose END ends the input is closed"+            $ splitStatements "create function f() returns int language sql begin atomic select 1; end"+            @?= Right ["create function f() returns int language sql begin atomic select 1; end"]+        ]+++plans :: TestTree+plans =+    testGroup+        "sqitch plan"+        [ testCase "reads the project, changes and tags" do+            let p =+                    parsePlan+                        [__i|+                            %syntax-version=1.0.0+                            %project=demo++                            a 2024-01-01T00:00:00Z Me <me@example.com> \# first+                            b [a] 2024-01-02T00:00:00Z Me <me@example.com> \# second+                            @v1 2024-01-03T00:00:00Z Me <me@example.com> \# tag+                            c 2024-01-04T00:00:00Z Me <me@example.com> \# third\n+                        |]+            p.project @?= "demo"+            p.changes @?= ["a", "b", "c"]+            p.tagged @?= Set.fromList ["a", "b"]+        , testCase "a reworked change is tagged only if its last entry is" do+            let p =+                    parsePlan+                        [__i|+                            %project=demo+                            a x+                            @v1 x+                            a x\n+                        |]+            p.changes @?= ["a", "a"]+            p.tagged @?= Set.empty+        ]+++ordering :: TestTree+ordering =+    testGroup+        "topoOrder"+        [ testCase "puts a node after what it needs"+            $ topoOrder (Set.fromList "abc") [('a', 'b'), ('b', 'c')]+            @?= "cba"+        , testCase "breaks ties by the smaller node"+            $ topoOrder (Set.fromList "cab") []+            @?= "abc"+        , testCase "ignores pairs outside the nodes"+            $ topoOrder (Set.fromList "ab") [('a', 'z')]+            @?= "ab"+        , testCase "puts cyclic nodes last"+            $ topoOrder (Set.fromList "abc") [('a', 'b'), ('b', 'a')]+            @?= "cab"+        , testCase "schedule takes the smallest priority among the ready"+            $ scheduleChars [(2, 'a'), (1, 'b'), (3, 'c')] []+            @?= Right "bac"+        , testCase "schedule lets a constraint beat priority"+            $ scheduleChars [(1, 'f'), (2, 'v')] [('f', 'v')]+            @?= Right "vf"+        , testCase "schedule reports what a cycle blocks"+            $ scheduleChars [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] [('a', 'b'), ('b', 'a'), ('d', 'a')]+            @?= Left ("c", "abd")+        , testProperty "every pair is respected in an acyclic graph" $ property do+            n <- forAll (Gen.int (Range.linear 1 30))+            pairs <- forAll (Gen.list (Range.linear 0 60) ((,) <$> Gen.int (Range.linear 0 (n - 1)) <*> Gen.int (Range.linear 0 (n - 1))))+            -- Only pairs from a higher node to a lower one, which cannot form a cycle.+            let acyclic = [(x, y) | (x, y) <- pairs, x > y]+                order = topoOrder (Set.fromList [0 .. n - 1]) acyclic+                position = Map.fromList (zip order [0 :: Int ..])+            length order === n+            [(x, y) | (x, y) <- acyclic, Map.lookup x position < Map.lookup y position] === []+        ]+++diffing :: TestTree+diffing =+    testGroup+        "diff"+        [ testCase "finds added, dropped and changed definitions"+            $ diff (\_ a b -> a == b) (Map.fromList [(k "a", "1"), (k "b", "2"), (k "c", "3") :: (ObjectKey, Text)]) (Map.fromList [(k "b", "2"), (k "c", "4"), (k "d", "5")])+            @?= Map.fromList [(k "a", Dropped "1"), (k "c", Changed "3" "4"), (k "d", Added "5")]+        , testCase "a dependent whose comment changes still depends" do+            let column = Column (qname "public" "t") (identifier "a")+                v = View (qname "public" "v")+                changes = Map.fromList [(ObjectKey Definition column, Changed "int" "bigint"), (ObjectKey Comment v, Changed "old" "new" :: Change Text)]+            affected (Set.fromList [column, v]) (indexEdges [Edge v column]) changes @?= Map.fromList [(column, Set.singleton v)]+        , testCase "the sameness test can hide a change"+            $ diff (\_ _ _ -> True) (Map.fromList [(k "a", "1") :: (ObjectKey, Text)]) (Map.fromList [(k "a", "2")])+            @?= Map.empty+        , testProperty "invert is an involution" $ property do+            c <- forAll (Gen.choice [Added <$> txt, Dropped <$> txt, Changed <$> txt <*> txt])+            invert (invert c) === c+        ]+  where+    k n = ObjectKey Definition (fromAddress (Address "table" ["public", n] []))+    txt = Gen.text (Range.linear 0 5) Gen.alpha+++columns :: TestTree+columns =+    testGroup+        "definitions"+        [ testCase "a column decodes and prints as before" do+            c <- decode @ColumnDef "{\"type\": \"integer\", \"collation\": \"C\", \"not_null\": {\"validated\": true, \"name\": \"x_nn\"}, \"expression\": \"42\"}"+            printed (ColumnDefinition c)+                @?= [__i|+                    type integer+                    collate "C"+                    not null constraint x_nn+                    default 42+                |]+        , testCase "NOT VALID, identity and its options" do+            c <- decode @ColumnDef "{\"type\": \"bigint\", \"not_null\": {\"validated\": false}, \"identity\": \"by default\", \"identity_options\": [\"increment by 5\"]}"+            c.nullability @?= NotNull NotValidated Nothing+            c.value @?= IdentityColumn ByDefault ["increment by 5"]+            printed (ColumnDefinition c) @?= "type bigint\nnot null not valid\nidentity by default\nidentity options increment by 5"+        , testCase "a generated column" do+            c <- decode @ColumnDef "{\"type\": \"int\", \"generated\": \"stored\", \"expression\": \"(a + 1)\"}"+            c.value @?= GeneratedColumn Stored "(a + 1)"+        , testCase "a multi-line default stays whole" do+            c <- decode @ColumnDef "{\"type\": \"text\", \"expression\": \"'a\\ntype b'::text\"}"+            c.colType @?= typeName "text"+            c.value @?= PlainColumn (Just "'a\ntype b'::text")+        , testCase "identity and generated together are refused"+            $ isLeft (Aeson.eitherDecodeStrict @ColumnDef "{\"type\": \"int\", \"identity\": \"always\", \"generated\": \"stored\", \"expression\": \"1\"}")+            @?= True+        , testCase "a role name with a space stays whole" do+            acl <- decode @Acl "[{\"grantee\": \"report readers\", \"privilege\": \"SELECT\", \"grantable\": false}, {\"grantee\": null, \"privilege\": \"USAGE\", \"grantable\": true}]"+            acl @?= ExplicitAcl (Set.fromList [Grant (Role (identifier "report readers")) "SELECT" False ByOwner, Grant Public "USAGE" True ByOwner])+            printed (AclDefinition acl) @?= "public USAGE with grant option\nreport readers SELECT"+        , testCase "drift ignores validity but not the words \"not valid\" in a comment" do+            let key o = ObjectKey Comment o+                table = Table (qname "public" "t")+                column validity = ColumnDefinition (plainColumn "int"){nullability = NotNull validity Nothing}+                columnKey = ObjectKey Definition (Column (qname "public" "t") (identifier "c"))+            Map.keys (fileDrift Set.empty (Map.fromList [(key table, Printed "is not valid")]) (Map.fromList [(key table, Printed "is")])) @?= [key table]+            fileDrift Set.empty (Map.fromList [(columnKey, column NotValidated)]) (Map.fromList [(columnKey, column Validated)]) @?= Map.empty+        , testCase "a foreign key knows its columns and target" do+            c <- decode @ConstraintDef "{\"kind\": \"f\", \"validated\": false, \"columns\": [\"Parent Id\"], \"references\": {\"schema\": \"a.b\", \"table\": \"t\", \"columns\": [\"id\"]}, \"clause\": \"FOREIGN KEY (\\\"Parent Id\\\") REFERENCES \\\"a.b\\\".t(id) NOT VALID\"}"+            c.kind @?= ForeignKey+            fmap (.table) c.references @?= Just (qname "a.b" "t")+            withoutValidity c @?= c{validity = Validated, clause = "FOREIGN KEY (\"Parent Id\") REFERENCES \"a.b\".t(id)"}+        , testCase "a table's settings print one per line" do+            t <- decode @TableDef "{\"unlogged\": true, \"partition_by\": \"RANGE (at)\", \"row_security\": true, \"force_row_security\": false, \"options\": [\"fillfactor=70\", \"toast.autovacuum_enabled=false\"]}"+            tableText t @?= "unlogged\npartition by RANGE (at)\nrow level security\nwith (fillfactor=70, toast.autovacuum_enabled=false)"+        , testCase "literal matches quote_literal" do+            Sql.literal "it's" @?= "'it''s'"+            Sql.literal "a\\, b" @?= "E'a\\\\, b'"+        , testCase "no ACL is the default, an empty one is not" do+            decode "null" >>= (@?= DefaultAcl)+            decode "[]" >>= (@?= ExplicitAcl Set.empty)+        ]+  where+    decode :: FromJSON a => ByteString -> IO a+    decode = either (assertFailure . ("does not decode: " <>)) pure . Aeson.eitherDecodeStrict+++formatting :: TestTree+formatting =+    testGroup+        "tidyIndex"+        [ testCase "lowers keywords and drops USING btree"+            $ tidyIndex "CREATE INDEX t_x ON public.t USING btree (x) WHERE (x > 0)"+            @?= "create index t_x on public.t (x) where (x > 0)"+        , testCase "keeps a non-default method"+            $ tidyIndex "CREATE INDEX t_x ON public.t USING gin (x)"+            @?= "create index t_x on public.t using gin (x)"+        , testCase "leaves string literals alone"+            $ tidyIndex "CREATE INDEX t_x ON public.t USING btree (x) WHERE (y <> ' WHERE ')"+            @?= "create index t_x on public.t (x) where (y <> ' WHERE ')"+        ]+++tableFlags :: TestTree+tableFlags =+    testGroup+        "table options"+        [ testCase "the file comparison by default, with its renames"+            $ describeMode (tableOptions flags{renames = [rename]})+            @?= Right "base file, 1 renames, ask if rename"+        , testCase "--against-database with --allow-drops"+            $ describeMode (tableOptions flags{againstDatabase = True, allowDrops = True})+            @?= Right "live table"+        , testCase "--rewrite-file with --live-from"+            $ describeMode (tableOptions flags{rewriteFile = True, liveFrom = Just (connectionString "dbname=live")})+            @?= Right "rewrite from dbname=live"+        , testCase "refuses flags that do not apply together" do+            let refused f = either (const True) (const False) (tableOptions f)+            for_+                [ flags{rewriteFile = True, renames = [rename]}+                , flags{rewriteFile = True, againstDatabase = True}+                , flags{rewriteFile = True, allowDrops = True}+                , flags{rewriteFile = True, dropAndAdd = True}+                , flags{againstDatabase = True, renames = [rename]}+                , flags{liveFrom = Just (connectionString "dbname=live")}+                , flags{allowDrops = True}+                ]+                \f -> refused f @?= True+        ]+  where+    rename = (identifier "a", identifier "b")+    flags =+        TableFlags+            { output = PrintMigration+            , againstDatabase = False+            , allowDrops = False+            , base = "master"+            , project = "."+            , top = Nothing+            , planPath = Nothing+            , tableTag = Nothing+            , renames = []+            , dropAndAdd = False+            , rewriteFile = False+            , liveFrom = Nothing+            }+    describeMode :: Either Text TableOptions -> Either Text Text+    describeMode = fmap \o -> case o.mode of+        MigrateToFile m ->+            let swap = if m.sameTypeSwap == AskIfRename then "ask if rename" else "drop and add" :: Text+             in case m.comparison of+                    WithBaseFile rs -> [i|base file, #{tshow (length rs)} renames, #{swap}|]+                    WithLiveTable _ -> "live table"+        RewriteFile live -> "rewrite from " <> maybe "--db" redacted live+++sqitchChecks :: TestTree+sqitchChecks =+    testGroup+        "sqitch checks"+        [ testCase "change names sqitch and the file system accept" do+            for_ ["public/function/f", "migrations/2026/11/2026-11-18-120000-add-x", "_x", "v1.2+1"] \n ->+                changeNameProblem n @?= Nothing+        , testCase "change names they refuse" do+            for_ ["", "a b", "a:b", "a@b", "a#b", "a\\b", "-a", "a.", "a^2", "a~12", "/abs", "a/../b", "a//b", "./a"] \n ->+                isJust (changeNameProblem n) @?= True+        , testCase "tags cannot have a slash" do+            isJust (tagNameProblem "a/b") @?= True+            tagNameProblem "2026-11-18_sqiff" @?= Nothing+        , testCase "the day's tag, or the next free one" do+            let at = Tagging{given = Nothing, now = UTCTime (fromGregorian 2026 11 18) 0}+            chooseTag (plan "") at @?= Right "2026-11-18_sqiff"+            chooseTag (plan "a 2026-01-01T00:00:00Z x <x@x> # a\n@2026-11-18_sqiff 2026-01-01T00:00:00Z x <x@x> # t\n") at @?= Right "2026-11-18_sqiff_2"+        , testCase "a given tag must be new" do+            let at = Tagging{given = Just "v1", now = UTCTime (fromGregorian 2026 11 18) 0}+            isLeft (chooseTag (plan "a 2026-01-01T00:00:00Z x <x@x> # a\n@v1 2026-01-01T00:00:00Z x <x@x> # t\n") at) @?= True+            chooseTag (plan "") at @?= Right "v1"+        , testCase "the plan's tags" do+            (plan "a 2026-01-01T00:00:00Z x <x@x> # a\n@v1 2026-01-01T00:00:00Z x <x@x> # t\nb [a] 2026-01-01T00:00:00Z x <x@x> # b\n@v2 2026-01-01T00:00:00Z x <x@x> # t\n").tags+                @?= Set.fromList ["v1", "v2"]+        , testCase "a batch with a collision, an existing add or a rework of nothing" do+            let p = plan "a 2026-01-01T00:00:00Z x <x@x> # a\n"+            length (batchProblems p [unitNamed AddChange "b", unitNamed AddChange "b"]) @?= 1+            length (batchProblems p [unitNamed AddChange "a"]) @?= 1+            length (batchProblems p [unitNamed ReworkChange "c"]) @?= 1+            batchProblems p [unitNamed ReworkChange "a", unitNamed AddChange "b"] @?= []+        , testCase "a column's position does not make it differ" do+            let at n = ColumnDefinition (plainColumn "int"){position = Position n}+                key = ObjectKey Definition (Column (qname "public" "t") (identifier "a"))+            diff (\_ a b -> a == b) (Map.fromList [(key, at 1)]) (Map.fromList [(key, at 3)]) @?= Map.empty+        , testCase "verify checks a column's full type, not only its base type" do+            let col ty = ColumnDefinition (plainColumn ty)+                object = Column (qname "public" "t") (identifier "a")+                retype =+                    (createStep object "alter table public.t alter column a type character varying(20)")+                        { rank = 6+                        , change = Changed (col "character varying(10)") (col "character varying(20)")+                        }+                script = verifyScript "-- verify" [retype]+            ("format_type(atttypid, atttypmod)" `T.isInfixOf` script, "= 'character varying(20)'" `T.isInfixOf` script) @?= (True, True)+        , testCase "verify checks routines, types, schemas and extensions" do+            let made object = (createStep object "create"){rank = 1, change = Added (Printed "x")}+                script = verifyScript "-- verify" (map made [Routine Function (qname "app" "f") [typeName "integer"], Type (typeName "app.mood"), Schema (identifier "app"), Extension (identifier "pgcrypto"), Table (qname "app" "t")])+            for_ ["to_regprocedure('app.f(integer)') is not null", "to_regtype('app.mood') is not null", "nspname = 'app'", "extname = 'pgcrypto'", "to_regclass('app.t') is not null"] \check ->+                (check, check `T.isInfixOf` script) @?= (check, True)+        , testCase "verify does not expect an object dropped to be created again to be gone" do+            let object = MaterializedView (qname "app" "mv")+                drop' =+                    (createStep object "drop materialized view app.mv")+                        { phase = DropPhase+                        , role = Drops+                        , rank = 1+                        , change = Changed (Printed "a") (Printed "b")+                        }+            ("still exists" `T.isInfixOf` verifyScript "-- verify" [drop']) @?= False+        , testCase "a step sqiff cannot write stops the deploy" do+            let object = Type (typeName "app.mood")+                manual =+                    (createStep object "-- only adding enum values is automated")+                        { rank = 8+                        , hazards = [Manual "only adding enum values is automated"]+                        , change = Changed (Printed "a") (Printed "b")+                        }+            ("raise exception" `T.isInfixOf` renderScript "-- deploy" Migration [manual]) @?= True+        , testCase "a table's migrations are found by its name as migration names write it" do+            let names = either error id (Aeson.eitherDecode "{}")+                ours = forTable names (qname "App" "Big Orders")+            ours "migrations/2026/11/2026-11-18-120000-add-column-app.big-orders.total" @?= True+            ours "migrations/2026/11/2026-11-18-120000-add-column-app.big-ordersx" @?= False+            ours "App/table/Big Orders/index/total_idx" @?= True+        , testCase "which statements change a table" do+            let changes = changesTableIn (qname "app" "orders")+            for_+                [ "alter table app.orders add column x int"+                , "ALTER TABLE IF EXISTS ONLY app.orders drop column x"+                , "drop table if exists app.other, app.orders cascade"+                , "drop table orders"+                , "alter table \"app\".\"orders\" add column y int"+                , "grant select on table app.orders to reader"+                , "revoke all on app.orders from reader"+                , "comment on column app.orders.total is 'x'"+                , "create index orders_total on app.orders (total)"+                , "create table if not exists app.orders (id int)"+                , "do $ begin perform 1 from app.orders; end $"+                ]+                \statement -> (statement, changes statement) @?= (statement, True)+            for_+                [ "alter table app.orders_archive add column x int"+                , "drop table other.orders"+                , "create view app.v as select * from app.orders"+                , "grant select on app.order_lines to reader"+                , "do $ begin perform 1 from app.orders_archive; end $"+                ]+                \statement -> (statement, changes statement) @?= (statement, False)+        , testCase "words and lists keep quoted names whole" do+            Sql.codeWords "()," "\"a, b\" int unique, -- note\n c text" @?= ["\"a, b\"", "int", "unique", "c", "text"]+            Sql.parenthesised "unique (\"a)\", (b)) x" @?= Just "\"a)\", (b)"+            Sql.splitTopLevel ',' "\"a, b\", f(c, d), 'e,f'" @?= ["\"a, b\"", "f(c, d)", "'e,f'"]+        , testCase "overloads of a new function make one change" do+            let names = either error id (Aeson.eitherDecode "{}")+                ctx = context Map.empty Map.empty Map.empty noDependencies Map.empty+                overload arg =+                    let object = Routine Function (qname "public" "f") [typeName arg]+                     in (createStep object [i|create function public.f(#{arg})|]){rank = 9, change = Added (Printed arg)}+                written = units names (const True) ctx Map.empty (plan "") (UTCTime (fromGregorian 2026 11 18) 0) [overload "int", overload "text"]+            map (\u -> (u.changeName, length u.deploy)) written @?= [("public/function/f", 2)]+        , testCase "the layout: the target's setting beats the engine's, which beats the core's" do+            let merged =+                    [ ("core.engine", "pg")+                    , ("core.top_dir", "core")+                    , ("engine.pg.top_dir", "engine")+                    , ("engine.pg.target", "prod")+                    , ("target.prod.deploy_dir", "elsewhere/deploy")+                    ]+            l <- either (assertFailure . T.unpack) pure (resolveLayout "/p" Nothing Nothing merged [])+            (l.topDir, l.planFile, l.deployDir, l.revertDir, l.extension) @?= ("engine", "engine/sqitch.plan", "elsewhere/deploy", "engine/revert", "sql")+        , testCase "the layout: --top-dir moves the scripts and the plan" do+            l <- either (assertFailure . T.unpack) pure (resolveLayout "/p" (Just "alt") Nothing [("core.top_dir", "db"), ("core.deploy_dir", "db/d")] [])+            (l.topDir, l.planFile, l.deployDir) @?= ("alt", "alt/sqitch.plan", "alt/deploy")+        , testCase "sqitch runs with the layout pinned for the core, the engine and the target" do+            let settings = [("core.engine", "pg"), ("core.top_dir", "db"), ("engine.pg.target", "prod"), ("target.prod.uri", "db:pg://h/x")]+            l <- either (assertFailure . T.unpack) pure (resolveLayout "/p" (Just "alt") Nothing settings settings)+            let conf = sqitchConf l+            for_ ["[core]", "[engine \"pg\"]", "[target \"prod\"]", "\ttop_dir = \"alt\"", "\turi = \"db:pg://h/x\""] \line ->+                (line, line `T.isInfixOf` conf) @?= (line, True)+            ("top_dir = \"db\"" `T.isInfixOf` conf) @?= False+        , testCase "a rework copies the scripts next to them, not under top_dir twice" do+            l <- either (assertFailure . T.unpack) pure (resolveLayout "/p" Nothing Nothing [("core.engine", "pg"), ("core.top_dir", "database")] [])+            let conf = sqitchConf l+            for_ ["\treworked_deploy_dir = \"database/deploy\"", "\treworked_revert_dir = \"database/revert\"", "\treworked_verify_dir = \"database/verify\""] \line ->+                (line, line `T.isInfixOf` conf) @?= (line, True)+        ]+  where+    plan entries = parsePlan ("%syntax-version=1.0.0\n%project=p\n\n" <> entries)+    unitNamed kind changeName = Unit{kind, changeName, note = "", placement = Migration, deploy = [], revert = []}+++folderExport :: TestTree+folderExport =+    testGroup+        "describe --out"+        [ testCase "names that differ give files that differ" do+            let paths = Map.keys (exportManifest (Map.fromList [(table n, Printed n) | n <- ["a b", "a-b", "a/b", "a%2Fb", ".a", "%2Ea"]]))+            length paths @?= 6+        , testCase "names that differ only in case get a hash, as some file systems fold case" do+            let paths = Map.keys (exportManifest (Map.fromList [(table n, Printed n) | n <- ["Orders", "orders", "other"]]))+                folded = Set.fromList (map (T.toLower . T.pack) paths)+            (length paths, Set.size folded) @?= (3, 3)+            ("table/public/other.sql" `elem` paths) @?= True+        , testCase "a kind of two words is a folder with a dash" do+            let paths = Map.keys (exportManifest (Map.fromList [(ObjectKey Definition (Column (qname "public" "orders") (identifier "amount")), Printed "integer")]))+            paths @?= ["table-column/public/orders/amount.sql"]+        , testCase "an empty schema writes the folder and its marker" do+            withSystemTempDirectory "sqiff-folder" \dir -> do+                writeFolder KeepExisting (dir </> "out") Map.empty+                doesFileExist (dir </> "out" </> ".sqiff") >>= (@?= True)+        , testCase "--replace swaps in the new export, and keeps the old one when writing fails" do+            withSystemTempDirectory "sqiff-folder" \dir -> do+                let out = dir </> "out"+                writeFolder KeepExisting out (Map.fromList [(table "old", Printed "old")])+                writeFolder ReplaceOwn out (Map.fromList [(table "new", Printed "new")])+                listDirectory (out </> "table" </> "public") >>= (@?= ["new.sql"])+                -- The staging folder cannot be made where a file of its name is.+                writeFileUtf8 (out <> ".sqiff-staging") "in the way"+                result <- tryAny (writeFolder ReplaceOwn out (Map.fromList [(table "newer", Printed "newer")]))+                isLeft result @?= True+                listDirectory (out </> "table" </> "public") >>= (@?= ["new.sql"])+        ]+  where+    table n = ObjectKey Definition (Table (qname "public" n))+++-- | 'schedule' over characters keyed by themselves, with the priorities given.+scheduleChars :: [(Int, Char)] -> [(Char, Char)] -> Either (String, String) String+scheduleChars items pairs = bimap (bimap (map snd) (map snd)) (map snd) (schedule snd fst items pairs)+++-- | A shared create-phase step that creates @object@ with @sql@ and is undone by its+-- inverse; tests change the fields they are about.+createStep :: ObjectId -> Text -> Step+createStep object sql =+    Step+        { phase = CreatePhase+        , role = Creates+        , rank = 0+        , object+        , sql+        , txn = Shared+        , hazards = []+        , key = ObjectKey Definition object+        , change = Added (Printed sql)+        , undo = UndoObject+        }+++-- | A nullable column of type @ty@, first in its table, with nothing else set.+plainColumn :: Text -> ColumnDef+plainColumn ty =+    ColumnDef+        { colType = typeName ty+        , collation = Nothing+        , nullability = Nullable+        , value = PlainColumn Nothing+        , rewritesOnAdd = False+        , position = Position 1+        , inheritedOnly = False+        }
+ test/Writing.hs view
@@ -0,0 +1,172 @@+{-# LANGUAGE DisambiguateRecordFields #-}+{-# LANGUAGE OverloadedRecordDot #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoImplicitPrelude #-}++-- | Writing changes with the real sqitch, in throwaway projects: the layout sqiff+-- resolves is the one sqitch writes to, a failure part-way leaves the project as it was,+-- and a rework on a day that already has sqiff's tag gets a new one.+module Writing (setUpSqitch, tests) where++import Data.String.Interpolate (i)+import Data.Time (UTCTime (..), fromGregorian)+import RIO+import RIO.Directory (createDirectoryIfMissing, doesFileExist, findExecutable, getPermissions, setOwnerWritable, setPermissions)+import RIO.FilePath ((</>))+import RIO.List (sort)+import RIO.Set qualified as Set+import RIO.Text qualified as T+import Sqiff.Connection (UserError (..))+import Sqiff.Definition (Definition (..))+import Sqiff.Diff (Change (..))+import Sqiff.Identifier (qname)+import Sqiff.Model (Aspect (..), ObjectId (..), ObjectKey (..))+import Sqiff.Recipe (Phase (..), Role (..), Step (..), Txn (..), Undo (..))+import Sqiff.Sqitch (withProject, writeUnits)+import Sqiff.Sqitch.Check (Tagging (..))+import Sqiff.Sqitch.Layout (findLayout)+import Sqiff.Sqitch.Plan (SqitchPlan (..), readPlan)+import Sqiff.Sqitch.Units (Placement (..), Unit (..), UnitKind (..))+import System.Environment (lookupEnv, setEnv)+import System.Process.Typed (proc, readProcess, readProcess_, setWorkingDir)+import Test.Tasty (TestTree, testGroup)+import Test.Tasty.HUnit (Assertion, assertBool, assertFailure, testCase, (@?=))+++-- | Puts SQIFF_TEST_SQITCH_BIN on PATH and gives sqitch an identity and no user+-- configuration; whether sqitch is then available.+setUpSqitch :: IO Bool+setUpSqitch = do+    lookupEnv "SQIFF_TEST_SQITCH_BIN" >>= traverse_ \bin -> do+        path <- fromMaybe "" <$> lookupEnv "PATH"+        setEnv "PATH" [i|#{bin}:#{path}|]+    setEnv "SQITCH_USER_CONFIG" "/nonexistent/sqiff-test/sqitch.conf"+    setEnv "SQITCH_FULLNAME" "sqiff test"+    setEnv "SQITCH_EMAIL" "sqiff@example.invalid"+    isJust <$> findExecutable "sqitch"+++tests :: Bool -> TestTree+tests available =+    testGroup "sqitch writing"+        $ if not available+            then [testCase "sqitch is available" (assertFailure "sqitch is neither on PATH nor in SQIFF_TEST_SQITCH_BIN")]+            else+                [ testCase "writes where --top-dir and --plan-file say, not where sqitch.conf does" customLayout+                , testCase "a failure part-way leaves the plan and the scripts as they were" rollsBack+                , testCase "a second rework on the same day gets a new tag" secondTag+                , testCase "a batch that would collide writes nothing" refusesCollisions+                ]+++-- | A new sqitch project whose sqitch.conf puts everything under @db@.+withSqitchProject :: (FilePath -> IO a) -> IO a+withSqitchProject action = withSystemTempDirectory "sqiff-writing" \dir -> do+    let root = dir </> "project"+    createDirectoryIfMissing True root+    void (readProcess_ (setWorkingDir root (proc "sqitch" ["init", "proj", "--engine", "pg", "--top-dir", "db"])))+    action root+++step :: Text -> Text -> Step+step name sql =+    let object = Table (qname "public" name)+     in Step+            { phase = CreatePhase+            , role = Creates+            , rank = 4+            , object+            , sql+            , txn = Shared+            , hazards = []+            , key = ObjectKey Definition object+            , change = Added (Printed sql)+            , undo = UndoObject+            }+++unit :: UnitKind -> Text -> Text -> Unit+unit kind changeName sql = Unit{kind, changeName, note = "sqiff: test", placement = Migration, deploy = [step changeName sql], revert = []}+++tagging :: Tagging+tagging = Tagging{given = Nothing, now = UTCTime (fromGregorian 2026 11 18) 0}+++-- | Every file under @dir@, relative to it.+filesIn :: FilePath -> IO [FilePath]+filesIn dir = do+    (_, out, _) <- readProcess (setWorkingDir dir (proc "find" [".", "-type", "f"]))+    pure (sort (lines (T.unpack (decodeUtf8Lenient (toStrictBytes out)))))+++customLayout :: Assertion+customLayout = withSqitchProject \root -> do+    createDirectoryIfMissing True (root </> "alt")+    writeFileUtf8 (root </> "alt/other.plan") "%syntax-version=1.0.0\n%project=proj\n\n"+    layout <- findLayout root (Just "alt") (Just "alt/other.plan")+    plan <- readPlan (root </> "alt/other.plan")+    withProject layout \project -> writeUnits project Nothing plan tagging [unit AddChange "one" "create table public.one ()"]+    deploy <- readFileUtf8 (root </> "alt/deploy/one.sql")+    assertBool "the deploy script has the statement" ("create table public.one ()" `T.isInfixOf` deploy)+    after <- readPlan (root </> "alt/other.plan")+    after.changes @?= ["one"]+    defaultPlan <- readPlan (root </> "db/sqitch.plan")+    defaultPlan.changes @?= []+    exists <- doesFileExist (root </> "db/deploy/one.sql")+    exists @?= False+++rollsBack :: Assertion+rollsBack = withSqitchProject \root -> do+    -- sqitch cannot write the second change's deploy script into a read-only directory.+    let planFile = root </> "db/sqitch.plan"+        readOnly = root </> "db/deploy/locked"+    createDirectoryIfMissing True readOnly+    setPermissions readOnly . setOwnerWritable False =<< getPermissions readOnly+    before <- (,) <$> readFileUtf8 planFile <*> filesIn root+    layout <- findLayout root Nothing Nothing+    plan <- readPlan planFile+    result <- try (withProject layout \project -> writeUnits project Nothing plan tagging [unit AddChange "one" "create table public.one ()", unit AddChange "locked/two" "create table public.two ()"])+    case result of+        Left (UserError message) -> assertBool (T.unpack message) ("nothing was written" `T.isInfixOf` message)+        Right () -> assertFailure "writing into a read-only directory succeeded"+    after <- (,) <$> readFileUtf8 planFile <*> filesIn root+    after @?= before+++secondTag :: Assertion+secondTag = withSqitchProject \root -> do+    let planFile = root </> "db/sqitch.plan"+    layout <- findLayout root Nothing Nothing+    let write units = do+            plan <- readPlan planFile+            withProject layout \project -> writeUnits project Nothing plan tagging units+    write [unit AddChange "one" "create table public.one ()"]+    write [unit ReworkChange "one" "create table public.one (a int)"]+    write [unit ReworkChange "one" "create table public.one (a int, b int)"]+    plan <- readPlan planFile+    plan.tags @?= Set.fromList ["2026-11-18_sqiff", "2026-11-18_sqiff_2"]+    snapshots <- for ["deploy", "revert", "verify"] \d -> (d,) <$> doesFileExist (root </> "db" </> d </> "one@2026-11-18_sqiff.sql")+    snapshots @?= [("deploy", True), ("revert", True), ("verify", True)]+++refusesCollisions :: Assertion+refusesCollisions = withSqitchProject \root -> do+    let planFile = root </> "db/sqitch.plan"+    before <- (,) <$> readFileUtf8 planFile <*> filesIn root+    layout <- findLayout root Nothing Nothing+    plan <- readPlan planFile+    result <-+        try+            ( withProject layout \project ->+                writeUnits project Nothing plan tagging [unit AddChange "one" "select 1", unit AddChange "one" "select 2", unit AddChange "../out" "select 3"]+            )+    case result of+        Left (UserError message) -> do+            assertBool (T.unpack message) ([i|"one" would be written 2 times|] `T.isInfixOf` message)+            assertBool (T.unpack message) ("\"../out\"" `T.isInfixOf` message)+        Right () -> assertFailure "a colliding batch was written"+    after <- (,) <$> readFileUtf8 planFile <*> filesIn root+    after @?= before