sqint (empty) → 0.1.0.1
raw patch · 39 files changed
+6047/−0 lines, 39 filesdep +aesondep +basedep +bytestring
Dependencies added: aeson, base, bytestring, containers, hasql, libpg-query, opt-env-conf, pqi, pqi-ffi, process, proto-lens, rio, sqint, sqitch-plan, string-interpolate, tasty, tasty-hunit, text, vector
Files
- CHANGELOG.md +12/−0
- LICENSE +21/−0
- README.md +406/−0
- app/Main.hs +136/−0
- sqint.cabal +139/−0
- src/Sqint/Cumulative.hs +318/−0
- src/Sqint/DeferredDependency.hs +173/−0
- src/Sqint/Deploy.hs +638/−0
- src/Sqint/Deploy/Connection.hs +94/−0
- src/Sqint/Deploy/Introspector.hs +24/−0
- src/Sqint/Deploy/Observer.hs +66/−0
- src/Sqint/Deploy/PlanCheck.hs +649/−0
- src/Sqint/DeployTree.hs +78/−0
- src/Sqint/Diagnostic.hs +46/−0
- src/Sqint/Domains.hs +121/−0
- src/Sqint/Location.hs +100/−0
- src/Sqint/Lock.hs +107/−0
- src/Sqint/NodeWalk.hs +104/−0
- src/Sqint/Output.hs +92/−0
- src/Sqint/PgAst.hs +243/−0
- src/Sqint/Plpgsql.hs +204/−0
- src/Sqint/QueryPlan.hs +267/−0
- src/Sqint/Rule.hs +114/−0
- src/Sqint/Run.hs +175/−0
- src/Sqint/SetLocal.hs +210/−0
- src/Sqint/Severity.hs +22/−0
- src/Sqint/Suppression.hs +107/−0
- test/Spec.hs +34/−0
- test/Sqint/CumulativeSpec.hs +147/−0
- test/Sqint/DeferredDependencySpec.hs +224/−0
- test/Sqint/DeploySpec.hs +74/−0
- test/Sqint/DomainsSpec.hs +111/−0
- test/Sqint/LockSpec.hs +54/−0
- test/Sqint/OutputSpec.hs +62/−0
- test/Sqint/PgAstSpec.hs +147/−0
- test/Sqint/PlanCheckSpec.hs +114/−0
- test/Sqint/QueryPlanSpec.hs +166/−0
- test/Sqint/SetLocalSpec.hs +141/−0
- test/Sqint/SuppressionSpec.hs +107/−0
+ CHANGELOG.md view
@@ -0,0 +1,12 @@+# Changelog++## 0.1.0.1++* Parse with libpg_query 18 (PostgreSQL 18's grammar), through+ `libpg-query` on Hackage instead of Kronor's `pg-query` fork.+* Read PL/pgSQL trigger bodies again under libpg_query 18.0.0 and 18.1.0,+ whose JSON for a trigger's implicit variables does not decode.++## 0.1.0.0++First release.
+ 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,406 @@+# sqint++sqint lints [sqitch](https://sqitch.org) deploy scripts for PostgreSQL migrations that are dangerous on a busy database: statements that hold heavy locks while they scan or rewrite a table, queries that stop using an index, settings silently lost between transactions, and functions left broken between one change and the next.++```console+$ cat deploy/add_orders_status.sql+-- Deploy shop:add_orders_status to pg++begin;++alter table public.orders add column status text not null default 'pending';+alter table public.orders add constraint orders_amount_positive check (amount > 0);+create index orders_customer on public.orders (customer_id);++commit;++$ sqint --database-root . deploy/add_orders_status.sql+BLOCK deploy/add_orders_status.sql:6 [lock/add-constraint] ADD CONSTRAINT CHECK — scans every row under AccessExclusiveLock+WARN deploy/add_orders_status.sql:7 [lock/create-index] CREATE INDEX (non-concurrent) — Share lock blocks writes for the duration of the build+1 informational or suppressed finding hidden — pass --verbose to show.+```++The `add column` is fine (a constant default is a catalog-only change since PostgreSQL 11), so it is only reported with `--verbose`. The check constraint reads every row while it holds a lock that blocks all reads and writes, and the index build blocks every write until it finishes.++sqint has two passes:++- **The static pass** reads only the SQL. It parses each statement with PostgreSQL's own parser ([libpg_query](https://github.com/pganalyze/libpg_query)), including the bodies of PL/pgSQL functions, so it needs no database and is fast enough for a pre-commit hook.+- **The dynamic pass** runs when you give it a database (`--with-postgres`) and the last change already deployed there (`--baseline-change`). It deploys every change after that one in plan order and, before each, runs its statements in a transaction it rolls back while a second connection reads `pg_locks`. It reports the locks actually taken and table rewrites, asks the planner whether a cast really costs an index, and reports SQL functions a change leaves broken. Meant for CI.++## Contents++1. [Install](#install)+2. [Running it](#running-it)+3. [What it catches](#what-it-catches)+ 1. [Locks held while a table is scanned or rewritten](#locks-held-while-a-table-is-scanned-or-rewritten)+ 2. [Queries that cannot use an index](#queries-that-cannot-use-an-index)+ 3. [Settings lost at COMMIT](#settings-lost-at-commit)+ 4. [Functions broken between changes](#functions-broken-between-changes)+ 5. [Locks observed while deploying](#locks-observed-while-deploying)+ 6. [Unfinished deferred backfills (opt-in)](#unfinished-deferred-backfills-opt-in)+4. [Opting out](#opting-out)+5. [Severities and exit status](#severities-and-exit-status)+6. [Options](#options)+7. [Rule reference](#rule-reference)+8. [Limits](#limits)+9. [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 sqint rather than building it once you accept the flake's settings.++```bash+nix run github:kronor-io/sqint -- --help+```++```bash+nix profile install github:kronor-io/sqint+```++Each version tag also publishes an image for amd64 and arm64, with sqitch and psql beside sqint for the dynamic pass:++```bash+docker run --rm -v "$PWD:/work" ghcr.io/kronor-io/sqint --help+```++On Linux without nix, each [release](https://github.com/kronor-io/sqint/releases) has a static binary for x86_64 and aarch64, which runs on any distribution. The tarball holds `bin/sqint` 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/sqint/releases/latest/download/sqint-$(uname -m)-linux.tar.xz" | tar -xJ -C ~/.local+```++The binary is sqint alone: the dynamic pass also needs `sqitch` on `PATH`.++In a clone, `nix build` 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, libpg_query, Postgres and sqitch, where `cabal build` and `cabal test` work.++## Running it++Give sqint the deploy scripts to check, usually the ones a branch adds or changes, and the sqitch top directory (the one holding `deploy/`, `database` unless you say otherwise):++```bash+sqint --database-root db $(git diff --name-only main -- db/deploy)+```++That is the static pass. For the dynamic pass, deploy the target branch to a scratch database first, then run sqint on the branch under review from the directory holding `sqitch.conf`. sqint runs `sqitch deploy --to-change <change> --verify` for each new change, so give sqitch the same database through the `PG*` variables:++```bash+git switch main+sqitch deploy db:pg://postgres@localhost/scratch+baseline=$(awk '!/^[%#@]/ && NF { change = $1 } END { print change }' db/sqitch.plan)++git switch my-branch+PGHOST=localhost PGUSER=postgres PGDATABASE=scratch \+ sqint --database-root db \+ --with-postgres "postgres://postgres@localhost/scratch" \+ --baseline-change "$baseline" \+ $(git diff --name-only main -- db/deploy)+```++Every change after the baseline is deployed for real, one at a time, so use a database you can throw away.++## What it catches++Every example below is sqint's own output for the SQL above it.++### Locks held while a table is scanned or rewritten++Most DDL takes a lock on the table. A lock held for a catalog change is released in microseconds; the danger is a lock held while PostgreSQL reads or rewrites every row, because every query that needs a conflicting lock queues behind it, and everything else queues behind those.++**Adding columns.** A nullable column, or one with a constant default, is a catalog change. A `not null` column without a default makes PostgreSQL check every row, and so does a column whose type is a domain with a `check`:++```sql+alter table public.orders add column note text;+alter table public.orders add column shipped_at timestamptz not null;+alter table public.customers add column contact public.email; -- create domain public.email as text check (…)+```++```console+INFO db/deploy/add_columns.sql:3 [lock/add-column] ADD COLUMN — quick catalog-only change+BLOCK db/deploy/add_columns.sql:4 [lock/add-column] ADD COLUMN ... NOT NULL without DEFAULT — every row must satisfy the constraint immediately+BLOCK db/deploy/add_columns.sql:5 [lock/add-column] ADD COLUMN of a CHECK-bearing domain — every existing row is validated under AccessExclusiveLock+```++sqint finds the domains with a `check` by reading every file under `deploy/`, so a domain created in another change counts.++**Constraints.** `check` and `foreign key` constraints are validated against every existing row under an `ACCESS EXCLUSIVE` lock, and a `check` added to a domain scans every column of that type:++```sql+alter table public.orders add constraint orders_amount_positive check (amount > 0);+alter table public.orders add constraint orders_customer_fk foreign key (customer_id) references public.customers (id);+alter domain public.email add constraint email_lowercase check (value = lower(value));+```++```console+BLOCK db/deploy/constraints.sql:3 [lock/add-constraint] ADD CONSTRAINT CHECK — scans every row under AccessExclusiveLock+BLOCK db/deploy/constraints.sql:4 [lock/add-constraint] ADD CONSTRAINT FOREIGN KEY — scans every row under AccessExclusiveLock+BLOCK db/deploy/constraints.sql:6 [lock/alter-domain] ALTER DOMAIN ADD CONSTRAINT — scans every column of every table using the domain+```++Add the constraint `not valid`, which only applies it to new rows, and validate it afterwards. `validate constraint` takes a `SHARE UPDATE EXCLUSIVE` lock, which lets reads and writes continue while it scans:++```sql+alter table public.orders add constraint orders_amount_positive check (amount > 0) not valid;+alter table public.orders validate constraint orders_amount_positive;+```++```console+INFO db/deploy/safe.sql:3 [lock/add-constraint] ADD CONSTRAINT CHECK ... NOT VALID — existing rows are not re-checked+```++**Changing a column's type** rewrites the table and every index on it, unless the old type converts to the new one without any change on disk (`varchar(10)` to `varchar(20)` or `text`, for example):++```sql+alter table public.orders alter column amount type numeric(12, 2);+```++```console+BLOCK db/deploy/retype.sql:3 [lock/alter-column-type] ALTER COLUMN TYPE — table rewrite under AccessExclusiveLock unless binary-coercible+```++The static pass cannot tell which conversions are free; the dynamic pass sees whether the table was rewritten.++**Indexes.** `create index` blocks writes for as long as the build takes; `drop index` takes an `ACCESS EXCLUSIVE` lock, briefly:++```sql+create index orders_customer on public.orders (customer_id);+drop index public.orders_created;+```++```console+WARN db/deploy/indexes.sql:3 [lock/create-index] CREATE INDEX (non-concurrent) — Share lock blocks writes for the duration of the build+```++Build and drop them `concurrently` instead, in a change of their own without `begin`/`commit`, since neither can run inside a transaction. sqint then reports both only with `--verbose`:++```console+INFO db/deploy/indexes_concurrently.sql:3 [lock/create-index] CREATE INDEX CONCURRENTLY — concurrent with DML+INFO db/deploy/indexes_concurrently.sql:4 [lock/drop-index] DROP INDEX CONCURRENTLY — concurrent with DML+```++### Queries that cannot use an index++A column wrapped in a cast or a function call in a `where`, `join … on`, `merge` or `on conflict` predicate is compared as an expression, so a plain index on the column cannot be used and PostgreSQL scans the table instead. sqint looks for this in top-level statements and in the statements of PL/pgSQL function bodies, such as triggers that run on every write:++```sql+create function public.link_payment() returns trigger language plpgsql as $$+begin+ update public.orders set paid = true where id::text = new.order_reference;+ return new;+end;+$$;++delete from public.sessions where date_trunc('day', created_at) < current_date - 30;+```++```console+WARN db/deploy/lookup.sql:10 [index/function-on-column] function call on a column may defeat an index+ A column is wrapped in a function call inside a WHERE/JOIN predicate,+ so Postgres compares the function result rather than the column and a+ plain index on the column cannot be used. Rewrite so the bare column+ is compared (move the function to the other side), or add a matching+ expression index. Suppress with `-- lint:ignore reason="…"` if the+ column is unindexed.+WARN db/deploy/lookup.sql:5 [index/cast-on-column] cast on a column reference may defeat an index+ A column is cast to another type inside a WHERE/JOIN predicate, which+ forces Postgres to treat the column as an expression and prevents+ normal index lookups on it. If the column has an index, drop the cast+ (cast the other side of the comparison instead) or add a matching+ expression index. Suppress with `-- lint:ignore reason="…"` if the+ column is unindexed.+```++Write `id = new.order_reference::bigint` and `created_at < current_date - 30` instead. A cast or function in a select list, `returning`, `set` or `having` does not affect how rows are found and is not reported.++The static pass does not know which columns are indexed, so these are warnings. The dynamic pass asks the planner: it runs `explain` on the statement as written and with the cast removed, and when only the version without the cast uses an index, the warning becomes a `BLOCK`:++```console+BLOCK deploy/link_payments.sql:9 [index/defeated] Cast on a column forces a sequential scan on orders+ Postgres EXPLAIN confirms a cast in this statement prevents the planner from using an index on orders. With the column cast removed the planner picks an Index Scan; with the cast in place it falls back to Seq Scan. Cast the other side of the comparison instead, or add an expression index. Suppress with `-- lint:ignore reason="…"` if the cast is intentional.+```++### Settings lost at COMMIT++A procedure that commits between batches loses every `set local` (and `set_config(…, true)`) at the first `commit`, so every batch after the first runs with the server's default:++```sql+create procedure public.archive_orders() language plpgsql as $$+begin+ set local lock_timeout = '1s';+ loop+ delete from public.orders where id in (select id from public.orders where archived limit 1000);+ exit when not found;+ commit;+ end loop;+end;+$$;+```++```console+BLOCK db/deploy/batches.sql:5 [txn/set-local-across-commit] transaction-scoped setting in a block that COMMITs+ `set local lock_timeout = '1s'` is scoped to the current transaction, and this block COMMITs. Only the first iteration runs with it; every one after that falls back to the cluster default (for lock_timeout, 0 -- wait forever). Use session scope instead: set_config(name, value, false).+```++### Functions broken between changes++Sqitch commits each change on its own. When a change drops or renames something a function uses and a later change fixes the function, every call to it fails in between. The dynamic pass checks every SQL function after each deploy:++```sql+-- deploy/orders.sql, already deployed:+create function public.customer_spend(customer bigint) returns numeric+language sql stable as $$+ select sum(amount) from public.orders where customer_id = customer;+$$;++-- deploy/rename_amount.sql, new:+alter table public.orders rename column amount to total;+```++```console+BLOCK ./deploy/rename_amount.sql:3 [function/broken-body] `customer_spend(bigint)` is broken after deploying `rename_amount`+ Postgres rejects the current definition of `customer_spend(bigint)` once `rename_amount` is deployed: column "amount" does not exist. No later change in this PR fixes it, so it stays broken after the deploy. Sqitch commits each change on its own, so every call to the function fails for as long as it is broken. Redefine the function in the same change that breaks it (for a new column, inside the migration's transaction).+```++Redefine the function in the same change, inside its transaction. A function already broken before the baseline is not reported.++### Locks observed while deploying++The dynamic pass reports the locks each statement actually took, which covers statements the static pass has no rule for, and whether the table was rewritten. Locks held only for a catalog change are informational:++```console+INFO ./deploy/rename_amount.sql:5 [lock/observed-access-exclusive] Acquired AccessExclusiveLock on public.orders (catalog-only)+ SAFE: AccessExclusiveLock held only briefly for a catalog-only change (no scan, no rewrite).+INFO ./deploy/link_payments.sql:14 [lock/observed-share-row-exclusive] Acquired ShareRowExclusiveLock on public.payments+```++A rewrite under `ACCESS EXCLUSIVE`, or a scan under a lock that blocks writes, is reported like its static counterpart. Statements that cannot run inside a transaction, such as `create index concurrently`, cannot be observed and are reported as `deploy/non-transactional`, with the static findings still applying.++### Unfinished deferred backfills (opt-in)++Some projects fill a new column on a large table in batches, outside the migration, and register the backfill in a table. With `--deferred-backfills`, sqint supports that convention: a change registers a backfill with `insert into deferred.migration (name, source_table) values (…)`, and a later change that validates a constraint or sets `not null` on that table must first `call deferred.ensure_finished('<name>', …)`. Otherwise it passes against the empty tables of development and CI, then fails in production on the rows not yet converted.++```sql+-- deploy/register_backfill.sql+alter table public.orders add column region text;+insert into deferred.migration (name, source_table)+values ('orders_region_backfill', 'public.orders');++-- deploy/region_not_null.sql+alter table public.orders alter column region set not null;+```++```console+$ sqint --database-root db --deferred-backfills db/deploy/region_not_null.sql+BLOCK db/deploy/region_not_null.sql:3 [deferred/unfinished-backfill] constraint depends on a deferred backfill that this change does not finalise+ A deferred backfill named `orders_region_backfill` is registered for this table. Validating the constraint without first calling deferred.ensure_finished('orders_region_backfill', …) passes in dev and CI, where the table is empty, and in production fails on unconverted rows.+```++Projects without that convention leave the flag off, and the rule never runs.++## Opting out++**For one statement**, put `-- lint:ignore reason="…"` on the line above it, or at the end of any of its lines:++```sql+-- lint:ignore reason="orders is empty until launch"+alter table public.orders add constraint orders_amount_positive check (amount > 0);++create index orders_customer on public.orders (customer_id); -- lint:ignore reason="built during the maintenance window"++-- lint:ignore+create index orders_status on public.orders (status);+```++```console+$ sqint --database-root db --verbose db/deploy/suppressed.sql+WARN db/deploy/suppressed.sql:8 [suppression/missing-reason] lint:ignore annotation missing reason="…"+ Annotation is ignored. Add `reason="why this is safe"` so the suppression is audited.+SUPPRESSED db/deploy/suppressed.sql:4 [lock/add-constraint] ADD CONSTRAINT CHECK — scans every row under AccessExclusiveLock+ reason: orders is empty until launch+SUPPRESSED db/deploy/suppressed.sql:6 [lock/create-index] CREATE INDEX (non-concurrent) — Share lock blocks writes for the duration of the build+ reason: built during the maintenance window+WARN db/deploy/suppressed.sql:9 [lock/create-index] CREATE INDEX (non-concurrent) — Share lock blocks writes for the duration of the build+```++- The annotation silences every finding on that statement, static and dynamic, and nothing else: never the next statement, and never the rest of the file.+- The reason is required. Without one the annotation does nothing and is itself reported, so every suppression says why it is safe.+- Suppressed findings are hidden by default; `--verbose` lists them with their reasons, and `--format json` marks them `"suppressed": true` with `"suppressedReason"`.++**For a whole pass or rule:**++- Without `--with-postgres`, only the static pass runs.+- The `deferred/` rule runs only with `--deferred-backfills`.+- sqint only reads the files you name, so a file you leave out is not checked (the deploy tree is still read for domains and backfill registrations).++There is no configuration file and no way to turn off a single rule for a whole run: a finding is either fixed or suppressed, with its reason, next to the statement it is about.++## Severities and exit status++| Severity | Meaning | Shown | Exit status |+|---|---|---|---|+| `BLOCK` | The statement blocks other sessions, or breaks something, on a table with rows. | Always | 1 |+| `WARN` | Likely a problem, but sqint cannot be sure: a cast that may defeat an index, an index build that blocks writes. | Always | 0 |+| `INFO` | Safe, or a check sqint could not run. | `--verbose` | 0 |++A suppressed finding never affects the exit status. `setup/` findings mean sqint could not run a check (SQL it could not parse, a plan it could not read, a baseline not in the plan); they say nothing about the migration, so check that they are not hiding something.++With `--format json`, sqint prints one array of findings for tools:++```json+[{"detail":"","endCol":65,"endLine":3,"path":"db/deploy/retype.sql","ruleId":"lock/alter-column-type","severity":"BLOCK","startCol":1,"startLine":3,"suppressed":false,"suppressedReason":null,"title":"ALTER COLUMN TYPE — table rewrite under AccessExclusiveLock unless binary-coercible"}]+```++## Options++| Option | |+|---|---|+| `FILE...` | Deploy scripts to lint. |+| `--database-root DIR` | The sqitch top directory, which holds `deploy/`. Default `database`. |+| `--plan-file FILE` | The plan that orders changes for the dynamic pass. Default `DIR/sqitch.plan`. |+| `--with-postgres DSN` | A libpq connection string (`postgres://…` or `key=value`) to a database deployed up to the baseline. Turns on the dynamic pass. |+| `--baseline-change CHANGE` | The last change of the target branch's plan. Every change after it is new and is deployed in order. |+| `--deferred-backfills` | Turn on the `deferred/` rule. |+| `--format text\|json` | Text for people, JSON for tools. |+| `--verbose` | Also print `INFO` and suppressed findings. |++## Rule reference++| Rule | Pass | Severity | Reports |+|---|---|---|---|+| `lock/add-column` | static | BLOCK, INFO | A `not null` column without a default, or a column of a domain with a `check`. |+| `lock/add-constraint` | static | BLOCK, INFO | A `check` or `foreign key` constraint added without `not valid`. |+| `lock/alter-domain` | static | BLOCK, INFO | A `check` added to a domain without `not valid`. |+| `lock/alter-column-type` | static | BLOCK | A column type change, which may rewrite the table. |+| `lock/create-index` | static | WARN, INFO | An index built without `concurrently`. |+| `lock/drop-index` | static | INFO | An index dropped, with or without `concurrently`. |+| `lock/observed-<mode>` | dynamic | BLOCK, WARN, INFO | A lock a statement was seen to take, such as `lock/observed-access-exclusive`, and whether it scanned or rewrote the table. |+| `index/cast-on-column` | static | WARN | A cast on a column in a predicate. |+| `index/function-on-column` | static | WARN | A function call on a column in a predicate. |+| `index/defeated` | dynamic | BLOCK | A cast the planner confirms turns an index scan into a sequential scan. |+| `txn/set-local-across-commit` | static | BLOCK | A transaction-scoped setting in a PL/pgSQL block that commits. |+| `function/broken-body` | dynamic | BLOCK | A SQL function a change leaves failing. |+| `deferred/unfinished-backfill` | static, opt-in | BLOCK | A constraint validated, or `not null` set, before a registered backfill on the table is finished. |+| `suppression/missing-reason` | static | WARN | A `lint:ignore` without a reason. |+| `deploy/non-transactional` | dynamic | INFO | A statement that cannot run in a transaction, so its locks were not observed. |+| `deploy/statement-not-observed` | dynamic | INFO | A statement the dynamic pass could not run on its own. |+| `deploy/failed` | dynamic | BLOCK | `sqitch deploy` failed on a change; the changes after it are not checked. |+| `function/check-skipped` | dynamic | WARN | The broken-function check could not run. |+| `index/plan-check-skipped` | dynamic | INFO | A statement the planner check could not plan. |+| `setup/unparsable-sql` | static | WARN | A file libpg_query could not parse. |+| `setup/unparsable-domain-file` | static | INFO | A deploy file sqint could not read for domains. |+| `setup/unparsable-plan` | dynamic | INFO | A `sqitch.plan` sqint could not read. |+| `setup/baseline-missing` | dynamic | INFO | A `--baseline-change` that is not in the plan. |++## Limits++- The static pass knows nothing about the database: not which columns are indexed, how big a table is, or which type changes are free. It errs towards reporting; the dynamic pass and `lint:ignore` settle the rest.+- Index rules look at the statements of PL/pgSQL bodies but not inside `language sql` bodies, `perform` or dynamic SQL run with `execute`. Only a cast or call directly on the compared column is reported, not one nested deeper in an expression.+- libpg_query parses PostgreSQL 18's grammar, so syntax newer than that is reported as `setup/unparsable-sql`.+- The dynamic pass deploys with sqitch and checks locks one statement at a time, inside a transaction it rolls back; it says nothing about how long a statement takes on production data.++## Tests++`cabal test` (or `nix flake check`) runs the static rules against SQL written in the tests. The dynamic pass needs a running PostgreSQL and is not covered by them.++## Licence++MIT
+ app/Main.hs view
@@ -0,0 +1,136 @@+{-# LANGUAGE ApplicativeDo #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++module Main where++import Data.Version (makeVersion)+import OptEnvConf+import RIO hiding (Reader)+import RIO.FilePath ((</>))+import Sqint.Deploy.Connection (DeploySettings, parseSettings)+import Sqint.Output (OutputFormat (..))+import Sqint.Run (LintConfig (..), runLint)+import System.Exit qualified as Exit+++data Args = Args+ { outputFormat :: OutputFormat+ , databaseRoot :: FilePath+ , planFile :: Maybe FilePath+ , baselineChange :: Maybe Text+ , verbose :: Bool+ , withPostgres :: Maybe DeploySettings+ , deferredBackfills :: Bool+ , paths :: [FilePath]+ }+++instance HasParser Args where+ settingsParser = do+ outputFormat <-+ setting+ [ help "Output format: text or json"+ , long "format"+ , reader outputFormatReader+ , metavar "FORMAT"+ , option+ , value OutputText+ ]+ databaseRoot <-+ setting+ [ help "The sqitch top directory: holds deploy/ and, by default, sqitch.plan"+ , long "database-root"+ , reader str+ , metavar "DIR"+ , option+ , value "database"+ ]+ planFile <-+ optional+ $ setting+ [ help "Path to sqitch.plan, which orders the new changes for the dynamic pass (default: DIR/sqitch.plan)"+ , long "plan-file"+ , reader str+ , metavar "FILE"+ , option+ ]+ baselineChange <-+ optional+ $ setting+ [ help+ "Target branch's plan head (sqitch change name). Everything\+ \ after it in the plan is treated as new in this PR and\+ \ observed cumulatively. Required for the dynamic pass."+ , long "baseline-change"+ , reader (fromString <$> str)+ , metavar "CHANGE"+ , option+ ]+ verbose <-+ setting+ [ help "Show informational and suppressed findings too (default: only BLOCK/WARN)"+ , long "verbose"+ , switch True+ , value False+ ]+ withPostgres <-+ optional+ $ setting+ [ help+ "libpq connection string (DSN/URI) for the dynamic\+ \ pass. When set, the linter runs both the static\+ \ AST classifier and the dynamic pass; when unset,\+ \ static-only."+ , long "with-postgres"+ , reader deploySettingsReader+ , metavar "DSN"+ , option+ ]+ deferredBackfills <-+ setting+ [ help+ "Check that a change finishes the deferred backfills registered\+ \ on a table (deferred.migration) before validating a constraint\+ \ or setting NOT NULL there"+ , long "deferred-backfills"+ , switch True+ , value False+ ]+ paths <-+ many+ $ setting+ [ help "SQL files to lint"+ , reader str+ , argument+ , metavar "FILE"+ ]+ pure Args{outputFormat, databaseRoot, planFile, baselineChange, verbose, withPostgres, deferredBackfills, paths}+++outputFormatReader :: Reader OutputFormat+outputFormatReader = maybeReader \case+ "text" -> Just OutputText+ "json" -> Just OutputJson+ _ -> Nothing+++deploySettingsReader :: Reader DeploySettings+deploySettingsReader = eitherReader parseSettings+++main :: IO ()+main = do+ args :: Args <- runSettingsParser (makeVersion [0, 1]) "Static + dynamic linter for sqitch migrations on PostgreSQL"+ Exit.exitWith+ =<< runLint+ LintConfig+ { paths = args.paths+ , outputFormat = args.outputFormat+ , verbose = args.verbose+ , databaseRoot = args.databaseRoot+ , planPath = fromMaybe (args.databaseRoot </> "sqitch.plan") args.planFile+ , baselineChange = args.baselineChange+ , postgres = args.withPostgres+ , deferredBackfills = args.deferredBackfills+ }
+ sqint.cabal view
@@ -0,0 +1,139 @@+cabal-version: 3.4+name: sqint+version: 0.1.0.1+synopsis:+ Lint sqitch migrations for PostgreSQL lock and rewrite hazards++description:+ sqint reads sqitch deploy scripts and reports statements that take+ heavy locks, rewrite or scan tables, defeat indexes, or leave SQL+ functions broken between changes. A static pass needs only the SQL;+ an optional dynamic pass deploys each new change to a scratch+ database and observes the locks it actually takes.++category: Database+homepage: https://github.com/kronor-io/sqint+bug-reports: https://github.com/kronor-io/sqint/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:+ CHANGELOG.md+ README.md++source-repository head+ type: git+ location: https://github.com/kronor-io/sqint++common shared+ default-language: GHC2021+ default-extensions:+ BlockArguments+ DataKinds+ DerivingStrategies+ DuplicateRecordFields+ LambdaCase+ MultilineStrings+ MultiWayIf+ NoImplicitPrelude+ OverloadedRecordDot+ OverloadedStrings+ PatternSynonyms+ QuasiQuotes+ RecordWildCards+ StrictData+ ViewPatterns++ ghc-options:+ -Wall -Wcompat -Widentities -Wincomplete-record-updates+ -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints+ -Wunused-packages++library+ import: shared+ hs-source-dirs: src+ exposed-modules:+ Sqint.Cumulative+ Sqint.DeferredDependency+ Sqint.Deploy+ Sqint.Deploy.Connection+ Sqint.Deploy.Introspector+ Sqint.Deploy.Observer+ Sqint.Deploy.PlanCheck+ Sqint.DeployTree+ Sqint.Diagnostic+ Sqint.Domains+ Sqint.Location+ Sqint.Lock+ Sqint.NodeWalk+ Sqint.Output+ Sqint.PgAst+ Sqint.Plpgsql+ Sqint.QueryPlan+ Sqint.Rule+ Sqint.Run+ Sqint.SetLocal+ Sqint.Severity+ Sqint.Suppression++ build-depends:+ , aeson >=2.3 && <2.4+ , base >=4.21 && <5+ , bytestring >=0.12 && <0.13+ , containers >=0.7 && <0.8+ , hasql >=2.0 && <2.1+ , libpg-query ^>=0.1+ , pqi >=1.1 && <1.2+ , pqi-ffi >=1.0 && <1.1+ , process >=1.6 && <1.7+ , proto-lens >=0.7 && <0.8+ , rio >=0.1.22 && <0.2+ , sqitch-plan ^>=0.1+ , string-interpolate >=1.0 && <1.1+ , text >=2.1 && <2.2+ , vector >=0.13 && <0.14++executable sqint+ import: shared+ hs-source-dirs: app+ main-is: Main.hs+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ build-depends:+ , base+ , opt-env-conf >=0.15 && <0.18+ , rio+ , sqint++test-suite sqint-test+ import: shared+ type: exitcode-stdio-1.0+ hs-source-dirs: test+ main-is: Spec.hs+ ghc-options: -threaded -rtsopts -with-rtsopts=-N+ other-modules:+ Sqint.CumulativeSpec+ Sqint.DeferredDependencySpec+ Sqint.DeploySpec+ Sqint.DomainsSpec+ Sqint.LockSpec+ Sqint.OutputSpec+ Sqint.PgAstSpec+ Sqint.PlanCheckSpec+ Sqint.QueryPlanSpec+ Sqint.SetLocalSpec+ Sqint.SuppressionSpec++ build-depends:+ , bytestring+ , containers+ , rio+ , sqint+ , sqitch-plan ^>=0.1+ , string-interpolate+ , tasty+ , tasty-hunit+ , text
+ src/Sqint/Cumulative.hs view
@@ -0,0 +1,318 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | Cumulative, plan-ordered dynamic pass.+--+-- The dynamic pass ("Sqint.Deploy") can only observe the+-- locks a migration takes against a schema that has every /preceding/+-- migration already applied. A pull request is usually a chain of+-- interdependent changes (add a column, backfill it, constrain it, add+-- an FK to a new table…), so observing each change against the bare+-- pre-PR baseline makes the later ones fail with "column/relation does+-- not exist" — false positives, because the migrations are fine, they+-- were just run against the wrong schema state.+--+-- This module fixes that at the source. The caller deploys the target+-- branch's schema up to its plan head (the @baseline@ change). We then+-- walk the PR's /new/ changes in @sqitch.plan@ order and, for each one:+--+-- 1. observe its locks against the current (correct) schema state via+-- 'Deploy.inspectFile' — a transaction that is rolled back, so the+-- observation never mutates anything; then+-- 2. @sqitch deploy --to-change <name>@ it for real, so the next+-- change observes against a schema that includes this one.+--+-- Because the real deploy advances the schema between observations,+-- every change is observed exactly as it will run in production, and+-- non-transactional changes (e.g. @CREATE INDEX CONCURRENTLY@) — which+-- cannot be observed inside a transaction — are still deployed normally+-- so the cumulative state never desyncs.+--+-- After each deploy it also checks that every @language sql@ function+-- still compiles ('Deploy.brokenSqlFunctions'). Sqitch commits each change+-- on its own, so a function left broken by one change and repaired by a+-- later one is broken in production for the time between them, and every+-- call in that window fails. Functions already broken at the baseline are+-- not reported.+module Sqint.Cumulative (+ runCumulativeDeploy,++ -- * Internals exposed for the test-suite+ newChangesAfter,+ BrokenFunction (..),+ FunctionCheck (..),+ recordCheck,+ trackBrokenFunctions,+ brokenFunctionFinding,+ firstStatementLine,+) where++import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import RIO.Directory (doesFileExist)+import RIO.FilePath ((</>))+import Sqint.Deploy qualified as Deploy+import Sqint.Deploy.Connection (DeploySettings)+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (Rule (..))+import Sqitch.Plan qualified as Plan+import System.Process (proc, readCreateProcessWithExitCode)+++-- | Run the cumulative dynamic pass: observe each new change against+-- the correct cumulative schema, deploying it for real before moving+-- to the next.+runCumulativeDeploy ::+ DeploySettings ->+ -- | The sqitch top directory, which holds @deploy/@.+ FilePath ->+ -- | Path to the PR's @sqitch.plan@.+ FilePath ->+ -- | The baseline change — the target branch's plan head. Everything+ -- after it in the plan is new in this PR.+ Text ->+ IO [Finding]+runCumulativeDeploy settings topDir planPath baseline = do+ planSrc <- readFileUtf8 planPath+ case Plan.parsePlan planSrc of+ Left err -> pure [planParseFinding planPath (Plan.renderParseError err)]+ Right plan -> case newChangesAfter plan baseline of+ Nothing -> pure [baselineMissingFinding planPath baseline]+ Just changes -> observeAndDeploy settings topDir planPath changes+++-- | The changes that come strictly after the @baseline@ change, in+-- plan (deploy) order. 'Nothing' when the baseline change is not in the+-- plan at all — a configuration error the caller surfaces rather than+-- silently treating every change as new (which would re-deploy the+-- whole history).+newChangesAfter :: Plan.Plan -> Text -> Maybe [Plan.Change]+newChangesAfter plan baseline = map (.value) <$> Plan.changesAfter baseline plan+++-- | The observe-then-deploy loop. Stops at the first deploy failure+-- (the schema would be desynced past that point, so later observations+-- would be meaningless) and reports it.+observeAndDeploy :: DeploySettings -> FilePath -> FilePath -> [Plan.Change] -> IO [Finding]+observeAndDeploy settings topDir planPath changes = do+ baseline <- tryAny (Deploy.brokenSqlFunctions settings)+ case baseline of+ Left err -> do+ findings <- go FunctionCheck{known = Nothing, episodes = []} [] changes+ pure (functionCheckSkippedFinding planPath (tshow err) : findings)+ Right known -> go FunctionCheck{known = Just known, episodes = []} [] changes+ where+ go functions acc [] = pure (reverse acc <> brokenFindings functions)+ go functions acc (change : rest) = do+ let name = change.name+ script = topDir </> "deploy" </> T.unpack name <> ".sql"+ exists <- doesFileExist script+ observed <-+ if exists+ then Deploy.inspectFile settings script+ else pure []+ deployed <- sqitchDeployTo (deployTarget change)+ case deployed of+ Right () -> do+ (functions', skipped) <- checkFunctions functions name script+ go functions' (skipped <> reverse observed <> acc) rest+ Left err ->+ pure (reverse acc <> observed <> [deployFailedFinding script name err] <> brokenFindings functions)++ checkFunctions functions name script+ | isNothing functions.known = pure (functions, [])+ | otherwise = do+ now <- either (Left . tshow) Right <$> tryAny (Deploy.brokenSqlFunctions settings)+ line <- firstStatementLine <$> readFileUtf8OrEmpty script+ pure (recordCheck name script line now functions)++ brokenFindings functions = map brokenFunctionFinding functions.episodes++ readFileUtf8OrEmpty path = fromRight "" <$> tryAny (readFileUtf8 path)+++-- | What the SQL function check has established so far.+data FunctionCheck = FunctionCheck+ { known :: Maybe (Map Text Text)+ -- ^ Broken at the baseline; 'Nothing' once a check has failed to run,+ -- which stops further checks.+ , episodes :: [BrokenFunction]+ -- ^ Every time a change in this PR left a function broken, oldest first.+ }+++-- | Fold one change's check result into the state. A check that fails to+-- run stops later checks but keeps what earlier checks found, so failing+-- to gather more evidence never hides a broken function already seen.+recordCheck ::+ -- | The change just deployed.+ Text ->+ -- | Its deploy script.+ FilePath ->+ -- | The line findings for this change point at.+ Int ->+ -- | Broken now, or why the check could not run.+ Either Text (Map Text Text) ->+ FunctionCheck ->+ (FunctionCheck, [Finding])+recordCheck name script line result functions = case (functions.known, result) of+ (Nothing, _) -> (functions, [])+ (Just _, Left err) -> (functions{known = Nothing}, [functionCheckSkippedFinding script err])+ (Just known, Right now) -> (functions{episodes = trackBrokenFunctions known name script line now functions.episodes}, [])+++-- | A function a change in this PR left broken.+data BrokenFunction = BrokenFunction+ { signature :: Text+ , message :: Text+ , brokenBy :: Text+ , script :: FilePath+ , line :: Int+ , fixedBy :: Maybe Text+ }+ deriving stock (Eq, Show)+++-- | Fold one change's check into the episodes so far: an open episode+-- whose function works again is closed as fixed by this change, and a+-- function broken now that was not broken at the baseline and has no+-- open episode starts a new one attributed to this change. A function+-- that is repaired and later broken again therefore gets a second+-- episode, and so a second finding.+trackBrokenFunctions ::+ -- | Broken at the baseline.+ Map Text Text ->+ -- | The change just deployed.+ Text ->+ -- | Its deploy script.+ FilePath ->+ -- | The line findings for this change point at.+ Int ->+ -- | Broken now.+ Map Text Text ->+ [BrokenFunction] ->+ [BrokenFunction]+trackBrokenFunctions known name script line now episodes =+ let isOpen f = isNothing f.fixedBy+ close f+ | isOpen f && not (Map.member f.signature now) = f{fixedBy = Just name}+ | otherwise = f+ stillOpen = Set.fromList [f.signature | f <- episodes, isOpen f, Map.member f.signature now]+ fresh =+ [ BrokenFunction{signature, message = err, brokenBy = name, script, line, fixedBy = Nothing}+ | (signature, err) <- Map.toList (now `Map.difference` known)+ , not (Set.member signature stillOpen)+ ]+ in map close episodes <> fresh+++-- | The finding for a function a change left broken.+brokenFunctionFinding :: BrokenFunction -> Finding+brokenFunctionFinding f =+ Finding+ { range = SourceRange{path = f.script, startLine = f.line, startCol = 1, endLine = f.line, endCol = 1}+ , severity = SeverityBlock+ , rule = FunctionBrokenBody+ , title = [i|`#{signature}` is broken after deploying `#{brokenBy}`|]+ , detail = [i|Postgres rejects the current definition of `#{signature}` once `#{brokenBy}` is deployed: #{message}. #{remaining} Sqitch commits each change on its own, so every call to the function fails for as long as it is broken. Redefine the function in the same change that breaks it (for a new column, inside the migration's transaction).|]+ , suppressedBy = Nothing+ }+ where+ signature = f.signature+ brokenBy = f.brokenBy+ message = f.message+ remaining = case f.fixedBy of+ Just later -> [i|It stays broken until `#{later}` deploys, so production sees it broken during the deploy.|] :: Text+ Nothing -> "No later change in this PR fixes it, so it stays broken after the deploy."+++-- | The first line of a deploy script that is neither blank nor a comment,+-- so a @-- lint:ignore reason="…"@ placed above the first statement+-- suppresses findings attributed to the whole change. 1 for an empty file.+firstStatementLine :: Text -> Int+firstStatementLine src =+ case [n | (n, l) <- zip [1 ..] (T.lines src), let s = T.strip l, not (T.null s), not ("--" `T.isPrefixOf` s)] of+ (n : _) -> n+ [] -> 1+++-- | The @--to-change@ specifier for a change. A reworked change shares+-- its name with the earlier instance already on the database, so a bare+-- name is ambiguous to sqitch ("matches multiple changes"); @\@HEAD@+-- pins it to the latest instance — the rework we are deploying. Plain+-- (non-reworked) changes have unique names, so no qualifier is needed.+deployTarget :: Plan.Change -> Text+deployTarget change =+ let name = change.name+ in if isJust (Plan.reworkTag change) then name <> "@HEAD" else name+++-- | @sqitch deploy --to-change <target> --verify@ from the working+-- directory, where @sqitch.conf@ is. Connection parameters come from the+-- inherited @PG*@ environment, which the caller sets to the same database+-- as the linter's DSN, so each deploy writes to the registry the baseline+-- deploy populated.+sqitchDeployTo :: Text -> IO (Either Text ())+sqitchDeployTo target = do+ (code, _out, err) <-+ readCreateProcessWithExitCode+ (proc "sqitch" ["deploy", "--to-change", T.unpack target, "--verify"])+ ""+ pure case code of+ ExitSuccess -> Right ()+ ExitFailure _ -> Left (T.strip (T.pack err))+++pointFinding :: FilePath -> Severity -> Rule -> Text -> Text -> Finding+pointFinding path severity rule title detail =+ Finding+ { range = SourceRange{path, startLine = 1, startCol = 1, endLine = 1, endCol = 1}+ , severity+ , rule+ , title+ , detail+ , suppressedBy = Nothing+ }+++planParseFinding :: FilePath -> Text -> Finding+planParseFinding path err =+ pointFinding+ path+ SeverityInfo+ SetupUnparsablePlan+ "Could not parse sqitch.plan for the cumulative dynamic pass"+ ("Dynamic lock observation was skipped; static checks still applied. " <> err)+++baselineMissingFinding :: FilePath -> Text -> Finding+baselineMissingFinding path baseline =+ pointFinding+ path+ SeverityInfo+ SetupBaselineMissing+ "Baseline change not found in sqitch.plan"+ [i|The baseline change `#{baseline}` is not present in the plan, so the cumulative dynamic pass was skipped; static checks still applied.|]+++deployFailedFinding :: FilePath -> Text -> Text -> Finding+deployFailedFinding path name err =+ pointFinding+ path+ SeverityBlock+ DeployFailed+ [i|Could not deploy `#{name}`; later changes were not observed|]+ [i|The cumulative dynamic pass stopped here because `sqitch deploy` failed. Subsequent migrations in this PR were not lock-observed. Error: #{err}|]+++functionCheckSkippedFinding :: FilePath -> Text -> Finding+functionCheckSkippedFinding planPath err =+ pointFinding+ planPath+ SeverityWarn+ FunctionCheckSkipped+ "Could not check SQL functions after deploying"+ [i|The check for SQL functions left broken between changes did not run to completion, so this PR was not checked for them. Error: #{err}|]
+ src/Sqint/DeferredDependency.hs view
@@ -0,0 +1,173 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | Block a change that VALIDATEs a constraint or SETs NOT NULL on a table with+-- a registered deferred backfill without calling deferred.ensure_finished in the+-- same change — such a change passes on empty dev/CI tables and fails or drains+-- inline in production.+module Sqint.DeferredDependency (+ loadRegisteredBackfills,+ detectUnfinishedDependency,+ registrationsIn,+) where++import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import Data.String.Interpolate (iii)+import Data.Text qualified as T+import PgQuery qualified as Pg+import RIO+import Sqint.DeployTree (DeployFile (..))+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Location (statementRange)+import Sqint.Rule (Rule (..))+++-- | Backfills registered anywhere in the deploy tree, keyed by the+-- @schema.table@ they run against.+loadRegisteredBackfills :: [DeployFile] -> Map Text (Set Text)+loadRegisteredBackfills deployTree =+ Map.unionsWith Set.union (map (registrationsInLowered . (.lowered)) deployTree)+++-- | The @(table, backfill name)@ pairs a deploy script registers, read textually+-- from each @insert into deferred.migration@. Values come from a lowercased copy:+-- fine for these two lowercase-identifier fields, not for the mixed-case+-- @enqueued_by@, which is deliberately not read here.+registrationsIn :: Text -> Map Text (Set Text)+registrationsIn = registrationsInLowered . T.toLower+++-- | 'registrationsIn' for a caller that already holds a case-folded copy,+-- which is every file of a deploy tree read by "Sqint.DeployTree".+registrationsInLowered :: Text -> Map Text (Set Text)+registrationsInLowered src =+ Map.fromListWith+ Set.union+ [ (table, Set.singleton name)+ | stmt <- drop 1 (T.splitOn "insert into deferred.migration" src)+ , let body = T.takeWhile (/= ';') stmt+ , Just fields <- [insertedFields body]+ , Just name <- [Map.lookup "name" fields]+ , Just table <- [Map.lookup "source_table" fields]+ ]+++-- | Pair a registration's column list with its @values@ row. An unreadable shape+-- yields nothing; the @prepare_migration@ trigger is the floor under this rule.+insertedFields :: Text -> Maybe (Map Text Text)+insertedFields body = do+ (columnList, afterColumns) <- parenGroup body+ (valueList, _) <- parenGroup (snd (T.breakOn "values" afterColumns))+ let columns = map T.strip (T.splitOn "," columnList)+ values = map (unquote . T.strip) (T.splitOn "," valueList)+ -- zip stops at the shorter, so a mismatched arity yields fewer fields.+ pure (Map.fromList (zip columns values))+ where+ unquote t = fromMaybe t (T.stripPrefix "'" t >>= T.stripSuffix "'")+++-- | The contents of the first @(…)@ group, and whatever follows it. Not+-- paren-balanced: both groups are flat lists of identifiers or literals.+parenGroup :: Text -> Maybe (Text, Text)+parenGroup t = do+ afterOpen <- T.stripPrefix "(" (snd (T.breakOn "(" t))+ let (inner, rest) = T.breakOn ")" afterOpen+ guard (not (T.null rest))+ pure (inner, T.drop 1 rest)+++-- | Findings for a changed file that validates a constraint or sets NOT NULL+-- on a table with a registered backfill it does not finalise.+detectUnfinishedDependency :: Map Text (Set Text) -> FilePath -> Text -> IO [Finding]+detectUnfinishedDependency registered path src+ | Map.null registered = pure []+ | otherwise = do+ result <- Pg.parseSql (T.unpack src)+ pure case result of+ Left _ -> []+ Right parsed ->+ let finalised = finalisedNames parsed+ in -- One finding per open backfill on the table: a table can carry+ -- one per column, and all must be finished.+ [ finding (statementRange path src raw) name+ | raw <- parsed ^.. Pg.stmts . traverse+ , table <- dependsOn raw+ , name <- toList (Map.findWithDefault Set.empty table registered)+ , not (Set.member name finalised)+ ]+++-- | The backfill names a change actually passes to @deferred.ensure_finished@.+-- Read from parsed statements, not the file's text: a textual co-occurrence check+-- would pass on a comment or on a change finalising a different backfill.+-- All string literals in the arguments are collected so named notation still matches.+finalisedNames :: Pg.ParseResult -> Set Text+finalisedNames parsed =+ Set.fromList+ [ literal+ | raw <- parsed ^.. Pg.stmts . traverse+ , call <- toList (view Pg.maybe'callStmt (raw ^. Pg.stmt))+ , let funcCall = call ^. Pg.funccall+ , isEnsureFinished (funcCall ^.. Pg.funcname . traverse . Pg.string . Pg.sval)+ , literal <- concatMap stringLiterals (funcCall ^.. Pg.args . traverse)+ ]+ where+ -- Unqualified is accepted too: a change with a search_path calling it bare+ -- is still finalising.+ isEnsureFinished = \case+ ["ensure_finished"] -> True+ ["deferred", "ensure_finished"] -> True+ _ -> False++ -- A literal, or a named-notation wrapper around one; nothing deeper.+ stringLiterals node =+ directLiteral node+ <> foldMap+ (directLiteral . view Pg.arg)+ (toList (view Pg.maybe'namedArgExpr node))++ directLiteral node = do+ constant <- toList (view Pg.maybe'aConst node)+ string <- toList (view Pg.maybe'sval constant)+ pure (string ^. Pg.sval)+++-- | The qualified table a statement depends on the data of, if it is one of the+-- two forms that require the data to already conform.+dependsOn :: Pg.RawStmt -> [Text]+dependsOn raw = do+ stmt <- toList (view Pg.maybe'alterTableStmt (raw ^. Pg.stmt))+ let rel = stmt ^. Pg.relation+ schema = case rel ^. Pg.schemaname of+ "" -> "public"+ s -> s+ table = rel ^. Pg.relname+ guard (any requiresConformingData (stmt ^.. Pg.cmds . traverse))+ pure [iii|#{schema}.#{table}|]+++requiresConformingData :: Pg.Node -> Bool+requiresConformingData node =+ case view Pg.maybe'alterTableCmd node of+ Nothing -> False+ Just cmd ->+ cmd ^. Pg.subtype `elem` [Pg.AT_ValidateConstraint, Pg.AT_SetNotNull]+++finding :: SourceRange -> Text -> Finding+finding range name =+ Finding+ { range+ , severity = SeverityBlock+ , rule = DeferredUnfinishedBackfill+ , title = "constraint depends on a deferred backfill that this change does not finalise"+ , detail =+ [iii|+ A deferred backfill named `#{name}` is registered for this table.+ Validating the constraint without first calling+ deferred.ensure_finished('#{name}', …) passes in dev and CI, where+ the table is empty, and in production fails on unconverted rows.+ |]+ , suppressedBy = Nothing+ }
+ src/Sqint/Deploy.hs view
@@ -0,0 +1,638 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | The dynamic pass: deploy each statement and observe its locks.+--+-- Given a connection to a Postgres database whose schema matches the+-- state immediately /before/ the candidate migration, we run each+-- top-level statement in the file inside a savepoint-wrapped+-- transaction on one connection (the @executor@). After each statement+-- a second connection (the @observer@) queries @pg_locks@ for the+-- executor's pid — the locks the statement acquired are still held+-- (transactions release locks only on commit/rollback). A relfilenode+-- snapshot via the executor (which sees its own uncommitted catalog+-- changes) reveals table rewrites within the same transaction.+--+-- We never commit; the transaction is rolled back at the end, leaving+-- the database in its pre-inspection state.+--+-- Implementation note: the executor uses the raw driver connection via+-- 'Sqint.Deploy.Connection.withPqConnection' rather than the Hasql Session+-- API. We need to keep one explicit transaction open across many+-- separate Haskell calls (so locks remain visible to the observer+-- between statements), and Hasql's per-statement extended-query+-- protocol implicitly commits when used at the top level. Raw libpq's+-- 'PQ.exec' uses the simple-query protocol, which leaves transaction+-- state alone.+module Sqint.Deploy (+ inspectFile,+ brokenSqlFunctions,++ -- * Internals exposed for the test-suite+ lockFindings,+ computeImpacts,+ TableStat (..),+ RelOid (..),+) where++import Data.ByteString.Char8 qualified as BS8+import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import Data.Text qualified as T+import Data.Text.IO qualified as Text.IO+import Hasql.Connection (Connection)+import PgQuery qualified as Pg+import Pqi qualified as PQ+import RIO+import Sqint.Deploy.Connection (DeploySettings, runSession, withConnection, withPqConnection)+import Sqint.Deploy.Introspector (Pid (..), RelFileNode (..), TableName (..))+import Sqint.Deploy.Observer (PidLock (..), listConnectionLocks)+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Location (statementRange)+import Sqint.Lock (LockClass (..), LockProfile (..), RewriteImpact (..), lockClassName, parseLockMode, severityFor)+import Sqint.Rule (Rule (..))+++-- | Inspect a single SQL file. Opens two connections (executor ++-- observer), runs each top-level statement on the executor inside a+-- savepoint, observes locks via the observer, snapshots relfilenodes+-- for rewrite detection.+inspectFile :: DeploySettings -> FilePath -> IO [Finding]+inspectFile settings path = do+ src <- Text.IO.readFile path+ stmts <- splitStatements path src+ case stmts of+ [] -> pure []+ _ ->+ withConnection settings \executor ->+ withConnection settings \observer ->+ withPqConnection executor \pq -> do+ execSimple pq "BEGIN"+ execSimple pq "SET LOCAL lock_timeout = '0'"+ execSimple pq setLinterStatementTimeout+ pid <- fetchPid pq+ findings <- runStatements pq observer pid stmts+ rollback pq+ pure findings+++-- | A top-level statement extracted from a file.+data Stmt = Stmt+ { range :: SourceRange+ , text :: Text+ }+++-- | Split via libpg_query, strip transaction-control statements (the+-- dynamic pass wraps the whole file in its own transaction).+splitStatements :: FilePath -> Text -> IO [Stmt]+splitStatements path src = do+ result <- Pg.parseSql (T.unpack src)+ case result of+ Left _ -> pure []+ Right parsed -> do+ let raws = parsed ^.. Pg.stmts . traverse+ kept =+ [ stmt+ | r <- raws+ , hasContent r src+ , let stmt@Stmt{text} = stmtFromRaw path src r+ , not (isTransactionControl text)+ ]+ pure kept+++isTransactionControl :: Text -> Bool+isTransactionControl t =+ let upper = T.toUpper (T.stripStart t)+ startsWith prefix = T.isPrefixOf prefix upper+ in any+ startsWith+ [ "BEGIN"+ , "START TRANSACTION"+ , "COMMIT"+ , "ROLLBACK"+ , "END"+ , "SAVEPOINT"+ , "RELEASE"+ , "SET "+ ]+++hasContent :: Pg.RawStmt -> Text -> Bool+hasContent raw src =+ not (T.null (T.strip (extractStmtText src (raw ^. Pg.stmtLocation) (raw ^. Pg.stmtLen))))+++stmtFromRaw :: FilePath -> Text -> Pg.RawStmt -> Stmt+stmtFromRaw path src raw =+ let loc = raw ^. Pg.stmtLocation+ len = raw ^. Pg.stmtLen+ text = stripLeadingComments (T.strip (extractStmtText src loc len))+ range = statementRange path src raw+ in Stmt{range, text}+++-- | libpg_query's @stmt_location@ points at the start of the statement+-- /including/ preceding comments and whitespace, so the text we slice+-- out always carries a header of @-- …@ lines. Strip them so the+-- 'isTransactionControl' classifier can see the actual SQL keyword+-- start, and so libpq doesn't ever interpret the comments as part of+-- the statement payload.+stripLeadingComments :: Text -> Text+stripLeadingComments t =+ let s = T.stripStart t+ in case T.stripPrefix "--" s of+ Just rest -> stripLeadingComments (T.dropWhile (/= '\n') rest)+ Nothing -> case T.stripPrefix "/*" s of+ Just rest -> case T.breakOn "*/" rest of+ (_, suffix)+ | T.null suffix -> s -- unterminated comment; leave as-is+ | otherwise -> stripLeadingComments (T.drop 2 suffix)+ Nothing -> s+++extractStmtText :: Integral n => Text -> n -> n -> Text+extractStmtText src offset len =+ let bytes = encodeUtf8 src+ o = max 0 (fromIntegral offset)+ l = max 0 (fromIntegral len)+ sliced+ | l == 0 = BS8.drop o bytes+ | otherwise = BS8.take l (BS8.drop o bytes)+ in decodeUtf8Lenient sliced+++-- | Run each statement with savepoint isolation, accumulating+-- findings. A failure rolls back to the savepoint so subsequent+-- statements can still run.+runStatements ::+ PQ.Connection ->+ Connection ->+ Pid ->+ [Stmt] ->+ IO [Finding]+runStatements executor observer pid stmts = do+ -- One stats snapshot per statement: the "after" snapshot of a+ -- successful statement is the "before" of the next (same+ -- transaction, RELEASE keeps its effects), and a rolled-back+ -- statement discards its sub-transaction stats, so the carried+ -- snapshot stays accurate without re-querying.+ initial <- fetchTableStats executor+ let existing = Set.fromList [stat.relOid | stat <- Map.elems initial]+ go existing initial [] stmts+ where+ go _ _ acc [] = pure (reverse acc)+ go existing statsBefore acc (stmt@Stmt{range} : rest) = do+ before <- runSession observer (listConnectionLocks pid)+ execSimple executor "SAVEPOINT lint_deploy_sp"+ result <- runStatement executor stmt+ case result of+ StmtOk -> do+ after <- runSession observer (listConnectionLocks pid)+ statsAfter <- fetchTableStats executor+ let newLocks =+ Set.fromList after+ `Set.difference` Set.fromList before+ impacts = computeImpacts existing statsBefore statsAfter+ findings = lockFindings range newLocks impacts+ execSimple executor "RELEASE SAVEPOINT lint_deploy_sp"+ go existing statsAfter (findings <> acc) rest+ StmtNonTransactional -> do+ tryRollbackSavepoint executor+ go existing statsBefore (warnNonTransactional stmt : acc) rest+ StmtError msg -> do+ tryRollbackSavepoint executor+ go existing statsBefore (warnExecutionError stmt msg : acc) rest+++tryRollbackSavepoint :: PQ.Connection -> IO ()+tryRollbackSavepoint pq = do+ -- ROLLBACK TO returns commands to "released" state on success; if+ -- the savepoint is gone we silently move on.+ _ <- tryAny do+ execSimple pq "ROLLBACK TO SAVEPOINT lint_deploy_sp"+ execSimple pq "RELEASE SAVEPOINT lint_deploy_sp"+ pure ()+++data StmtOutcome+ = StmtOk+ | StmtNonTransactional+ | StmtError Text+++-- | Execute the candidate statement on the executor. We classify the+-- failure reason for non-transactional statements so the diagnostic+-- pipeline can WARN-instead-of-BLOCK.+runStatement :: PQ.Connection -> Stmt -> IO StmtOutcome+runStatement executor Stmt{text} = do+ let bytes = encodeUtf8 text+ result <- tryExecSimple executor bytes+ case result of+ Right () -> pure StmtOk+ Left msg ->+ pure+ $ if "cannot run inside a transaction block" `T.isInfixOf` msg+ then StmtNonTransactional+ else StmtError msg+++warnNonTransactional :: Stmt -> Finding+warnNonTransactional Stmt{range} =+ Finding+ { range+ , severity = SeverityInfo+ , rule = DeployNonTransactional+ , title = "Statement cannot be inspected dynamically (non-transactional DDL)"+ , detail = "Static lock-class classification still applies."+ , suppressedBy = Nothing+ }+++-- | A statement the dynamic pass could not execute. After the+-- cumulative deploy lands each preceding change for real, a genuinely+-- correct migration's dependencies always exist, so this is+-- informational ("we couldn't dynamically verify this one"), not a+-- problem with the migration — the static rules still applied.+warnExecutionError :: Stmt -> Text -> Finding+warnExecutionError Stmt{range} msg =+ Finding+ { range+ , severity = SeverityInfo+ , rule = DeployStatementNotObserved+ , title = "The dynamic pass could not execute this statement (static checks still applied)"+ , detail = msg+ , suppressedBy = Nothing+ }+++-- | One finding per (table, lock-mode) the statement acquired, with the+-- lock's /impact/ folded in: whether the statement also rewrote the+-- table (relfilenode changed) or scanned it under the lock+-- (transaction-local sequential-scan counter rose). That impact is what+-- decides severity and the SAFE/RISKY reason, so a catalog-only+-- AccessExclusiveLock reads very differently from one held across a+-- full-table scan or rewrite.+lockFindings :: SourceRange -> Set PidLock -> Map TableName RewriteImpact -> [Finding]+lockFindings range newLocks impacts =+ let lockBased =+ [ observedLockFinding range tname cls (Map.findWithDefault NoImpact (TableName tname) impacts)+ | PidLock{table = TableName tname, mode} <- Set.toList newLocks+ , Just cls <- [parseLockMode mode]+ ]+ covered = Set.fromList [t | PidLock{table = t} <- Set.toList newLocks]+ -- A table the statement rewrote/scanned without our observing a+ -- \*new* lock (the lock was taken by an earlier statement in the+ -- same change) still warrants a finding; such operations always+ -- run under AccessExclusiveLock.+ extra =+ [ observedLockFinding range tname AccessExclusive impact+ | (TableName tname, impact) <- Map.toList impacts+ , not (Set.member (TableName tname) covered)+ ]+ in lockBased <> extra+++observedLockFinding :: SourceRange -> Text -> LockClass -> RewriteImpact -> Finding+observedLockFinding range tname cls impact =+ Finding+ { range+ , severity = severityFor LockProfile{lockClass = cls, rewriteImpact = impact}+ , rule = LockObserved cls+ , title = lockTitle cls impact tname+ , detail = lockDetail cls impact+ , suppressedBy = Nothing+ }+++lockTitle :: LockClass -> RewriteImpact -> Text -> Text+lockTitle cls impact tname =+ let base = "Acquired " <> lockClassName cls <> "Lock on " <> tname+ in case (cls, impact) of+ (AccessExclusive, TableRewrite) -> base <> " and rewrote the table"+ (AccessExclusive, TableScan) -> base <> " while scanning the whole table"+ (AccessExclusive, NoImpact) -> base <> " (catalog-only)"+ _ -> base+++lockDetail :: LockClass -> RewriteImpact -> Text+lockDetail AccessExclusive TableRewrite =+ "RISKY: a physical table rewrite runs under AccessExclusiveLock; every transaction touching the table blocks until the rewrite finishes. Use an expand/contract migration instead."+lockDetail AccessExclusive TableScan =+ "RISKY: the whole table is scanned while AccessExclusiveLock is held, so every transaction touching it blocks for the duration of the scan. Split the validation out (e.g. ADD CONSTRAINT ... NOT VALID, then VALIDATE CONSTRAINT, which scans under a weaker lock)."+lockDetail AccessExclusive NoImpact =+ "SAFE: AccessExclusiveLock held only briefly for a catalog-only change (no scan, no rewrite)."+lockDetail _ _ = ""+++-- | Per-table impact of a single statement, derived from before/after+-- snapshots: a changed relfilenode means a physical rewrite; otherwise+-- a rise in the transaction's sequential-scan /count/ means the+-- statement scanned the table (e.g. @SET NOT NULL@, @VALIDATE+-- CONSTRAINT@, @ADD CONSTRAINT@ that validates) while holding its lock.+--+-- We count scans, not tuples read, on purpose: the linter's database is+-- schema-only (no rows), so a tuple-read delta would be zero and these+-- scans would look free. The scan-count counter still ticks when the+-- planner executes a sequential scan over an empty relation, so the+-- dangerous "scan under AccessExclusiveLock" shape is caught regardless+-- of data volume. Only non-'NoImpact' tables are returned.+--+-- Tables whose OID is not in @existing@ were created by this file; they+-- are invisible to other transactions until commit, so they are skipped.+computeImpacts :: Set RelOid -> Map TableName TableStat -> Map TableName TableStat -> Map TableName RewriteImpact+computeImpacts existing before after =+ Map.fromList+ [ (tname, impact)+ | (tname, a) <- Map.toList after+ , Set.member a.relOid existing+ , Just b <- [Map.lookup tname before]+ , let impact = classify b a+ , impact /= NoImpact+ ]+ where+ classify b a+ | b.relFileNode /= a.relFileNode = TableRewrite+ | a.seqScans > b.seqScans = TableScan+ | otherwise = NoImpact+++-- ---------------------------------------------------------------------+-- libpq helpers (executor connection)+-- ---------------------------------------------------------------------++newtype DeployQueryError = DeployQueryError Text+ deriving stock (Show)+++instance Exception DeployQueryError+++-- | Run a simple-query statement on the executor. Throws on error.+execSimple :: PQ.Connection -> ByteString -> IO ()+execSimple conn sql = do+ result <- tryExecSimple conn sql+ case result of+ Right () -> pure ()+ Left msg -> throwIO (DeployQueryError (decodeUtf8Lenient sql <> ": " <> msg))+++-- | Variant of 'execSimple' that returns a 'Left' on PG-side errors+-- instead of throwing. Used for the candidate statement, whose failure+-- is informational.+tryExecSimple :: PQ.Connection -> ByteString -> IO (Either Text ())+tryExecSimple conn sql = do+ result <- execTuples conn sql+ pure (void result)+++-- | Run a simple-query statement and return the 'PQ.Result' for+-- callers that need to read rows. The result is wrapped in 'Either Text'+-- so PG-side errors carry their message instead of an opaque 'Nothing'.+execTuples :: PQ.Connection -> ByteString -> IO (Either Text PQ.Result)+execTuples conn sql = do+ mResult <- PQ.exec conn sql+ case mResult of+ Nothing -> do+ mErr <- PQ.errorMessage conn+ pure (Left (maybe "libpq: no result" decodeUtf8Lenient mErr))+ Just result -> do+ status <- PQ.resultStatus result+ case status of+ PQ.CommandOk -> pure (Right result)+ PQ.TuplesOk -> pure (Right result)+ PQ.EmptyQuery -> pure (Right result)+ _ -> do+ mErr <- PQ.resultErrorMessage result+ pure (Left (maybe (tshow status) decodeUtf8Lenient mErr))+++-- | Run an exec, throw on error, return rows; the inverse of+-- 'tryExecSimple' for queries we cannot let fail (catalog reads).+execTuplesOrThrow :: Text -> PQ.Connection -> ByteString -> IO PQ.Result+execTuplesOrThrow context conn sql = do+ result <- execTuples conn sql+ case result of+ Right r -> pure r+ Left msg -> throwIO (DeployQueryError (context <> ": " <> msg))+++-- | The statement budget the linter gives its own work.+setLinterStatementTimeout :: ByteString+setLinterStatementTimeout = "SET LOCAL statement_timeout = '60s'"+++-- | Run one of the linter's own queries under the linter's statement budget,+-- then hand the session back whatever the migration had set.+--+-- The candidate statement runs on this connection and can change+-- @statement_timeout@ for the rest of the transaction, and migrations that+-- take locks routinely do: @select set_config('statement_timeout', '50ms', false)@+-- as a change's first line keeps a blocked @ALTER@ from queueing every query+-- behind it. That 50ms then applies to 'fetchTableStats', which reads+-- @pg_class@ for every relation in the database — 68ms for about 1900+-- relations on a CI runner, 22ms on a developer machine. So the linter cancelled+-- its own snapshot and reported it as the migration timing out, on hosts slow+-- enough to cross the line and not on others.+--+-- Restoring the previous value rather than leaving 60s in place keeps the+-- observation honest: a statement that follows one setting a 50ms budget must+-- still run under 50ms, because that is what production will do.+withLinterStatementTimeout :: PQ.Connection -> IO a -> IO a+withLinterStatementTimeout conn action = do+ saved <- fetchStatementTimeout conn+ execSimple conn setLinterStatementTimeout+ action `finally` restore saved+ where+ -- Best-effort: on the exception path the transaction is abandoned anyway,+ -- and a failure to restore must not mask the original error.+ restore saved = void (tryAny (execSimple conn (assignment saved)))+ assignment saved = BS8.concat ["SET LOCAL statement_timeout = '", escapeLiteral saved, "'"]+ escapeLiteral = BS8.intercalate "''" . BS8.split '\''+++fetchStatementTimeout :: PQ.Connection -> IO ByteString+fetchStatementTimeout conn = do+ result <- execTuplesOrThrow "fetchStatementTimeout" conn "select current_setting('statement_timeout')"+ rows <- PQ.ntuples result+ when (rows /= 1)+ $ throwIO (DeployQueryError ("fetchStatementTimeout: expected 1 row, got " <> tshow rows))+ getCellOrThrow "fetchStatementTimeout" result 0 0+++rollback :: PQ.Connection -> IO ()+rollback pq = do+ _ <- tryAny (execSimple pq "ROLLBACK")+ pure ()+++fetchPid :: PQ.Connection -> IO Pid+fetchPid conn = do+ result <- execTuplesOrThrow "fetchPid" conn "SELECT pg_backend_pid()::text"+ rows <- PQ.ntuples result+ when (rows /= 1) $ throwIO (DeployQueryError ("fetchPid: expected 1 row, got " <> tshow rows))+ bs <- getCellOrThrow "fetchPid" result 0 0+ case readMaybe (BS8.unpack bs) of+ Just n -> pure (Pid n)+ Nothing -> throwIO (DeployQueryError ("fetchPid: not an int: " <> decodeUtf8Lenient bs))+++-- | A per-table snapshot the impact diff is computed from: the table's+-- OID (stable across renames), its physical relfilenode (to detect+-- rewrites) and the current transaction's cumulative sequential-scan+-- count for it (to detect scans under the lock, even on the linter's+-- empty tables).+data TableStat = TableStat+ { relOid :: RelOid+ , relFileNode :: RelFileNode+ , seqScans :: Int64+ }+++newtype RelOid = RelOid Int64+ deriving stock (Eq, Ord)+++fetchTableStats :: PQ.Connection -> IO (Map TableName TableStat)+fetchTableStats conn = withLinterStatementTimeout conn do+ result <- execTuplesOrThrow "fetchTableStats" conn tableStatsSql+ rows <- PQ.ntuples result+ Map.fromList <$> forM (rowIndices rows) \r -> do+ name <- getCellOrThrow "fetchTableStats (relname)" result r 0+ node <- getCellOrThrow "fetchTableStats (filenode)" result r 1+ scan <- getCellOrThrow "fetchTableStats (seq_scan)" result r 2+ oid <- getCellOrThrow "fetchTableStats (oid)" result r 3+ rel <- parseInt64 "filenode" node+ sc <- parseInt64 "seq_scan" scan+ o <- parseInt64 "oid" oid+ pure+ ( TableName (decodeUtf8Lenient name)+ , TableStat{relOid = RelOid o, relFileNode = RelFileNode rel, seqScans = sc}+ )+ where+ parseInt64 :: Text -> ByteString -> IO Int64+ parseInt64 label bs = case readMaybe (BS8.unpack bs) of+ Just n -> pure n+ Nothing ->+ throwIO (DeployQueryError ("fetchTableStats: bad " <> label <> ": " <> decodeUtf8Lenient bs))+++-- | Every @language sql@ function whose current definition Postgres now+-- rejects, keyed by signature, with the error it raises.+--+-- Postgres checks a SQL function's body, including that its result matches+-- the declared return type, only when the function is created. A later+-- change to a type or table the body uses is not re-checked, so a function+-- can be left broken until it is next called. Re-running each function's+-- own @pg_get_functiondef@ surfaces that without calling it. Every+-- re-creation is undone in its own subtransaction, and the outer+-- transaction is rolled back.+brokenSqlFunctions :: DeploySettings -> IO (Map Text Text)+brokenSqlFunctions settings =+ withConnection settings \conn ->+ withPqConnection conn \pq -> do+ execSimple pq "BEGIN"+ execSimple pq setLinterStatementTimeout+ execSimple pq sqlFunctionCheckSql+ result <-+ execTuplesOrThrow+ "brokenSqlFunctions"+ pq+ "select signature, error from pg_temp.lint_broken_sql_functions()"+ rows <- PQ.ntuples result+ broken <- forM (rowIndices rows) \r -> do+ signature <- getCellOrThrow "brokenSqlFunctions (signature)" result r 0+ err <- getCellOrThrow "brokenSqlFunctions (error)" result r 1+ pure (decodeUtf8Lenient signature, decodeUtf8Lenient err)+ rollback pq+ pure (Map.fromList broken)+++-- | A temporary function that re-creates every SQL function from its own+-- definition and returns the ones that fail. @KL001@ is a private SQLSTATE+-- used only to roll back each successful re-creation. Extension-owned+-- functions are skipped: they are not ours to keep consistent.+sqlFunctionCheckSql :: ByteString+sqlFunctionCheckSql =+ """+ create function pg_temp.lint_broken_sql_functions()+ returns table (signature text, error text)+ language plpgsql+ as $fn$+ declare+ f record;+ detail text;+ begin+ for f in+ select p.oid+ from pg_catalog.pg_proc p+ join pg_catalog.pg_namespace n on n.oid = p.pronamespace+ where p.prolang = (select oid from pg_catalog.pg_language where lanname = 'sql')+ and p.prokind in ('f', 'p')+ and n.nspname <> 'information_schema'+ and n.nspname !~ '^pg_'+ and not exists (+ select 1 from pg_catalog.pg_depend d+ where d.classid = 'pg_catalog.pg_proc'::regclass+ and d.objid = p.oid+ and d.deptype = 'e'+ )+ loop+ begin+ execute pg_catalog.pg_get_functiondef(f.oid);+ raise exception using errcode = 'KL001';+ exception+ when sqlstate 'KL001' then+ null;+ when others then+ get stacked diagnostics detail = pg_exception_detail;+ signature := f.oid::regprocedure::text;+ error := sqlerrm || coalesce(' (' || nullif(detail, '') || ')', '');+ return next;+ end;+ end loop;+ end;+ $fn$+ """+++-- | Read a single cell from a 'PQ.Result' or throw with a helpful+-- context label.+getCellOrThrow :: Text -> PQ.Result -> Int32 -> Int32 -> IO ByteString+getCellOrThrow context result row col = do+ mVal <- PQ.getvalue result row col+ maybe (throwIO (DeployQueryError (context <> ": null cell"))) pure mVal+++-- | Per-table relfilenode (for rewrite detection) and the current+-- transaction's sequential-scan count (for scan detection).+--+-- We drive off @pg_class@ and LEFT JOIN @pg_stat_xact_user_tables@:+-- that view only lists tables touched so far this transaction, so a+-- plain join would drop untouched tables and lose their relfilenode+-- baseline. The view's @seq_scan@ is backend-local, in-progress, and+-- ticks the moment a sequential scan executes — before commit and+-- regardless of row count — so a scan-under-lock shows up even on the+-- linter's empty tables. @coalesce@ defaults untouched tables to zero.+tableStatsSql :: ByteString+tableStatsSql =+ """+ select (quote_ident(n.nspname) || '.' || quote_ident(c.relname))::text,+ c.relfilenode::text,+ coalesce(s.seq_scan, 0)::text,+ c.oid::bigint::text+ from pg_catalog.pg_class c+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace+ left join pg_catalog.pg_stat_xact_user_tables s on s.relid = c.oid+ where n.nspname not in ('pg_catalog', 'information_schema', 'pg_toast')+ and n.nspname not like 'pg_temp_%'+ and n.nspname not like 'pg_toast_temp_%'+ and c.relkind in ('r', 'p')+ and c.relfilenode <> 0+ order by 1+ """+++rowIndices :: Int32 -> [Int32]+rowIndices total = [0 .. total - 1]
+ src/Sqint/Deploy/Connection.hs view
@@ -0,0 +1,94 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Thin wrappers around 'Hasql.Connection' so the deploy modules can+-- acquire/release per-purpose connections (executor + observer) without+-- repeating boilerplate. Each dynamic-pass run opens one or two short+-- connections and closes them immediately afterwards; we don't need a+-- pool for what is essentially a CI batch tool.+module Sqint.Deploy.Connection (+ DeploySettings (..),+ parseSettings,+ withConnection,+ withPqConnection,+ runSession,+ ConnectionError (..),+) where++import Data.Text qualified as T+import Hasql.Connection (Connection)+import Hasql.Connection qualified as Conn+import Hasql.Connection.Settings qualified as Settings+import Hasql.Errors qualified+import Hasql.Session (Session)+import Hasql.Session qualified as Session+import Pqi qualified+import Pqi.Ffi qualified+import RIO+++-- | Connection parameters for the dynamic pass. Always supplied as a libpq+-- DSN/URI; the static linter path stays free of this type so we never+-- accidentally require Postgres for pre-commit usage.+newtype DeploySettings = DeploySettings {dsn :: Text}+++-- | Reject empty input and otherwise forward the string to libpq via+-- 'Settings.connectionString', which accepts both @postgres://@ URIs+-- and @key=value@ DSNs. Format validation is deferred to libpq — at+-- this layer any non-empty string is structurally valid; the actual+-- syntactic check happens when 'withConnection' calls @Conn.acquire@.+parseSettings :: String -> Either String DeploySettings+parseSettings input+ | null input = Left "empty connection string"+ | otherwise = Right (DeploySettings (T.pack input))+++data ConnectionError+ = AcquireFailed Text+ | SessionFailed Hasql.Errors.SessionError+ deriving stock (Show)+++instance Exception ConnectionError+++-- | Acquire a connection, run the action, release the connection. Even+-- on exceptions, the connection is released.+withConnection :: DeploySettings -> (Connection -> IO a) -> IO a+withConnection DeploySettings{dsn} =+ bracket acquire Conn.release+ where+ settings = Settings.connectionString dsn++ -- libpq, through pqi's FFI binding: the dynamic pass needs TLS for+ -- a remote database, which pqi's native driver does not offer.+ acquire = do+ result <- Conn.acquire Pqi.Ffi.adapter settings+ case result of+ Right conn -> pure conn+ Left err -> throwIO (AcquireFailed (tshow err))+++-- | Run a 'Session' against a connection, throwing on errors.+runSession :: Connection -> Session a -> IO a+runSession conn s = do+ result <- Conn.use conn s+ case result of+ Right value -> pure value+ Left err -> throwIO (SessionFailed err)+++-- | Borrow the driver connection underlying a hasql connection, for the+-- statements the dynamic pass sends as-is (@EXPLAIN@, savepoints, a whole+-- script through the simple-query protocol) rather than as a prepared+-- 'Session'.+--+-- The hasql connection is locked for the whole callback, so nothing else+-- may use it meanwhile.+withPqConnection :: Connection -> (Pqi.Connection -> IO a) -> IO a+withPqConnection conn act = do+ result <-+ Conn.use+ conn+ (Session.onLibpqConnection \pq -> (,pq) . Right <$> act pq)+ either (throwIO . SessionFailed) pure result
+ src/Sqint/Deploy/Introspector.hs view
@@ -0,0 +1,24 @@+-- | Catalog-introspection types shared between the dynamic pass's executor+-- (raw libpq) and observer (Hasql) sides. The actual queries live next+-- to their consumers — see 'Sqint.Deploy.fetchRelFileNodes'+-- for the executor-side relfilenode snapshot and+-- 'Sqint.Deploy.Observer.listConnectionLocks' for the+-- observer-side @pg_locks@ query.+module Sqint.Deploy.Introspector (+ Pid (..),+ TableName (..),+ RelFileNode (..),+) where++import RIO+++newtype Pid = Pid Int32+++newtype TableName = TableName Text+ deriving stock (Eq, Ord)+++newtype RelFileNode = RelFileNode Int64+ deriving stock (Eq)
+ src/Sqint/Deploy/Observer.hs view
@@ -0,0 +1,66 @@+{-# LANGUAGE MultilineStrings #-}++-- | Query @pg_locks@ from a side connection to learn what locks a target+-- backend (the executor) is currently holding. Used immediately after+-- the executor runs the candidate statement and before its transaction+-- ends — the locks acquired by the statement are still in+-- @pg_locks@.+module Sqint.Deploy.Observer (+ listConnectionLocks,+ PidLock (..),+) where++import Data.Vector qualified as Vector+import Hasql.Decoders qualified as Decoders+import Hasql.Encoders qualified as Encoders+import Hasql.Session (Session)+import Hasql.Session qualified as Session+import Hasql.Statement (Statement)+import Hasql.Statement qualified as Statement+import RIO+import Sqint.Deploy.Introspector (Pid (..), TableName (..))+++data PidLock = PidLock+ { table :: TableName+ , mode :: Text+ }+ deriving stock (Eq, Ord)+++-- | List the relation-level locks held by a specific backend+-- ('Pid'). Restricted to relations outside system schemas so we don't+-- surface noise from catalog tables that every transaction touches.+listConnectionLocks :: Pid -> Session [PidLock]+listConnectionLocks (Pid pid) = do+ rows <- Session.statement pid locksHeldBy+ pure+ $ [ PidLock{table = TableName t, mode = m}+ | (t, m) <- Vector.toList rows+ ]+++locksHeldBy :: Statement Int32 (Vector (Text, Text))+locksHeldBy =+ Statement.preparable+ """+ select+ (quote_ident(n.nspname) || '.' || quote_ident(c.relname))::text+ , l.mode::text+ from pg_catalog.pg_locks l+ join pg_catalog.pg_class c+ on c.oid = l.relation+ join pg_catalog.pg_namespace n+ on n.oid = c.relnamespace+ where l.pid = $1::int4+ and n.nspname not in ('pg_catalog', 'information_schema', 'pg_toast')+ and n.nspname not like 'pg_temp_%'+ and n.nspname not like 'pg_toast_temp_%'+ and c.relkind in ('r', 'p')+ and l.locktype = 'relation'+ and l.granted+ """+ (Encoders.param (Encoders.nonNullable Encoders.int4))+ (Decoders.rowVector ((,) <$> text <*> text))+ where+ text = Decoders.column (Decoders.nonNullable Decoders.text)
+ src/Sqint/Deploy/PlanCheck.hs view
@@ -0,0 +1,649 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | Plan-level cast check: prove a cast actually defeats an index by+-- comparing two @EXPLAIN@ plans of the same statement — one with the+-- cast, one with the cast removed.+--+-- For each embedded @PLpgSQL_stmt_execsql@ that "Sqint.Plpgsql"+-- surfaces, we:+--+-- 1. Walk the libpg_query parse tree for every @TypeCast@ whose arg+-- is a @ColumnRef@.+-- 2. If none, skip — this rule only has something to say about+-- column-side casts.+-- 3. Substitute every @NEW.x@ / @OLD.x@ 'ColumnRef' with a @$N@+-- 'ParamRef' so the embedded DML can be planned outside its+-- trigger context.+-- 4. Build two variants of the statement: the original, and one+-- where every @TypeCast@ over a @ColumnRef@ has been replaced+-- with the bare 'ColumnRef'. Both go through+-- @pg_query_deparse_protobuf@ so the SQL is faithful to whatever+-- Postgres's regular SQL grammar accepts.+-- 5. Run @EXPLAIN (FORMAT JSON, COSTS OFF, GENERIC_PLAN)@ on both+-- variants. @GENERIC_PLAN@ is what lets us plan a query whose+-- parameters are unbound — without it Postgres compiles against+-- @NULL@ and short-circuits to @One-Time Filter: "false"@,+-- producing a plan that's useless for our diff.+-- 6. Walk both plan trees. A finding is emitted iff, for the same+-- table, the cast variant picks @Seq Scan@ / @Parallel Seq Scan@+-- and the no-cast variant picks any flavour of index scan.+--+-- The static @index/cast-on-column@ WARN still fires for every cast — the+-- two rules layer: WARN says "this looks suspicious", BLOCK says+-- "Postgres confirms the index isn't used".+module Sqint.Deploy.PlanCheck (+ checkFile,++ -- * Internals exposed for the test-suite+ Plan (..),+ Candidate (..),+ diffPlans,+ stripPartitionSuffix,+) where++import Data.Aeson qualified as Aeson+import Data.Char (isDigit)+import Data.Map.Strict qualified as Map+import Data.Monoid (Any (..))+import Data.ProtoLens (defMessage)+import Data.Set qualified as Set+import Data.String.Interpolate (iii)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import Data.Text.IO qualified as Text.IO+import PgQuery qualified as Pg+import Pqi qualified as PQ+import RIO+import RIO.State (State, evalState, state)+import Sqint.Deploy.Connection (DeploySettings, withConnection, withPqConnection)+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Plpgsql (EmbeddedSql (..), extractEmbeddedSql)+import Sqint.Rule (Rule (..))+++-- | Inspect every cast-bearing DML in @path@. Returns one BLOCK+-- finding per candidate whose differential EXPLAIN confirms an+-- index would be usable absent the column-side cast, plus one INFO+-- finding per candidate that couldn't be checked (deparse failure,+-- libpq error, etc.) so the failure surface is visible.+checkFile :: DeploySettings -> FilePath -> IO [Finding]+checkFile settings path = do+ src <- Text.IO.readFile path+ candidates <- collectCandidates path src+ if null candidates+ then pure []+ else withConnection settings \conn ->+ withPqConnection conn \pq ->+ concat <$> traverse (checkCandidate pq) candidates+++-- | One DML the plan checker considers, located in the original+-- source so findings carry an accurate 'SourceRange'.+data Candidate = Candidate+ { sql :: Text+ , range :: SourceRange+ }+++collectCandidates :: FilePath -> Text -> IO [Candidate]+collectCandidates path src = do+ embeds <- extractEmbeddedSql src+ pure+ [ Candidate+ { sql = e.sql+ , range = rangeAtLine path e.fileLine+ }+ | e <- embeds+ ]+++rangeAtLine :: FilePath -> Int -> SourceRange+rangeAtLine path line =+ SourceRange+ { path+ , startLine = line+ , startCol = 1+ , endLine = line+ , endCol = 1+ }+++-- ---------------------------------------------------------------------+-- Per-candidate check+-- ---------------------------------------------------------------------++checkCandidate :: PQ.Connection -> Candidate -> IO [Finding]+checkCandidate pq cand = do+ parsed <- Pg.parseSql (T.unpack cand.sql)+ case parsed of+ Left msg -> pure [skippedFinding cand ("libpg_query parse failed: " <> T.pack msg)]+ Right tree+ | not (hasColumnCast tree) -> pure []+ | otherwise -> runDifferential pq cand tree+++hasColumnCast :: Pg.ParseResult -> Bool+hasColumnCast tree =+ any (nodeHasColumnCast . view Pg.stmt) (tree ^.. Pg.stmts . traverse)+++nodeHasColumnCast :: Pg.Node -> Bool+nodeHasColumnCast node+ | Just tc <- view Pg.maybe'typeCast node+ , isColumnRef (tc ^. Pg.arg) =+ True+ | otherwise =+ getAny+ . getConst+ $ descendNode (Const . Any . nodeHasColumnCast) node+++isColumnRef :: Pg.Node -> Bool+isColumnRef n = isJust (view Pg.maybe'columnRef n)+++runDifferential :: PQ.Connection -> Candidate -> Pg.ParseResult -> IO [Finding]+runDifferential pq cand tree = do+ let treeWithParams = substituteNewOld tree+ treeNoCast = stripColumnCastsTree treeWithParams+ eOrig <- explainSql pq treeWithParams+ eNoCast <- explainSql pq treeNoCast+ case (eOrig, eNoCast) of+ (Right pOrig, Right pNoCast) ->+ pure (diffPlans cand pOrig pNoCast)+ (Left msg, _) -> pure [skippedFinding cand msg]+ (_, Left msg) -> pure [skippedFinding cand msg]+++skippedFinding :: Candidate -> Text -> Finding+skippedFinding cand msg =+ Finding+ { range = cand.range+ , severity = SeverityInfo+ , rule = IndexPlanCheckSkipped+ , title = "Plan-level cast check skipped for this statement"+ , detail =+ [iii|+ The dynamic plan diff could not run on this statement; the+ static index/cast-on-column warning still applies. Reason:+ #{msg}+ |]+ , suppressedBy = Nothing+ }+++-- ---------------------------------------------------------------------+-- Single recursive descent — used for both pure and stateful walks+-- ---------------------------------------------------------------------++-- | Apply an effectful transformation to every immediate 'Pg.Node'+-- child of the input 'Pg.Node', preserving the oneof discriminator.+-- Callers recurse by passing themselves as @f@; this function only+-- handles one level of descent.+--+-- 'Applicative' is enough — 'mapNode' below upgrades to 'Monad' for+-- bottom-up traversals that depend on the children's rewritten form.+descendNode :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.Node -> f Pg.Node+descendNode f node+ | Just v <- view Pg.maybe'selectStmt node = setSelect <$> descendSelect f v+ | Just v <- view Pg.maybe'updateStmt node = setUpdate <$> descendUpdate f v+ | Just v <- view Pg.maybe'deleteStmt node = setDelete <$> descendDelete f v+ | Just v <- view Pg.maybe'insertStmt node = setInsert <$> descendInsert f v+ | Just v <- view Pg.maybe'aExpr node = setAExpr <$> descendAExpr f v+ | Just v <- view Pg.maybe'boolExpr node = setBoolExpr <$> descendBoolExpr f v+ | Just v <- view Pg.maybe'funcCall node = setFuncCall <$> descendFuncCall f v+ | Just v <- view Pg.maybe'typeCast node = setTypeCast <$> descendTypeCast f v+ | Just v <- view Pg.maybe'caseExpr node = setCaseExpr <$> descendCaseExpr f v+ | Just v <- view Pg.maybe'caseWhen node = setCaseWhen <$> descendCaseWhen f v+ | Just v <- view Pg.maybe'coalesceExpr node = setCoalesce <$> descendCoalesce f v+ | Just v <- view Pg.maybe'nullTest node = setNullTest <$> descendNullTest f v+ | Just v <- view Pg.maybe'subLink node = setSubLink <$> descendSubLink f v+ | Just v <- view Pg.maybe'list node = setList <$> descendList f v+ | Just v <- view Pg.maybe'resTarget node = setResTarget <$> descendResTarget f v+ | otherwise = pure node+ where+ setSelect v = node & Pg.maybe'selectStmt .~ Just v+ setUpdate v = node & Pg.maybe'updateStmt .~ Just v+ setDelete v = node & Pg.maybe'deleteStmt .~ Just v+ setInsert v = node & Pg.maybe'insertStmt .~ Just v+ setAExpr v = node & Pg.maybe'aExpr .~ Just v+ setBoolExpr v = node & Pg.maybe'boolExpr .~ Just v+ setFuncCall v = node & Pg.maybe'funcCall .~ Just v+ setTypeCast v = node & Pg.maybe'typeCast .~ Just v+ setCaseExpr v = node & Pg.maybe'caseExpr .~ Just v+ setCaseWhen v = node & Pg.maybe'caseWhen .~ Just v+ setCoalesce v = node & Pg.maybe'coalesceExpr .~ Just v+ setNullTest v = node & Pg.maybe'nullTest .~ Just v+ setSubLink v = node & Pg.maybe'subLink .~ Just v+ setList v = node & Pg.maybe'list .~ Just v+ setResTarget v = node & Pg.maybe'resTarget .~ Just v+++descendSelect :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.SelectStmt -> f Pg.SelectStmt+descendSelect f s =+ update+ <$> f (s ^. Pg.whereClause)+ <*> f (s ^. Pg.havingClause)+ <*> traverse f (s ^.. Pg.targetList . traverse)+ <*> traverse f (s ^.. Pg.fromClause . traverse)+ where+ update w h t fr =+ s+ & Pg.whereClause+ .~ w+ & Pg.havingClause+ .~ h+ & Pg.targetList+ .~ t+ & Pg.fromClause+ .~ fr+++descendUpdate :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.UpdateStmt -> f Pg.UpdateStmt+descendUpdate f u =+ update+ <$> f (u ^. Pg.whereClause)+ <*> traverse f (u ^.. Pg.targetList . traverse)+ <*> traverse f (u ^.. Pg.fromClause . traverse)+ <*> traverse f (u ^.. Pg.maybe'returningClause . traverse . Pg.exprs . traverse)+ where+ update w t fr r =+ u+ & Pg.whereClause+ .~ w+ & Pg.targetList+ .~ t+ & Pg.fromClause+ .~ fr+ & Pg.maybe'returningClause+ . traverse+ . Pg.exprs+ .~ r+++descendDelete :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.DeleteStmt -> f Pg.DeleteStmt+descendDelete f d =+ update+ <$> f (d ^. Pg.whereClause)+ <*> traverse f (d ^.. Pg.usingClause . traverse)+ <*> traverse f (d ^.. Pg.maybe'returningClause . traverse . Pg.exprs . traverse)+ where+ update w using r =+ d+ & Pg.whereClause+ .~ w+ & Pg.usingClause+ .~ using+ & Pg.maybe'returningClause+ . traverse+ . Pg.exprs+ .~ r+++descendInsert :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.InsertStmt -> f Pg.InsertStmt+descendInsert f i =+ update+ <$> f (i ^. Pg.selectStmt)+ <*> traverse f (i ^.. Pg.maybe'returningClause . traverse . Pg.exprs . traverse)+ where+ update sel r = i & Pg.selectStmt .~ sel & Pg.maybe'returningClause . traverse . Pg.exprs .~ r+++descendAExpr :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.A_Expr -> f Pg.A_Expr+descendAExpr f e =+ (\l r -> e & Pg.lexpr .~ l & Pg.rexpr .~ r)+ <$> f (e ^. Pg.lexpr)+ <*> f (e ^. Pg.rexpr)+++descendBoolExpr :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.BoolExpr -> f Pg.BoolExpr+descendBoolExpr f e =+ (\xs -> e & Pg.args .~ xs) <$> traverse f (e ^.. Pg.args . traverse)+++descendFuncCall :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.FuncCall -> f Pg.FuncCall+descendFuncCall f e =+ (\xs -> e & Pg.args .~ xs) <$> traverse f (e ^.. Pg.args . traverse)+++descendTypeCast :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.TypeCast -> f Pg.TypeCast+descendTypeCast f tc =+ (\a -> tc & Pg.arg .~ a) <$> f (tc ^. Pg.arg)+++descendCaseExpr :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.CaseExpr -> f Pg.CaseExpr+descendCaseExpr f e =+ (\a xs d -> e & Pg.arg .~ a & Pg.args .~ xs & Pg.defresult .~ d)+ <$> f (e ^. Pg.arg)+ <*> traverse f (e ^.. Pg.args . traverse)+ <*> f (e ^. Pg.defresult)+++descendCaseWhen :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.CaseWhen -> f Pg.CaseWhen+descendCaseWhen f cw =+ (\e r -> cw & Pg.expr .~ e & Pg.result .~ r)+ <$> f (cw ^. Pg.expr)+ <*> f (cw ^. Pg.result)+++descendCoalesce :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.CoalesceExpr -> f Pg.CoalesceExpr+descendCoalesce f e =+ (\xs -> e & Pg.args .~ xs) <$> traverse f (e ^.. Pg.args . traverse)+++descendNullTest :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.NullTest -> f Pg.NullTest+descendNullTest f e =+ (\a -> e & Pg.arg .~ a) <$> f (e ^. Pg.arg)+++descendSubLink :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.SubLink -> f Pg.SubLink+descendSubLink f e =+ (\t s -> e & Pg.testexpr .~ t & Pg.subselect .~ s)+ <$> f (e ^. Pg.testexpr)+ <*> f (e ^. Pg.subselect)+++descendList :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.List -> f Pg.List+descendList f l =+ (\xs -> l & Pg.items .~ xs) <$> traverse f (l ^.. Pg.items . traverse)+++descendResTarget :: Applicative f => (Pg.Node -> f Pg.Node) -> Pg.ResTarget -> f Pg.ResTarget+descendResTarget f rt =+ (\v -> rt & Pg.val .~ v) <$> f (rt ^. Pg.val)+++-- | Bottom-up node traversal. Children are rewritten first, then+-- the function is applied to the (already-rewritten) node.+mapNode :: Monad m => (Pg.Node -> m Pg.Node) -> Pg.Node -> m Pg.Node+mapNode f node = descendNode (mapNode f) node >>= f+++traverseStmts :: Monad m => (Pg.Node -> m Pg.Node) -> Pg.ParseResult -> m Pg.ParseResult+traverseStmts f tree = do+ rewritten <- traverse rewriteRaw (tree ^.. Pg.stmts . traverse)+ pure (tree & Pg.stmts .~ rewritten)+ where+ rewriteRaw r = do+ n <- mapNode f (r ^. Pg.stmt)+ pure (r & Pg.stmt .~ n)+++-- ---------------------------------------------------------------------+-- AST mutations+-- ---------------------------------------------------------------------++-- | Replace every @NEW.<col>@ / @OLD.<col>@ 'ColumnRef' with a+-- numbered @$N@ 'ParamRef'. Numbering starts at 1 and follows+-- source order; the leftover counter is discarded — we don't need+-- the (param, column) ledger because @EXPLAIN (GENERIC_PLAN)@ types+-- parameters from how they're used in the query.+substituteNewOld :: Pg.ParseResult -> Pg.ParseResult+substituteNewOld tree = evalState (traverseStmts substituteOne tree) 1+++substituteOne :: Pg.Node -> State Int32 Pg.Node+substituteOne node =+ case view Pg.maybe'columnRef node of+ Just cr | newOrOld cr -> paramRefNode <$> nextParam+ _ -> pure node+++nextParam :: State Int32 Int32+nextParam = state \i -> (i, i + 1)+++-- | A 'Pg.ColumnRef' refers to @NEW@/@OLD@ when it has exactly two+-- @String@ field parts and the first is @"new"@ or @"old"@+-- (case-insensitive).+newOrOld :: Pg.ColumnRef -> Bool+newOrOld cr =+ case cr ^.. Pg.fields . traverse of+ [a, _] | Just alias <- stringVal a -> T.toLower alias `elem` ["new", "old"]+ _ -> False+++stringVal :: Pg.Node -> Maybe Text+stringVal n = view Pg.sval <$> view Pg.maybe'string n+++paramRefNode :: Int32 -> Pg.Node+paramRefNode n =+ defMessage & Pg.paramRef .~ (defMessage & Pg.number .~ n)+++-- | Apply 'stripColumnCasts' to every statement in the parse tree.+-- This is the pure, top-down walker — the only mutation is replacing+-- a @TypeCast(ColumnRef)@ with its bare 'ColumnRef'.+stripColumnCastsTree :: Pg.ParseResult -> Pg.ParseResult+stripColumnCastsTree = runIdentity . traverseStmts (Identity . stripColumnCasts)+++stripColumnCasts :: Pg.Node -> Pg.Node+stripColumnCasts node+ | Just tc <- view Pg.maybe'typeCast node+ , isColumnRef (tc ^. Pg.arg) =+ tc ^. Pg.arg+ | otherwise =+ runIdentity (descendNode (Identity . stripColumnCasts) node)+++-- ---------------------------------------------------------------------+-- EXPLAIN+-- ---------------------------------------------------------------------++-- | Deparse the tree and run @EXPLAIN (FORMAT JSON, COSTS OFF,+-- GENERIC_PLAN)@ directly on it. @GENERIC_PLAN@ tells Postgres to+-- build a plan whose parameters are unbound — exactly the case we+-- want, because a plan compiled against a specific @NULL@ value+-- short-circuits to @One-Time Filter: false@ instead of choosing+-- between Seq Scan / Index Scan.+explainSql :: PQ.Connection -> Pg.ParseResult -> IO (Either Text Plan)+explainSql pq tree = do+ deparsed <- Pg.deparseProtobuf tree+ case deparsed of+ Left e -> pure (Left ("deparse: " <> T.pack e))+ Right sql -> do+ let stmt =+ "EXPLAIN (FORMAT JSON, COSTS OFF, GENERIC_PLAN) "+ <> stripTrailingSemicolon sql+ result <- exec pq (TE.encodeUtf8 stmt)+ case result of+ Left err -> pure (Left err)+ Right [planBytes] ->+ case Aeson.eitherDecodeStrict planBytes of+ Left e -> pure (Left ("decode plan: " <> T.pack e))+ Right [ExplainEnvelope p] -> pure (Right p)+ Right _ -> pure (Left "EXPLAIN: unexpected plan-array shape")+ Right _ -> pure (Left "EXPLAIN: expected single plan row")+++-- | Run a simple-query statement; on @TuplesOk@ return the first+-- column of every row.+exec :: PQ.Connection -> ByteString -> IO (Either Text [ByteString])+exec pq sql = do+ mResult <- PQ.exec pq sql+ case mResult of+ Nothing -> do+ mErr <- PQ.errorMessage pq+ pure (Left (maybe "libpq: no result" TE.decodeUtf8Lenient mErr))+ Just r -> do+ status <- PQ.resultStatus r+ case status of+ PQ.CommandOk -> pure (Right [])+ PQ.TuplesOk -> do+ nRows <- PQ.ntuples r+ rows <- forM [0 .. nRows - 1] \i ->+ fromMaybe mempty <$> PQ.getvalue r i 0+ pure (Right rows)+ _ -> do+ mErr <- PQ.resultErrorMessage r+ pure (Left (maybe (tshow status) TE.decodeUtf8Lenient mErr))+++stripTrailingSemicolon :: Text -> Text+stripTrailingSemicolon = T.stripEnd . T.dropWhileEnd (== ';') . T.stripEnd+++-- ---------------------------------------------------------------------+-- Typed plan tree+-- ---------------------------------------------------------------------++-- | @EXPLAIN (FORMAT JSON)@ returns @[{"Plan": {…}}]@. We decode the+-- envelope and then operate on the inner 'Plan'.+newtype ExplainEnvelope = ExplainEnvelope Plan+++instance Aeson.FromJSON ExplainEnvelope where+ parseJSON = Aeson.withObject "ExplainEnvelope" \o ->+ ExplainEnvelope <$> o Aeson..: "Plan"+++-- | The subset of a Postgres plan node we use. Other fields (@Costs@,+-- @Filter@, @Async Capable@, …) are intentionally not in the type —+-- if we ever care about them, adding a field here is the right+-- pressure point for the change. The recursive @Plans@ field carries+-- nested subplans (e.g. partition children under an @Append@).+data Plan = Plan+ { nodeType :: Text+ , relationName :: Maybe Text+ , indexName :: Maybe Text+ , plans :: [Plan]+ }+++instance Aeson.FromJSON Plan where+ parseJSON = Aeson.withObject "Plan" \o ->+ Plan+ <$> o+ Aeson..: "Node Type"+ <*> o+ Aeson..:? "Relation Name"+ <*> o+ Aeson..:? "Index Name"+ <*> o+ Aeson..:? "Plans"+ Aeson..!= []+++-- ---------------------------------------------------------------------+-- Plan diff+-- ---------------------------------------------------------------------++-- | A scan node we care about: Seq Scan or any flavour of Index Scan.+data ScanNode = ScanNode+ { nodeType :: Text+ , relation :: Text+ , indexName :: Maybe Text+ }+++-- | Flatten a plan tree to every scan node that names a relation.+collectScans :: Plan -> [ScanNode]+collectScans p =+ here <> concatMap collectScans p.plans+ where+ here = case p.relationName of+ Just rel ->+ [ ScanNode+ { nodeType = p.nodeType+ , relation = rel+ , indexName = p.indexName+ }+ ]+ Nothing -> []+++-- | At most one finding per candidate: when /any/ relation scanned+-- sequentially in the cast plan would be index-scanned in the+-- no-cast plan, emit one BLOCK and name the affected root tables.+--+-- Multi-relation correctness: a relation can appear multiple times in+-- one plan (self-join, @UPDATE … FROM same_table@, Append over+-- partitions). We compare /counts/ per relation rather than relying+-- on @Map.fromList@ to pick a representative — a relation is+-- "defeated" iff the cast plan has strictly more Seq Scans on it+-- than the no-cast plan AND the no-cast plan has at least one Index+-- Scan on the same relation.+diffPlans :: Candidate -> Plan -> Plan -> [Finding]+diffPlans cand orig noCast =+ let origScans = collectScans orig+ noCastScans = collectScans noCast++ countSeqByRelation :: [ScanNode] -> Map Text Int+ countSeqByRelation =+ Map.fromListWith (+) . map (\s -> (s.relation, 1)) . filter (isSeqScan . (.nodeType))++ relationsWithIndexScan :: [ScanNode] -> Set Text+ relationsWithIndexScan = Set.fromList . map (.relation) . filter (isIndexScan . (.nodeType))++ castSeq = countSeqByRelation origScans+ noCastSeq = countSeqByRelation noCastScans+ noCastIndexed = relationsWithIndexScan noCastScans++ defeated =+ [ relation+ | (relation, castN) <- Map.toList castSeq+ , castN > Map.findWithDefault 0 relation noCastSeq+ , Set.member relation noCastIndexed+ ]+ in case defeated of+ [] -> []+ _ -> [defeatedFinding cand defeated]+++isSeqScan :: Text -> Bool+isSeqScan t = t `elem` ["Seq Scan", "Parallel Seq Scan"]+++isIndexScan :: Text -> Bool+isIndexScan t =+ t+ `elem` [ "Index Scan"+ , "Index Only Scan"+ , "Bitmap Index Scan"+ , "Bitmap Heap Scan"+ , "Parallel Index Scan"+ , "Parallel Index Only Scan"+ ]+++defeatedFinding :: Candidate -> [Text] -> Finding+defeatedFinding cand relations =+ let roots = nubOrd (map stripPartitionSuffix relations)+ rootList = T.intercalate ", " roots+ in Finding+ { range = cand.range+ , severity = SeverityBlock+ , rule = IndexDefeated+ , title = "Cast on a column forces a sequential scan on " <> rootList+ , detail =+ [iii|+ Postgres EXPLAIN confirms a cast in this statement prevents+ the planner from using an index on #{rootList}. With the+ column cast removed the planner picks an Index Scan; with+ the cast in place it falls back to Seq Scan. Cast the other+ side of the comparison instead, or add an expression index.+ Suppress with `-- lint:ignore reason="…"` if the cast is+ intentional.+ |]+ , suppressedBy = Nothing+ }+++-- | Reduce a per-partition table name to its root: strip a trailing+-- @_p<digits>@ /or/ @_default@ component. Used so a finding that hits+-- a partitioned table reads as "on @shop.event@" rather than+-- enumerating @event_p20260201@, @…p20260301@, …+stripPartitionSuffix :: Text -> Text+stripPartitionSuffix name+ | Just root <- T.stripSuffix "_default" name = root+ | otherwise = case T.breakOnEnd "_p" name of+ (before, digits)+ | not (T.null before)+ , not (T.null digits)+ , T.all isDigit digits ->+ T.dropEnd 2 before+ _ -> name
+ src/Sqint/DeployTree.hs view
@@ -0,0 +1,78 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | The deploy tree, read once per run.+--+-- Two static rules need a fact about the whole schema rather than about+-- the files a run was asked to lint: which domains carry a CHECK (see+-- "Sqint.Domains") and which tables have a registered deferred+-- backfill (see "Sqint.DeferredDependency"). Each used to walk+-- and read the deploy tree for itself, so every run read every+-- file twice and case-folded them twice — together more than everything+-- else a run does.+module Sqint.DeployTree (+ DeployFile (..),+ loadDeployTree,+) where++import Data.List (sort)+import Data.Text qualified as T+import RIO+import RIO.Directory (doesDirectoryExist, listDirectory)+import RIO.FilePath ((</>))+++data DeployFile = DeployFile+ { path :: !FilePath+ , source :: !Text+ , lowered :: !Text+ -- ^ 'source' case-folded once. Both scanners match lowercase SQL+ -- keywords against it before doing anything expensive with+ -- 'source', and folding five megabytes of migrations per scanner+ -- is not free.+ }+++-- | Every @.sql@ file under @\<databaseRoot\>\/deploy@, sorted, so that+-- whatever is built from it is stable.+--+-- Siblings of @deploy@ (@revert@, @verify@, @test@) are deliberately not+-- read: they hold rewrites and intentionally-invalid SQL that would+-- confuse both scanners.+--+-- A deploy script that is not valid UTF-8 fails the run, loudly and by+-- path. Nothing here would know what to do with another encoding, and+-- skipping such a file quietly+-- would make the rules built on this tree report a clean bill of health+-- for a file they never read.+loadDeployTree :: FilePath -> IO [DeployFile]+loadDeployTree databaseRoot = do+ paths <- sqlFilesUnder (databaseRoot </> "deploy")+ traverse readDeployFile paths+++readDeployFile :: FilePath -> IO DeployFile+readDeployFile path = do+ source <- readFileUtf8 path+ pure DeployFile{path, source, lowered = T.toLower source}+++sqlFilesUnder :: FilePath -> IO [FilePath]+sqlFilesUnder top = do+ exists <- doesDirectoryExist top+ if exists then sqlFilesIn top else pure []+++sqlFilesIn :: FilePath -> IO [FilePath]+sqlFilesIn dir = do+ entries <- listDirectory dir+ concat <$> traverse (classify dir) (sort entries)+++classify :: FilePath -> FilePath -> IO [FilePath]+classify dir entry = do+ let full = dir </> entry+ isDir <- doesDirectoryExist full+ if isDir+ then sqlFilesIn full+ else pure [full | ".sql" `T.isSuffixOf` T.pack entry]
+ src/Sqint/Diagnostic.hs view
@@ -0,0 +1,46 @@+{-# LANGUAGE NoFieldSelectors #-}++module Sqint.Diagnostic (+ Severity (..),+ Finding (..),+ SourceRange (..),+ severityExitCode,+ severityRank,+ isBlocking,+) where++import RIO+import Sqint.Rule (Rule)+import Sqint.Severity (Severity (..), severityRank)+++data SourceRange = SourceRange+ { path :: FilePath+ , startLine :: Int+ , startCol :: Int+ , endLine :: Int+ , endCol :: Int+ }+ deriving stock (Eq, Show)+++data Finding = Finding+ { range :: SourceRange+ , severity :: Severity+ , rule :: Rule+ , title :: Text+ , detail :: Text+ , suppressedBy :: Maybe Text+ }+ deriving stock (Eq, Show)+++isBlocking :: Finding -> Bool+isBlocking f =+ f.severity == SeverityBlock && isNothing f.suppressedBy+++severityExitCode :: [Finding] -> ExitCode+severityExitCode findings+ | any isBlocking findings = ExitFailure 1+ | otherwise = ExitSuccess
+ src/Sqint/Domains.hs view
@@ -0,0 +1,121 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | Discover which PostgreSQL domains have a CHECK constraint.+--+-- The lock-class linter needs this to surface the+-- @ADD COLUMN \<domain-with-CHECK\>@ case: adding a column whose+-- declared type is a CHECK-bearing domain forces PostgreSQL to+-- validate every existing row under @AccessExclusiveLock@. Without+-- the domain set the linter would either emit false positives on+-- harmless typed columns or false negatives on the dangerous ones.+--+-- The loader looks at every @.sql@ file in the deploy tree — not only+-- the files under @deploy/type/@ — because a migration can create a+-- domain inline.+-- Parse failures are surfaced as a @WARN@ finding instead of+-- silently skipping the file, so reviewers know the rule may produce+-- false negatives.+module Sqint.Domains (+ DomainSet (..),+ loadDomainSet,+) where++import Data.Set qualified as Set+import Data.Text qualified as T+import PgQuery qualified as Pg+import RIO+import Sqint.DeployTree (DeployFile (..))+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (Rule (..))+++data DomainSet = DomainSet+ { withCheck :: Set Text+ -- ^ Domain names that have at least one CHECK constraint+ -- attached. Names are lower-cased; the linter compares against+ -- the parsed column type name (also lower-cased) when applying+ -- the rule.+ , parseFailures :: [Finding]+ -- ^ Files we could not parse; tracking them lets the caller+ -- surface a single per-file warning instead of one per+ -- statement.+ }+++-- | Pick the CHECK-bearing domains out of a deploy tree read by+-- "Sqint.DeployTree", which is what confines this to+-- @deploy@ — siblings (@revert/@, @verify/@, @test/@) may hold+-- rewrites or intentionally-invalid SQL and are never read.+loadDomainSet :: [DeployFile] -> IO DomainSet+loadDomainSet deployTree = do+ results <- traverse scanOne deployTree+ pure+ DomainSet+ { withCheck = Set.unions (map (.withCheck) results)+ , parseFailures = concatMap (.parseFailures) results+ }+++scanOne :: DeployFile -> IO DomainSet+scanOne file = do+ -- Skip files that can't define a domain. Sqitch deploy scripts+ -- contain psql client metacommands (`\timing`, `\gset`) and+ -- PG18-only syntax (`GENERATED … VIRTUAL`, top-level COMMIT) that+ -- libpg_query can't read; parsing those just to discover they+ -- have no @CREATE DOMAIN@ wastes work and floods CI with+ -- WARN findings the linter has no real complaint about.+ if not ("create domain" `T.isInfixOf` file.lowered)+ then pure DomainSet{withCheck = mempty, parseFailures = []}+ else do+ result <- Pg.parseSql (T.unpack file.source)+ case result of+ Left err ->+ pure+ DomainSet+ { withCheck = mempty+ , parseFailures = [parseFailure file.path err]+ }+ Right parsed ->+ pure+ DomainSet+ { withCheck = Set.fromList (mapMaybe domainFromStmt (parsed ^.. Pg.stmts . traverse . Pg.stmt))+ , parseFailures = []+ }+++parseFailure :: FilePath -> String -> Finding+parseFailure path err =+ Finding+ { range = SourceRange{path, startLine = 1, startCol = 1, endLine = 1, endCol = 1}+ , -- Informational, not a warning: this fires for pre-existing+ -- domain-definition files the linter can't fully parse, on+ -- every run regardless of what the PR changed, so it is+ -- constant noise rather than something to act on in a given+ -- PR. It still surfaces under --verbose.+ severity = SeverityInfo+ , rule = SetupUnparsableDomainFile+ , title = "could not parse domain source"+ , detail =+ "libpg_query: "+ <> T.pack err+ <> " — the lock-class rule for ADD COLUMN with a domain type may produce "+ <> "false negatives for domains declared in this file."+ , suppressedBy = Nothing+ }+++-- | Pull the (lower-cased) domain name out of a CreateDomainStmt that+-- carries at least one CHECK constraint. Other CONSTR types+-- (NOT NULL, DEFAULT) are not relevant for the rewrite/scan rule.+domainFromStmt :: Pg.Node -> Maybe Text+domainFromStmt node = do+ stmt <- view Pg.maybe'createDomainStmt node+ let constraints =+ mapMaybe+ (view Pg.maybe'constraint)+ (stmt ^.. Pg.constraints . traverse)+ guard (any (\c -> c ^. Pg.contype == Pg.CONSTR_CHECK) constraints)+ case stmt ^.. Pg.domainname . traverse . Pg.string . Pg.sval of+ [] -> Nothing+ parts -> Just (T.toLower (T.intercalate "." parts))
+ src/Sqint/Location.hs view
@@ -0,0 +1,100 @@+{-# LANGUAGE NoFieldSelectors #-}++-- | Turning libpg_query's byte offsets into the lines a finding reports.+--+-- libpg_query reports a statement as starting just past the previous+-- statement's semicolon (or at offset 0 for the first), so the span it+-- gives includes the whitespace and comments in between — the+-- @-- Deploy …@ header, a @-- lint:ignore@ above the statement. A finding+-- placed at that raw offset lands on the line of the previous statement,+-- and an annotation written above or beside the statement it means+-- misses. 'statementRange' skips that leading trivia and covers every line+-- of the statement, which is what suppressions match against.+--+-- Offsets are UTF-8 byte offsets, so all arithmetic here is on the+-- encoded bytes; columns are counted in characters.+module Sqint.Location (+ sourceRangeAt,+ statementRange,+) where++import Data.ByteString qualified as BS+import Data.ByteString.Char8 qualified as BS8+import Data.Text.Encoding qualified as TE+import PgQuery qualified as Pg+import RIO+import Sqint.Diagnostic (SourceRange (..))+++-- | A zero-width range at a byte offset — for a token's own location,+-- which libpg_query reports exactly.+sourceRangeAt :: Integral n => FilePath -> Text -> n -> SourceRange+sourceRangeAt path src offset =+ let (line, col) = position (TE.encodeUtf8 src) (clamp offset)+ in SourceRange{path, startLine = line, startCol = col, endLine = line, endCol = col}+++-- | From a statement's first token to its last non-blank character.+statementRange :: FilePath -> Text -> Pg.RawStmt -> SourceRange+statementRange path src raw =+ let bytes = TE.encodeUtf8 src+ total = BS.length bytes+ loc = min total (clamp (raw ^. Pg.stmtLocation))+ len = clamp (raw ^. Pg.stmtLen)+ -- A length of 0 means "to the end of the input".+ end = if len == 0 then total else min total (loc + len)+ start = case skipTrivia bytes loc end of+ s | s < end -> s+ _ -> loc+ lastChar = max start (trimEnd bytes start end - 1)+ (startLine, startCol) = position bytes start+ (endLine, endCol) = position bytes lastChar+ in SourceRange{path, startLine, startCol, endLine, endCol}+++-- | 1-based line and column of a byte offset.+position :: ByteString -> Int -> (Int, Int)+position bytes offset =+ let before = BS.take offset bytes+ line = 1 + BS8.count '\n' before+ lineStart = maybe 0 (+ 1) (BS8.elemIndexEnd '\n' before)+ col = 1 + BS.length (BS.filter isLeadByte (BS.drop lineStart before))+ in (line, col)+ where+ -- Count characters, not bytes: skip UTF-8 continuation bytes.+ isLeadByte b = b < 0x80 || b >= 0xC0+++-- | The first offset at or after @i@ that is not whitespace or a comment.+skipTrivia :: ByteString -> Int -> Int -> Int+skipTrivia bytes i end+ | i >= end = end+ | isSpaceByte (BS.index bytes i) = skipTrivia bytes (i + 1) end+ | startsWith "--" = skipTrivia bytes (lineEnd (i + 2)) end+ | startsWith "/*" = skipTrivia bytes (blockEnd (1 :: Int) (i + 2)) end+ | otherwise = i+ where+ startsWith p = p `BS.isPrefixOf` BS.drop i bytes+ lineEnd j = maybe end (+ j) (BS8.elemIndex '\n' (BS.drop j (BS.take end bytes)))+ -- PostgreSQL block comments nest.+ blockEnd depth j+ | j >= end = end+ | depth == 0 = j+ | "*/" `BS.isPrefixOf` BS.drop j bytes = blockEnd (depth - 1) (j + 2)+ | "/*" `BS.isPrefixOf` BS.drop j bytes = blockEnd (depth + 1) (j + 2)+ | otherwise = blockEnd depth (j + 1)+++-- | One past the last non-whitespace byte in @[start, end)@.+trimEnd :: ByteString -> Int -> Int -> Int+trimEnd bytes start end+ | end > start && isSpaceByte (BS.index bytes (end - 1)) = trimEnd bytes start (end - 1)+ | otherwise = end+++isSpaceByte :: Word8 -> Bool+isSpaceByte b = b == 0x20 || (b >= 0x09 && b <= 0x0D)+++clamp :: Integral n => n -> Int+clamp n = max 0 (fromIntegral n)
+ src/Sqint/Lock.hs view
@@ -0,0 +1,107 @@+{-# LANGUAGE NoFieldSelectors #-}++-- | Lock-class taxonomy and severity policy.+--+-- Mirrors PostgreSQL's documented lock modes (PG docs ch. 13.3 and the+-- ALTER TABLE notes). Each statement we lint is mapped to a+-- @(LockClass, RewriteImpact)@ pair; the severity policy below turns+-- that pair into a 'Diagnostic.Severity'.+module Sqint.Lock (+ LockClass (..),+ RewriteImpact (..),+ LockProfile (..),+ severityFor,+ parseLockMode,+ lockClassName,+) where++import RIO+import Sqint.Severity (Severity (..))+++-- | PostgreSQL lock modes, listed in the declaration from least to most+-- blocking.+data LockClass+ = AccessShare+ | RowShare+ | RowExclusive+ | ShareUpdateExclusive+ | Share+ | ShareRowExclusive+ | Exclusive+ | AccessExclusive+ deriving stock (Eq, Show)+++-- | What the statement does to row storage.+data RewriteImpact+ = NoImpact+ | TableScan+ | TableRewrite+ deriving stock (Eq)+++data LockProfile = LockProfile+ { lockClass :: LockClass+ , rewriteImpact :: RewriteImpact+ }+++-- | Single severity policy applied to every classified statement.+--+-- What makes a lock dangerous is not its /mode/ but whether it is held+-- while the statement does real work. A lock taken for a catalog-only+-- change (ADD COLUMN without default, ADD CONSTRAINT ... NOT VALID, a+-- NOT-VALID foreign key, DROP COLUMN/INDEX) is released in+-- microseconds and is safe whatever its mode — so 'NoImpact' is always+-- informational. A scan or a rewrite is what holds the lock long+-- enough to block other sessions, and then the mode decides how badly:+-- under AccessExclusiveLock everything blocks (BLOCK); under a+-- write-blocking mode (Share/ShareRowExclusive/Exclusive, e.g. a+-- non-concurrent CREATE INDEX) writers block (WARN); under+-- ShareUpdateExclusive or weaker (e.g. CREATE INDEX CONCURRENTLY,+-- VALIDATE CONSTRAINT) normal traffic proceeds (INFO).+severityFor :: LockProfile -> Severity+severityFor LockProfile{lockClass, rewriteImpact} = case rewriteImpact of+ NoImpact -> SeverityInfo+ TableRewrite -> SeverityBlock+ TableScan -> scanSeverity lockClass+ where+ scanSeverity = \case+ AccessExclusive -> SeverityBlock+ Exclusive -> SeverityWarn+ ShareRowExclusive -> SeverityWarn+ Share -> SeverityWarn+ ShareUpdateExclusive -> SeverityInfo+ RowExclusive -> SeverityInfo+ RowShare -> SeverityInfo+ AccessShare -> SeverityInfo+++-- | Parse a lock-mode name as it appears in @pg_locks.mode@ (the trailing+-- @Lock@ suffix is what the catalog uses, e.g. @AccessExclusiveLock@).+parseLockMode :: Text -> Maybe LockClass+parseLockMode = \case+ "AccessShareLock" -> Just AccessShare+ "RowShareLock" -> Just RowShare+ "RowExclusiveLock" -> Just RowExclusive+ "ShareUpdateExclusiveLock" -> Just ShareUpdateExclusive+ "ShareLock" -> Just Share+ "ShareRowExclusiveLock" -> Just ShareRowExclusive+ "ExclusiveLock" -> Just Exclusive+ "AccessExclusiveLock" -> Just AccessExclusive+ _ -> Nothing+++-- | The catalog spelling of a 'LockClass' (no @Lock@ suffix). Used in+-- diagnostic messages.+lockClassName :: LockClass -> Text+lockClassName = \case+ AccessShare -> "AccessShare"+ RowShare -> "RowShare"+ RowExclusive -> "RowExclusive"+ ShareUpdateExclusive -> "ShareUpdateExclusive"+ Share -> "Share"+ ShareRowExclusive -> "ShareRowExclusive"+ Exclusive -> "Exclusive"+ AccessExclusive -> "AccessExclusive"
+ src/Sqint/NodeWalk.hs view
@@ -0,0 +1,104 @@+{-# LANGUAGE GADTs #-}+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TypeApplications #-}++-- | Generic, complete traversal of the @pg-query@ (proto-lens) parse+-- tree, built entirely from proto-lens field reflection.+--+-- The libpg_query AST is a single recursive @Node@ \"oneof\" with a few+-- hundred variants. A hand-written descent (@case@ on each+-- @maybe'selectStmt@ / @maybe'aExpr@ / … and listing every+-- expression-bearing field) is both boilerplate and lossy: any node+-- position the author forgot to enumerate becomes a silent false+-- negative — which, for a linter, means a dangerous migration passes+-- review.+--+-- proto-lens types have no 'Data'/'Generic' instance, so SYB/uniplate+-- can't traverse them. They do, however, expose enough /reflection/ to+-- build the traversal generically:+--+-- * 'fieldsByTag' enumerates every field of any message;+-- * pattern-matching 'MessageField' recovers a 'Message' dictionary+-- for message-typed fields, which is what lets us recurse without+-- knowing the concrete type;+-- * the 'FieldAccessor' lens pulls the value(s) out.+--+-- To hand a rule a /typed/ node we recover the concrete type by+-- round-tripping the existential through the wire format, guarded on+-- the message name. That needs only 'Message' (no 'Typeable'), and the+-- round-trip only runs for name matches, so the cost is one+-- serialise/parse per node we actually care about.+module Sqint.NodeWalk (+ universeOfType,+) where++import Data.ProtoLens.Encoding (decodeMessage, encodeMessage)+import Data.ProtoLens.Message (+ FieldAccessor (..),+ FieldDescriptor (..),+ FieldTypeDescriptor (..),+ Message,+ fieldsByTag,+ messageName,+ )+import RIO+import RIO.Map qualified as Map+++-- | A proto message whose concrete type is hidden but whose 'Message'+-- dictionary is retained, so it can be recursed into or re-serialised.+data SomeMessage where+ SomeMessage :: Message m => m -> SomeMessage+++-- | Every message of type @t@ reachable from @root@ (inclusive),+-- returned as the concrete, typed value. The proto-lens counterpart of+-- uniplate's @[x | x <- universe root]@ — but it works on types with no+-- 'Data' instance, and is complete by construction (it descends every+-- message-typed field of every node, so no AST variant can hide a+-- match).+universeOfType :: forall t root. (Message t, Message root) => root -> [t]+universeOfType root =+ [t | SomeMessage m <- universeMessages root, Just t <- [downcast m]]+++-- | @root@ plus every transitive sub-message, discovered purely by+-- reflecting over each message's fields.+universeMessages :: Message root => root -> [SomeMessage]+universeMessages root =+ SomeMessage root+ : concatMap (\(SomeMessage child) -> universeMessages child) (childMessages root)+++-- | The immediate sub-messages of any message — the generic+-- replacement for a hand-written @childNodes@.+childMessages :: forall m. Message m => m -> [SomeMessage]+childMessages msg = concatMap descend (Map.elems (fieldsByTag @m))+ where+ descend :: FieldDescriptor m -> [SomeMessage]+ descend (FieldDescriptor _ fieldType accessor) =+ case fieldType of+ -- Matching 'MessageField' brings @Message value@ into+ -- scope, which is what authorises the 'SomeMessage' below.+ MessageField _ -> SomeMessage <$> accessorValues accessor+ _ -> []++ accessorValues :: FieldAccessor m value -> [value]+ accessorValues = \case+ PlainField _ l -> [msg ^. l]+ OptionalField l -> maybeToList (msg ^. l)+ RepeatedField _ l -> msg ^. l+ -- The pg_query AST has no map-of-message fields; if one is ever+ -- added, the value would need recursing here.+ MapField{} -> []+++-- | Recover a concrete message type from an existential by round-+-- tripping through the wire format, guarded on the message name so we+-- never decode an unrelated type. Needs only 'Message'.+downcast :: forall t s. (Message t, Message s) => s -> Maybe t+downcast s+ | messageName (Proxy @s) == messageName (Proxy @t) =+ either (const Nothing) Just (decodeMessage (encodeMessage s))+ | otherwise = Nothing
+ src/Sqint/Output.hs view
@@ -0,0 +1,92 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE NoFieldSelectors #-}++module Sqint.Output (+ OutputFormat (..),+ renderFindings,+) where++import Data.Aeson (object, (.=))+import Data.Aeson qualified as Aeson+import Data.ByteString.Lazy.Char8 qualified as BSL+import Data.String.Interpolate (i)+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (renderRule)+++data OutputFormat = OutputText | OutputJson+ deriving stock (Show)+++-- | Render findings for the chosen format. In text mode, unless+-- @verbose@ is set, only actionable findings (un-suppressed BLOCK/WARN)+-- are printed and the rest are collapsed into a one-line footer — the+-- informational lock observations and suppressed findings are real but+-- rarely what you act on, and printing them all buries the signal.+-- JSON always carries every finding so downstream tooling can filter.+renderFindings :: OutputFormat -> Bool -> [Finding] -> Text+renderFindings OutputJson _ fs =+ TE.decodeUtf8Lenient (BSL.toStrict (Aeson.encode (map findingJson fs)))+renderFindings OutputText verbose fs+ | verbose = T.unlines (map renderText fs)+ | otherwise =+ let visible = filter isActionable fs+ hidden = length fs - length visible+ footer = [hiddenFooter hidden | hidden > 0]+ in T.unlines (map renderText visible <> footer)+++-- | A finding worth surfacing by default: a non-suppressed blocker or+-- warning.+isActionable :: Finding -> Bool+isActionable f = isNothing f.suppressedBy && f.severity `elem` [SeverityBlock, SeverityWarn]+++hiddenFooter :: Int -> Text+hiddenFooter n =+ [i|#{n} informational or suppressed finding#{plural} hidden — pass --verbose to show.|]+ where+ plural :: Text+ plural = if n == 1 then "" else "s"+++renderText :: Finding -> Text+renderText f =+ let prefix = maybe (renderSeverity f.severity) (const "SUPPRESSED") f.suppressedBy+ path = f.range.path+ line = f.range.startLine+ ruleId = renderRule f.rule+ title = f.title+ detailBody = T.intercalate "\n " (T.lines (T.stripEnd f.detail))+ detail :: Text+ detail = if T.null f.detail then "" else [i|\n #{detailBody}|]+ reason :: Text+ reason = maybe "" (\r -> [i|\n reason: #{r}|]) f.suppressedBy+ in [i|#{prefix} #{path}:#{line} [#{ruleId}] #{title}#{detail}#{reason}|]+++renderSeverity :: Severity -> Text+renderSeverity SeverityBlock = "BLOCK"+renderSeverity SeverityWarn = "WARN"+renderSeverity SeverityInfo = "INFO"+++findingJson :: Finding -> Aeson.Value+findingJson f =+ object+ [ "path" .= f.range.path+ , "startLine" .= f.range.startLine+ , "startCol" .= f.range.startCol+ , "endLine" .= f.range.endLine+ , "endCol" .= f.range.endCol+ , "severity" .= renderSeverity f.severity+ , "ruleId" .= renderRule f.rule+ , "title" .= f.title+ , "detail" .= f.detail+ , "suppressed" .= isJust f.suppressedBy+ , "suppressedReason" .= f.suppressedBy+ ]
+ src/Sqint/PgAst.hs view
@@ -0,0 +1,243 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | DDL lock-class detection via @libpg_query@.+--+-- Walks the protobuf parse tree returned by @pg-query@ and classifies+-- each top-level statement by 'LockProfile' (lock class + rewrite+-- impact). Severity comes from the central policy in+-- "Sqint.Lock".+module Sqint.PgAst (+ classifySql,+) where++import Data.Set qualified as Set+import Data.Text qualified as T+import PgQuery qualified as Pg+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Location (statementRange)+import Sqint.Lock (LockClass (..), LockProfile (..), RewriteImpact (..), severityFor)+import Sqint.Rule (Rule (..))+++classifySql ::+ -- | Names of user-defined domains that carry a CHECK constraint —+ -- ADD COLUMN with one of these types forces a table scan under+ -- AccessExclusiveLock. Pass 'Set.empty' to disable the rule.+ Set Text ->+ -- | Source path (used for diagnostic locations).+ FilePath ->+ -- | SQL source text.+ Text ->+ IO [Finding]+classifySql checkDomains path src = do+ result <- Pg.parseSql (T.unpack src)+ case result of+ Left err -> pure [parseFailure path err]+ Right parsed ->+ pure+ $ concatMap+ (classifyRawStmt checkDomains path src)+ (parsed ^.. Pg.stmts . traverse)+++parseFailure :: FilePath -> String -> Finding+parseFailure path err =+ Finding+ { range = SourceRange{path, startLine = 1, startCol = 1, endLine = 1, endCol = 1}+ , severity = SeverityWarn+ , rule = SetupUnparsableSql+ , title = "Could not parse SQL"+ , detail = "libpg_query: " <> T.pack err+ , suppressedBy = Nothing+ }+++classifyRawStmt :: Set Text -> FilePath -> Text -> Pg.RawStmt -> [Finding]+classifyRawStmt checkDomains path src raw =+ let node = raw ^. Pg.stmt+ range = statementRange path src raw+ in catMaybes+ [ alterTableFinding checkDomains range node+ , alterDomainFinding range node+ , indexFinding range node+ , dropIndexFinding range node+ ]+++-- | An ALTER TABLE statement is a sequence of subcommands. We emit+-- one finding for the first subcommand of concern; subsequent ones+-- would have the same source range anyway.+alterTableFinding :: Set Text -> SourceRange -> Pg.Node -> Maybe Finding+alterTableFinding checkDomains range node = do+ stmt <- view Pg.maybe'alterTableStmt node+ profile <- listToMaybe (mapMaybe (alterTableCmdProfile checkDomains) (stmt ^.. Pg.cmds . traverse))+ pure (toFinding range profile)+++-- | Decide the lock profile for a single ALTER TABLE subcommand+-- (extracted from the surrounding 'Pg.Node' wrapper).+alterTableCmdProfile :: Set Text -> Pg.Node -> Maybe (Rule, Text, LockProfile)+alterTableCmdProfile checkDomains node = do+ cmd <- view Pg.maybe'alterTableCmd node+ case cmd ^. Pg.subtype of+ Pg.AT_AddColumn -> Just (addColumnProfile checkDomains (cmd ^. Pg.def))+ Pg.AT_AddConstraint -> Just (addConstraintProfile (cmd ^. Pg.def))+ Pg.AT_AlterColumnType ->+ Just+ ( LockAlterColumnType+ , "ALTER COLUMN TYPE — table rewrite under AccessExclusiveLock unless binary-coercible"+ , LockProfile{lockClass = AccessExclusive, rewriteImpact = TableRewrite}+ )+ _ -> Nothing+++addColumnProfile :: Set Text -> Pg.Node -> (Rule, Text, LockProfile)+addColumnProfile checkDomains defNode =+ let constraintTypes = columnDefConstraintTypes defNode+ hasDefault =+ Pg.CONSTR_DEFAULT+ `elem` constraintTypes+ || maybe False (isJust . view Pg.maybe'rawDefault) (view Pg.maybe'columnDef defNode)+ notNull =+ Pg.CONSTR_NOTNULL+ `elem` constraintTypes+ || maybe False (view Pg.isNotNull) (view Pg.maybe'columnDef defNode)+ domainMatch = columnTypeIsCheckDomain checkDomains defNode+ rewrite+ | notNull && not hasDefault = TableScan+ | domainMatch = TableScan+ | otherwise = NoImpact+ title' = case (notNull && not hasDefault, domainMatch) of+ (True, _) ->+ "ADD COLUMN ... NOT NULL without DEFAULT — every row must satisfy the constraint immediately"+ (False, True) ->+ "ADD COLUMN of a CHECK-bearing domain — every existing row is validated under AccessExclusiveLock"+ (False, False) ->+ "ADD COLUMN — quick catalog-only change"+ in (LockAddColumn, title', LockProfile{lockClass = AccessExclusive, rewriteImpact = rewrite})+++-- | The declared type name of a column (lower-cased, dotted for+-- qualified names). Returns 'Nothing' if the def node doesn't carry+-- a ColumnDef.+columnTypeName :: Pg.Node -> Maybe Text+columnTypeName defNode = do+ col <- view Pg.maybe'columnDef defNode+ typ <- view Pg.maybe'typeName col+ case typ ^.. Pg.names . traverse . Pg.string . Pg.sval of+ [] -> Nothing+ parts -> Just (T.toLower (T.intercalate "." parts))+++columnTypeIsCheckDomain :: Set Text -> Pg.Node -> Bool+columnTypeIsCheckDomain checkDomains defNode =+ maybe False (`Set.member` checkDomains) (columnTypeName defNode)+++-- | The PostgreSQL parser puts inline @NOT NULL@, @DEFAULT …@, @CHECK+-- …@, etc. into 'Pg.columnDef'\'s @constraints@ array, not into the+-- top-level boolean flags. Pull out the constraint kinds we care about.+columnDefConstraintTypes :: Pg.Node -> [Pg.ConstrType]+columnDefConstraintTypes defNode =+ case view Pg.maybe'columnDef defNode of+ Nothing -> []+ Just col ->+ mapMaybe+ (fmap (view Pg.contype) . view Pg.maybe'constraint)+ (col ^.. Pg.constraints . traverse)+++addConstraintProfile :: Pg.Node -> (Rule, Text, LockProfile)+addConstraintProfile defNode =+ let mConstraint = view Pg.maybe'constraint defNode+ ct = maybe Pg.CONSTR_TYPE_UNDEFINED (view Pg.contype) mConstraint+ skipValidation = maybe False (view Pg.skipValidation) mConstraint+ rewrite+ | ct `elem` [Pg.CONSTR_CHECK, Pg.CONSTR_FOREIGN] =+ if skipValidation then NoImpact else TableScan+ | otherwise = NoImpact+ title' = case ct of+ Pg.CONSTR_CHECK ->+ if skipValidation+ then "ADD CONSTRAINT CHECK ... NOT VALID — existing rows are not re-checked"+ else "ADD CONSTRAINT CHECK — scans every row under AccessExclusiveLock"+ Pg.CONSTR_FOREIGN ->+ if skipValidation+ then "ADD CONSTRAINT FOREIGN KEY ... NOT VALID — existing rows are not re-checked"+ else "ADD CONSTRAINT FOREIGN KEY — scans every row under AccessExclusiveLock"+ _ -> "ADD CONSTRAINT — review for table scan"+ in (LockAddConstraint, title', LockProfile{lockClass = AccessExclusive, rewriteImpact = rewrite})+++-- | @ALTER DOMAIN ADD CONSTRAINT@ scans every column of every table+-- that uses the domain. @NOT VALID@ downgrades that.+alterDomainFinding :: SourceRange -> Pg.Node -> Maybe Finding+alterDomainFinding range node = do+ stmt <- view Pg.maybe'alterDomainStmt node+ -- subtype "C" identifies the ADD CONSTRAINT form per PostgreSQL's+ -- parser; see src/include/nodes/parsenodes.h.+ guard (stmt ^. Pg.subtype == "C")+ let mConstraint = view Pg.maybe'constraint (stmt ^. Pg.def)+ skipValidation = maybe False (view Pg.skipValidation) mConstraint+ rewrite = if skipValidation then NoImpact else TableScan+ title' =+ if skipValidation+ then "ALTER DOMAIN ADD CONSTRAINT ... NOT VALID — tables are not re-scanned"+ else "ALTER DOMAIN ADD CONSTRAINT — scans every column of every table using the domain"+ pure+ ( toFinding+ range+ ( LockAlterDomain+ , title'+ , LockProfile{lockClass = AccessExclusive, rewriteImpact = rewrite}+ )+ )+++-- | @CREATE INDEX@ holds Share lock (blocks writes) and scans the+-- table. @CONCURRENTLY@ downgrades both.+indexFinding :: SourceRange -> Pg.Node -> Maybe Finding+indexFinding range node = do+ stmt <- view Pg.maybe'indexStmt node+ let concurrent = stmt ^. Pg.concurrent+ profile =+ if concurrent+ then LockProfile{lockClass = ShareUpdateExclusive, rewriteImpact = TableScan}+ else LockProfile{lockClass = Share, rewriteImpact = TableScan}+ title' =+ if concurrent+ then "CREATE INDEX CONCURRENTLY — concurrent with DML"+ else "CREATE INDEX (non-concurrent) — Share lock blocks writes for the duration of the build"+ pure (toFinding range (LockCreateIndex, title', profile))+++-- | @DROP INDEX@ briefly holds AccessExclusiveLock on the table.+-- @CONCURRENTLY@ downgrades to ShareUpdateExclusive.+dropIndexFinding :: SourceRange -> Pg.Node -> Maybe Finding+dropIndexFinding range node = do+ stmt <- view Pg.maybe'dropStmt node+ guard (stmt ^. Pg.removeType == Pg.OBJECT_INDEX)+ let concurrent = stmt ^. Pg.concurrent+ profile =+ if concurrent+ then LockProfile{lockClass = ShareUpdateExclusive, rewriteImpact = NoImpact}+ else LockProfile{lockClass = AccessExclusive, rewriteImpact = NoImpact}+ title' =+ if concurrent+ then "DROP INDEX CONCURRENTLY — concurrent with DML"+ else "DROP INDEX (non-concurrent) — AccessExclusiveLock; blocks every transaction touching the table"+ pure (toFinding range (LockDropIndex, title', profile))+++toFinding :: SourceRange -> (Rule, Text, LockProfile) -> Finding+toFinding range (rule, title, profile) =+ Finding+ { range+ , severity = severityFor profile+ , rule+ , title+ , detail = ""+ , suppressedBy = Nothing+ }
+ src/Sqint/Plpgsql.hs view
@@ -0,0 +1,204 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | Extract static SQL statements embedded in PL/pgSQL function+-- bodies.+--+-- libpg_query's regular SQL parser treats the @$$ … $$@ body of a+-- @CREATE FUNCTION … LANGUAGE plpgsql@ as opaque text, so any cast,+-- DML, or other rule that walks the protobuf AST won't see what's+-- inside. libpg_query does expose a /separate/ PL/pgSQL parser+-- (@pg_query_parse_plpgsql@) which returns a JSON-encoded AST of+-- each function definition; we walk that JSON, pull out every+-- @PLpgSQL_stmt_execsql@ statement, and map its line number back to+-- the outer file.+--+-- Out of scope (deliberately): @PERFORM …@ (@PLpgSQL_stmt_perform@)+-- and @EXECUTE …@ (@PLpgSQL_stmt_dynexecute@). The former wraps an+-- expression we'd then have to re-parse to find a SELECT; the latter+-- builds SQL at runtime from text concatenation and is unparseable+-- statically by definition. Both can be added if we ever grow a rule+-- that cares about them.+--+-- Callers (currently 'Sqint.QueryPlan') re-parse each+-- embedded SQL via 'PgQuery.parseSql' and apply their existing+-- AST-walking rules.+module Sqint.Plpgsql (+ EmbeddedSql (..),+ extractEmbeddedSql,+ decodePlpgsqlJson,+) where++import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Text qualified as T+import Data.Text.Encoding qualified as TE+import PgQuery qualified as Pg+import RIO+++-- | One SQL statement extracted from a PL/pgSQL function body.+data EmbeddedSql = EmbeddedSql+ { sql :: Text+ -- ^ Raw SQL text exactly as the plpgsql parser stored it.+ , fileLine :: Int+ -- ^ 1-based line number in the outer source file where this+ -- statement begins. Mapped from the plpgsql JSON's @lineno@+ -- (which is relative to the function body) by counting newlines+ -- between the start of @CREATE FUNCTION@ and the start of the+ -- body in the outer source.+ }+++-- | For each @CREATE FUNCTION … LANGUAGE plpgsql@ in the source,+-- return every SQL statement embedded in its body.+--+-- Failures are silent: if libpg_query can't parse the outer SQL or+-- the plpgsql body, we return no findings for the affected+-- statements rather than aborting the whole linter. (The lock-class+-- and top-level cast rules will already have flagged any outer+-- parse failure.)+extractEmbeddedSql :: Text -> IO [EmbeddedSql]+extractEmbeddedSql src = do+ result <- Pg.parseSql (T.unpack src)+ case result of+ Left _ -> pure []+ Right parsed ->+ concat <$> traverse (rawStmtEmbedded src) (parsed ^.. Pg.stmts . traverse)+++rawStmtEmbedded :: Text -> Pg.RawStmt -> IO [EmbeddedSql]+rawStmtEmbedded src raw =+ case view Pg.maybe'createFunctionStmt (raw ^. Pg.stmt) of+ Nothing -> pure []+ Just fn+ | not (isPlpgsql fn) -> pure []+ | otherwise -> embeddedFromFunction src raw+++-- | A @CREATE FUNCTION@ is plpgsql when one of its 'options' is a+-- @DefElem@ with @defname == "language"@ and an argument whose+-- 'sval' equals @"plpgsql"@.+isPlpgsql :: Pg.CreateFunctionStmt -> Bool+isPlpgsql fn = any langOptionIsPlpgsql (fn ^.. Pg.options . traverse)+ where+ langOptionIsPlpgsql node =+ case view Pg.maybe'defElem node of+ Nothing -> False+ Just de ->+ de+ ^. Pg.defname+ == "language"+ && defElemStringArg de+ == Just "plpgsql"+++-- | A @DefElem@ whose @arg@ is a single @String@ node returns its+-- @sval@; otherwise 'Nothing'.+defElemStringArg :: Pg.DefElem -> Maybe Text+defElemStringArg de = view Pg.sval <$> view Pg.maybe'string (de ^. Pg.arg)+++embeddedFromFunction :: Text -> Pg.RawStmt -> IO [EmbeddedSql]+embeddedFromFunction src raw = do+ let stmtText = sliceStmt src raw+ fnStartLine = lineAt src (raw ^. Pg.stmtLocation)+ bodyStartOffsetInStmt = findBodyStartOffset stmtText+ bodyStartLine = fnStartLine + countNewlines (T.take bodyStartOffsetInStmt stmtText)+ parsed <- Pg.parsePlpgsql (T.unpack stmtText)+ case parsed of+ Left _ -> pure []+ Right json ->+ case decodePlpgsqlJson json of+ Nothing -> pure []+ Just value -> pure (walkJson bodyStartLine value [])+++-- | Decode what 'Pg.parsePlpgsql' returns. libpg_query 18.0.0 and 18.1.0+-- write each of a trigger function's implicit variables (@TG_OP@ and the+-- rest) into @datums@ as @{}}@, which is not JSON, so every trigger body+-- would decode to nothing; pganalyze/libpg_query#384 fixes it after 18.1.0.+-- @[{}}@ and @,{}}@ cannot occur in valid JSON outside a string, so when+-- the first decode fails, those become @[{}@ and @,{}@ and it is tried again.+decodePlpgsqlJson :: Text -> Maybe Aeson.Value+decodePlpgsqlJson json =+ Aeson.decodeStrict (TE.encodeUtf8 json)+ <|> Aeson.decodeStrict (TE.encodeUtf8 (T.replace "[{}}" "[{}" (T.replace ",{}}" ",{}" json)))+++-- | Slice a @RawStmt@'s substring out of the outer source. A+-- @stmt_len@ of 0 means "to the end of the input" per libpg_query's+-- convention.+sliceStmt :: Text -> Pg.RawStmt -> Text+sliceStmt src raw =+ let off = intFromInt32 (raw ^. Pg.stmtLocation)+ len = intFromInt32 (raw ^. Pg.stmtLen)+ rest = T.drop off src+ in if len == 0 then rest else T.take len rest+++-- | Find the byte offset within the @CREATE FUNCTION@ substring at+-- which the body text begins — i.e. the character right after the+-- opening @$$@ or @$tag$@. Returns 0 if no dollar-quote marker is+-- found (degenerate; the body is conceptually empty in that case).+findBodyStartOffset :: Text -> Int+findBodyStartOffset stmtText =+ case T.breakOn "$" stmtText of+ (_, rest)+ | T.null rest -> 0+ | otherwise ->+ let afterTag = T.dropWhile (/= '$') (T.drop 1 rest)+ in if T.null afterTag+ then 0+ else T.length stmtText - T.length afterTag + 1+++-- | Recursively walk a parsed plpgsql JSON value, accumulating an+-- 'EmbeddedSql' for every @PLpgSQL_stmt_execsql@ statement.+--+-- We don't need a typed representation of the plpgsql AST — the+-- shape we care about is "anywhere in the tree, an object with this+-- key, containing a 'sqlstmt' / 'query' with the embedded SQL and a+-- 'lineno'". Walking 'Value' generically also keeps us robust to+-- future shape additions.+walkJson :: Int -> Aeson.Value -> [EmbeddedSql] -> [EmbeddedSql]+walkJson bodyStartLine = go+ where+ go (Aeson.Object o) acc =+ let here = mapMaybe (uncurry (extractExecsql bodyStartLine)) (KeyMap.toList o)+ below = foldr go acc (KeyMap.elems o)+ in here <> below+ go (Aeson.Array xs) acc = foldr go acc xs+ go _ acc = acc+++-- | An @execsql@ statement wraps an @sqlstmt@ object whose+-- @PLpgSQL_expr@ holds the SQL text in a @query@ field.+extractExecsql :: Int -> Aeson.Key -> Aeson.Value -> Maybe EmbeddedSql+extractExecsql bodyStartLine key value = do+ guard (key == "PLpgSQL_stmt_execsql")+ Aeson.Object stmt <- pure value+ Aeson.Object inner <- KeyMap.lookup "sqlstmt" stmt+ Aeson.Object expr <- KeyMap.lookup "PLpgSQL_expr" inner+ Aeson.String q <- KeyMap.lookup "query" expr+ let lineno = case KeyMap.lookup "lineno" stmt of+ Just (Aeson.Number n) -> max 1 (truncate n)+ _ -> 1+ pure+ EmbeddedSql+ { sql = q+ , fileLine = bodyStartLine + lineno - 1+ }+++-- | 1-based outer-file line for a libpg_query byte offset.+lineAt :: Integral n => Text -> n -> Int+lineAt src offset = 1 + countNewlines (T.take (intFromInt32 offset) src)+++countNewlines :: Text -> Int+countNewlines = T.count "\n"+++intFromInt32 :: Integral n => n -> Int+intFromInt32 n = max 0 (fromIntegral n)
+ src/Sqint/QueryPlan.hs view
@@ -0,0 +1,267 @@+{-# LANGUAGE MultilineStrings #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TypeApplications #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | Query-plan rule: detect non-sargable column references inside+-- scan-qualifying predicates.+--+-- Background: a trigger that compared @id::text = reference@ turned an+-- index lookup into a sequential scan on every write. Wrapping an indexed+-- column in an expression — a cast (@id::text@) or a function call+-- (@lower(id)@, @date_trunc('day', created_at)@) — makes Postgres treat+-- the operand as an expression, so the column's plain index is no longer+-- usable and the planner falls back to a sequential scan.+--+-- The danger is specific to /predicates/. Wrapping a column only defeats+-- an index when the result gates a scan or a join. The same expression+-- in a SELECT list, a CTE projection, a RETURNING list, an UPDATE SET+-- assignment, or a HAVING clause (which filters /after/ grouping, off the+-- scan path) is computed per output row and never influences the access+-- path, so those must not warn.+--+-- Implementation: 'detectIndexedCasts' descends to the scan/join+-- qualifier subtrees — WHERE, JOIN ON, MERGE ON\/WHEN, and partial-index+-- \/ ON CONFLICT predicates — using the generic "Sqint.NodeWalk"+-- traversal to reach those clauses no matter how deeply they are nested+-- (subqueries, CTEs, MERGE, …). Within each qualifier it looks for a+-- comparison 'Pg.A_Expr' whose direct operand is an 'IndexHazard': a+-- @col::type@ cast (WARN, @index/cast-on-column@) or a function call taking a+-- column argument (WARN, @index/function-on-column@). DML embedded in a PL/pgSQL+-- body is surfaced via "Sqint.Plpgsql", re-parsed, and run+-- through the same collector.+--+-- The rule has no schema or plan knowledge, so it cannot tell an indexed+-- column from an unindexed one; reviewers can add an inline+-- @-- lint:ignore reason="…"@ when the column is not indexed. Only direct+-- comparison operands are inspected, so an expression wrapped one level+-- deeper (@lower(id) || 'x' = …@) and the @CASE@\/@COALESCE@ expression+-- nodes are intentionally out of scope for now.+module Sqint.QueryPlan (+ detectIndexedCasts,+) where++import Data.Text qualified as T+import PgQuery qualified as Pg+import RIO+import RIO.Set qualified as Set+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Location (sourceRangeAt)+import Sqint.NodeWalk (universeOfType)+import Sqint.Plpgsql (EmbeddedSql (..), extractEmbeddedSql)+import Sqint.Rule (Rule (..))+++-- | The two index-defeating operand shapes this rule recognises. Each+-- maps to its own rule id so reviewers can suppress them independently.+data IndexHazard+ = -- | @col::type@ — a cast of a bare column reference.+ CastHazard+ | -- | @f(col, …)@ — a function call that takes a column as an argument.+ FuncHazard+ deriving (Eq, Ord)+++detectIndexedCasts ::+ FilePath ->+ Text ->+ IO [Finding]+detectIndexedCasts path src = do+ topLevel <- topLevelFindings path src+ embedded <- embeddedFindings path src+ pure (topLevel <> embedded)+++-- | Hazards in the regular protobuf parse tree. PL/pgSQL function bodies+-- are handled separately in 'embeddedFindings'.+topLevelFindings :: FilePath -> Text -> IO [Finding]+topLevelFindings path src = do+ result <- Pg.parseSql (T.unpack src)+ pure $ case result of+ Left _ -> []+ Right parsed ->+ [ hazardFinding hz (sourceRangeAt path src loc)+ | (hz, loc) <- predicateHazards parsed+ ]+++-- | Hazards inside PL/pgSQL function bodies. We extract every embedded+-- SQL statement via the plpgsql parser, re-parse each through+-- 'PgQuery.parseSql', and run the same collector. Findings are located+-- at the embedded statement's outer-file line (column 1) — column-level+-- precision isn't worth the bookkeeping for a rule whose primary value+-- is "look here" — so we emit one per distinct hazard kind present.+embeddedFindings :: FilePath -> Text -> IO [Finding]+embeddedFindings path src = do+ embeds <- extractEmbeddedSql src+ concat <$> traverse (embedFindings path) embeds+++embedFindings :: FilePath -> EmbeddedSql -> IO [Finding]+embedFindings path e = do+ result <- Pg.parseSql (T.unpack e.sql)+ pure $ case result of+ Left _ -> []+ Right parsed ->+ [ hazardFinding hz (embeddedRange path e.fileLine)+ | hz <- Set.toList (Set.fromList (map fst (predicateHazards parsed)))+ ]+++-- | Every index hazard that appears as a direct operand of a comparison+-- inside a scan\/join qualifier, paired with its source location.+-- Deduplicated because nested qualifiers (a subquery's WHERE inside an+-- outer WHERE) are reached through more than one root.+predicateHazards :: Pg.ParseResult -> [(IndexHazard, Int32)]+predicateHazards parsed =+ Set.toList+ $ Set.fromList+ [ hz+ | qual <- scanQualifiers parsed+ , hz <- comparisonHazards qual+ ]+++-- | The scan\/join qualifier subtrees: the clauses Postgres uses to+-- choose an access path. The generic walk finds each enclosing statement+-- wherever it is nested, so subqueries, CTEs and MERGE are all covered;+-- the few clause fields below are the only hand-written part, and a+-- missing one is a false negative, never a crash. HAVING is deliberately+-- excluded — it filters after grouping and never gates the scan.+scanQualifiers :: Pg.ParseResult -> [Pg.Node]+scanQualifiers parsed =+ concat+ [ universeOfType @Pg.SelectStmt parsed+ >>= \s -> maybeToList (s ^. Pg.maybe'whereClause)+ , universeOfType @Pg.UpdateStmt parsed+ >>= \s -> maybeToList (s ^. Pg.maybe'whereClause)+ , universeOfType @Pg.DeleteStmt parsed+ >>= \s -> maybeToList (s ^. Pg.maybe'whereClause)+ , universeOfType @Pg.JoinExpr parsed+ >>= \j -> maybeToList (j ^. Pg.maybe'quals)+ , universeOfType @Pg.MergeStmt parsed+ >>= \m -> maybeToList (m ^. Pg.maybe'joinCondition)+ , universeOfType @Pg.MergeWhenClause parsed+ >>= \w -> maybeToList (w ^. Pg.maybe'condition)+ , universeOfType @Pg.IndexStmt parsed+ >>= \i -> maybeToList (i ^. Pg.maybe'whereClause)+ , universeOfType @Pg.OnConflictClause parsed+ >>= \o -> maybeToList (o ^. Pg.maybe'whereClause)+ ]+++-- | Every index hazard that is a direct operand of a comparison+-- somewhere inside the given qualifier subtree. The generic walk descends+-- boolean nesting (@AND@\/@OR@) and any subquery quals, so the comparison+-- can be arbitrarily deep.+comparisonHazards :: Pg.Node -> [(IndexHazard, Int32)]+comparisonHazards qual =+ [ hz+ | ae <- universeOfType @Pg.A_Expr qual+ , isComparisonKind (ae ^. Pg.kind)+ , operand <- maybeToList (ae ^. Pg.maybe'lexpr) <> maybeToList (ae ^. Pg.maybe'rexpr)+ , Just hz <- [operandHazard operand]+ ]+++-- | Classify a comparison operand. A bare 'ColumnRef' (or a literal) is+-- fine — the hazard is an /expression/ wrapping a column: a cast of a+-- column, or a function call taking a column argument.+operandHazard :: Pg.Node -> Maybe (IndexHazard, Int32)+operandHazard operand+ | Just tc <- operand ^. Pg.maybe'typeCast+ , isColumnRefCast tc =+ Just (CastHazard, tc ^. Pg.location)+ | Just fc <- operand ^. Pg.maybe'funcCall+ , funcCallTakesColumn fc =+ Just (FuncHazard, fc ^. Pg.location)+ | otherwise = Nothing+++-- | A 'Pg.TypeCast' is a hazard when its @arg@ is a bare 'ColumnRef' —+-- @col::type@ — the shape that defeats an index.+isColumnRefCast :: Pg.TypeCast -> Bool+isColumnRefCast tc = isJust (view Pg.maybe'columnRef (tc ^. Pg.arg))+++-- | A 'Pg.FuncCall' is a hazard when one of its arguments references a+-- column — @lower(id)@, @date_trunc('day', created_at)@ — since the+-- function result, not the column, is what the comparison sees. Argument+-- references only (the function /name/ is not a column), and functions+-- over only constants (@now()@, @lower('x')@) are not hazards.+funcCallTakesColumn :: Pg.FuncCall -> Bool+funcCallTakesColumn fc =+ not (all (null . universeOfType @Pg.ColumnRef) (fc ^.. Pg.args . traverse))+++-- | The 'Pg.A_Expr' kinds that express a comparison the planner could+-- otherwise satisfy with an index: operators (incl. @ANY@\/@ALL@),+-- @IS [NOT] DISTINCT@, @IN@, @LIKE@\/@ILIKE@ and @BETWEEN@. @NULLIF@ and+-- @SIMILAR TO@ are excluded — neither is an index-usable scan qual.+isComparisonKind :: Pg.A_Expr_Kind -> Bool+isComparisonKind k =+ k+ `elem` [ Pg.AEXPR_OP+ , Pg.AEXPR_OP_ANY+ , Pg.AEXPR_OP_ALL+ , Pg.AEXPR_DISTINCT+ , Pg.AEXPR_NOT_DISTINCT+ , Pg.AEXPR_IN+ , Pg.AEXPR_LIKE+ , Pg.AEXPR_ILIKE+ , Pg.AEXPR_BETWEEN+ , Pg.AEXPR_NOT_BETWEEN+ , Pg.AEXPR_BETWEEN_SYM+ , Pg.AEXPR_NOT_BETWEEN_SYM+ ]+++embeddedRange :: FilePath -> Int -> SourceRange+embeddedRange path line =+ SourceRange{path, startLine = line, startCol = 1, endLine = line, endCol = 1}+++hazardFinding :: IndexHazard -> SourceRange -> Finding+hazardFinding hz range =+ Finding+ { range+ , severity = SeverityWarn+ , rule = ruleFor hz+ , title = titleFor hz+ , detail = detailFor hz+ , suppressedBy = Nothing+ }+++ruleFor :: IndexHazard -> Rule+ruleFor = \case+ CastHazard -> IndexCastOnColumn+ FuncHazard -> IndexFunctionOnColumn+++titleFor :: IndexHazard -> Text+titleFor = \case+ CastHazard -> "cast on a column reference may defeat an index"+ FuncHazard -> "function call on a column may defeat an index"+++detailFor :: IndexHazard -> Text+detailFor = \case+ CastHazard ->+ """+ A column is cast to another type inside a WHERE/JOIN predicate, which+ forces Postgres to treat the column as an expression and prevents+ normal index lookups on it. If the column has an index, drop the cast+ (cast the other side of the comparison instead) or add a matching+ expression index. Suppress with `-- lint:ignore reason="…"` if the+ column is unindexed.+ """+ FuncHazard ->+ """+ A column is wrapped in a function call inside a WHERE/JOIN predicate,+ so Postgres compares the function result rather than the column and a+ plain index on the column cannot be used. Rewrite so the bare column+ is compared (move the function to the other side), or add a matching+ expression index. Suppress with `-- lint:ignore reason="…"` if the+ column is unindexed.+ """
+ src/Sqint/Rule.hs view
@@ -0,0 +1,114 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Every rule the linter can report, and the @family/rule@ ID it is+-- printed as.+--+-- The family says which part of the linter found it:+--+-- * @lock/@ — a lock a statement takes. Predicted from the SQL by the+-- static pass, or observed by deploying it (@lock/observed-…@).+-- * @deploy/@ — the dynamic pass deploying the branch's changes.+-- * @function/@ — SQL functions a change leaves broken.+-- * @index/@ — predicates that may stop a query using an index.+-- * @txn/@, @deferred/@, @suppression/@ — one rule each.+-- * @setup/@ — the linter could not run a check; nothing is known to+-- be wrong with the migration.+--+-- IDs are what people read in CI output and the JSON report, so a new+-- rule picks a family here rather than a new prefix.+module Sqint.Rule (+ Rule (..),+ renderRule,+ isPredictedLock,+ isObservedLock,+) where++import RIO+import Sqint.Lock (LockClass (..))+++data Rule+ = LockAddColumn+ | LockAlterColumnType+ | LockAddConstraint+ | LockAlterDomain+ | LockCreateIndex+ | LockDropIndex+ | LockObserved LockClass+ | DeployNonTransactional+ | DeployStatementNotObserved+ | DeployFailed+ | FunctionBrokenBody+ | FunctionCheckSkipped+ | IndexCastOnColumn+ | IndexFunctionOnColumn+ | IndexDefeated+ | IndexPlanCheckSkipped+ | TxnSetLocalAcrossCommit+ | DeferredUnfinishedBackfill+ | SuppressionMissingReason+ | SetupUnparsableSql+ | SetupUnparsableDomainFile+ | SetupUnparsablePlan+ | SetupBaselineMissing+ deriving stock (Eq, Show)+++renderRule :: Rule -> Text+renderRule = \case+ LockAddColumn -> "lock/add-column"+ LockAlterColumnType -> "lock/alter-column-type"+ LockAddConstraint -> "lock/add-constraint"+ LockAlterDomain -> "lock/alter-domain"+ LockCreateIndex -> "lock/create-index"+ LockDropIndex -> "lock/drop-index"+ LockObserved cls -> "lock/observed-" <> lockMode cls+ DeployNonTransactional -> "deploy/non-transactional"+ DeployStatementNotObserved -> "deploy/statement-not-observed"+ DeployFailed -> "deploy/failed"+ FunctionBrokenBody -> "function/broken-body"+ FunctionCheckSkipped -> "function/check-skipped"+ IndexCastOnColumn -> "index/cast-on-column"+ IndexFunctionOnColumn -> "index/function-on-column"+ IndexDefeated -> "index/defeated"+ IndexPlanCheckSkipped -> "index/plan-check-skipped"+ TxnSetLocalAcrossCommit -> "txn/set-local-across-commit"+ DeferredUnfinishedBackfill -> "deferred/unfinished-backfill"+ SuppressionMissingReason -> "suppression/missing-reason"+ SetupUnparsableSql -> "setup/unparsable-sql"+ SetupUnparsableDomainFile -> "setup/unparsable-domain-file"+ SetupUnparsablePlan -> "setup/unparsable-plan"+ SetupBaselineMissing -> "setup/baseline-missing"+++-- | PostgreSQL's lock mode names (@ACCESS EXCLUSIVE@ and so on), in the+-- ID's lower-case, hyphenated style.+lockMode :: LockClass -> Text+lockMode = \case+ AccessShare -> "access-share"+ RowShare -> "row-share"+ RowExclusive -> "row-exclusive"+ ShareUpdateExclusive -> "share-update-exclusive"+ Share -> "share"+ ShareRowExclusive -> "share-row-exclusive"+ Exclusive -> "exclusive"+ AccessExclusive -> "access-exclusive"+++-- | A lock the static pass predicted from the SQL alone.+isPredictedLock :: Rule -> Bool+isPredictedLock = \case+ LockAddColumn -> True+ LockAlterColumnType -> True+ LockAddConstraint -> True+ LockAlterDomain -> True+ LockCreateIndex -> True+ LockDropIndex -> True+ _ -> False+++-- | A lock the dynamic pass saw a statement take.+isObservedLock :: Rule -> Bool+isObservedLock = \case+ LockObserved _ -> True+ _ -> False
+ src/Sqint/Run.hs view
@@ -0,0 +1,175 @@+{-# LANGUAGE NoFieldSelectors #-}++-- | Top-level orchestration: discover changed files, run the+-- classifiers, apply suppressions, and emit findings.+--+-- Two passes:+--+-- * /static/ — per changed file, order-independent: the AST+-- lock-class classifier and the indexed-cast detector. This is all+-- the pre-commit hook runs (no Postgres required).+--+-- * /dynamic/ — only when a live Postgres and a baseline change are+-- supplied (CI). The cumulative dynamic pass observes each new change's+-- locks against the correct, progressively-deployed schema (see+-- "Sqint.Cumulative"), and the plan-level cast check runs+-- against the fully-deployed PR schema afterwards.+module Sqint.Run (+ LintConfig (..),+ runLint,+) where++import Data.Map.Strict qualified as Map+import Data.Text.IO qualified as Text.IO+import RIO+import Sqint.Cumulative qualified as Cumulative+import Sqint.DeferredDependency qualified as DeferredDependency+import Sqint.Deploy.Connection (DeploySettings)+import Sqint.Deploy.PlanCheck qualified as PlanCheck+import Sqint.DeployTree (loadDeployTree)+import Sqint.Diagnostic (Finding (..), SourceRange (..), severityExitCode, severityRank)+import Sqint.Domains (DomainSet (..), loadDomainSet)+import Sqint.Output (OutputFormat (..), renderFindings)+import Sqint.PgAst qualified as PgAst+import Sqint.QueryPlan qualified as QueryPlan+import Sqint.Rule (isObservedLock, isPredictedLock)+import Sqint.SetLocal qualified as SetLocal+import Sqint.Suppression qualified as Suppression+++data LintConfig = LintConfig+ { paths :: [FilePath]+ , outputFormat :: OutputFormat+ , verbose :: Bool+ -- ^ Show informational and suppressed findings too. Off by default+ -- so the text output stays focused on what needs attention.+ , databaseRoot :: FilePath+ -- ^ The sqitch top directory. The linter reads+ -- @\<databaseRoot\>/deploy/**/*.sql@ for facts about the whole+ -- schema (CHECK-bearing domains, registered backfills), and the+ -- dynamic pass finds each change's deploy script under it.+ , planPath :: FilePath+ -- ^ Path to @sqitch.plan@, used by the cumulative dynamic pass to+ -- order the PR's new changes.+ , baselineChange :: Maybe Text+ -- ^ The target branch's plan head. Everything after it in the plan+ -- is new in this PR. Required for the dynamic pass.+ , postgres :: Maybe DeploySettings+ , deferredBackfills :: Bool+ -- ^ Check that a change finishes the deferred backfills on a table+ -- before it validates a constraint there. Off unless the project+ -- registers backfills in @deferred.migration@.+ }+++-- | Run the linter, emit findings, return the exit code. The caller+-- invokes 'System.Exit.exitWith' on it.+runLint :: LintConfig -> IO ExitCode+runLint cfg = do+ -- Read once for the whole run: the deploy tree is large and both of the+ -- facts drawn from it are the same for every changed file.+ deployTree <- loadDeployTree cfg.databaseRoot+ domains <- loadDomainSet deployTree+ let registered+ | cfg.deferredBackfills = DeferredDependency.loadRegisteredBackfills deployTree+ | otherwise = mempty+ static <- concat <$> traverse (staticOne domains.withCheck registered) cfg.paths+ dynamic <- runDynamic cfg+ suppressed <- applySuppressions cfg.paths (domains.parseFailures <> static <> dynamic)+ let final = dedupe suppressed+ Text.IO.putStr (renderFindings cfg.outputFormat cfg.verbose final)+ pure (severityExitCode final)+++-- | Static, order-independent classifiers for one changed file.+staticOne :: Set Text -> Map Text (Set Text) -> FilePath -> IO [Finding]+staticOne checkDomains registered path+ | isSnapshotPath path = pure []+ | otherwise = do+ src <- Text.IO.readFile path+ ast <- PgAst.classifySql checkDomains path src+ plan <- QueryPlan.detectIndexedCasts path src+ setLocal <- SetLocal.detectSetLocalAcrossCommit path src+ deferred <- DeferredDependency.detectUnfinishedDependency registered path src+ pure (ast <> plan <> setLocal <> deferred)+++-- | The dynamic pass: cumulative lock observation + the plan-level cast+-- check. Skipped entirely unless both a Postgres connection and a+-- baseline change are configured.+runDynamic :: LintConfig -> IO [Finding]+runDynamic cfg = case (cfg.postgres, cfg.baselineChange) of+ (Just settings, Just baseline) -> do+ dyn <- Cumulative.runCumulativeDeploy settings cfg.databaseRoot cfg.planPath baseline+ -- PlanCheck's differential EXPLAIN needs the referenced objects+ -- to exist, so it runs against the fully-deployed PR schema the+ -- cumulative pass just produced.+ pc <- concat <$> traverse (planCheckOne settings) cfg.paths+ pure (dyn <> pc)+ _ -> pure []+++planCheckOne :: DeploySettings -> FilePath -> IO [Finding]+planCheckOne settings path+ | isSnapshotPath path = pure []+ | otherwise = PlanCheck.checkFile settings path+++-- | Rework snapshot files (@\<name\>@\<tag\>.sql@) are frozen copies of+-- a prior object definition; they are never deployed and linting them+-- only produces noise, so both passes skip them.+isSnapshotPath :: FilePath -> Bool+isSnapshotPath = elem '@'+++-- | Apply @-- lint:ignore reason="…"@ annotations across every changed+-- file (path-aware, so an annotation in one file never suppresses a+-- finding in another), and surface malformed annotations.+applySuppressions :: [FilePath] -> [Finding] -> IO [Finding]+applySuppressions paths findings = do+ parsed <- forM paths \path -> do+ msrc <- tryReadFile path+ pure (path, maybe ([], []) (Suppression.parseAnnotations path) msrc)+ let annsByPath = Map.fromList [(path, fst result) | (path, result) <- parsed]+ malformed = concatMap (snd . snd) parsed+ mark f = case Map.lookup f.range.path annsByPath of+ Just anns | [marked] <- Suppression.applyAnnotations anns [f] -> marked+ _ -> f+ pure (malformed <> map mark findings)+++tryReadFile :: FilePath -> IO (Maybe Text)+tryReadFile path = either (const Nothing) Just <$> tryAny (Text.IO.readFile path)+++-- | Drop a predicted @lock/…@ finding when the dynamic pass observed a+-- lock at the same source location /at least as severe/: the live+-- observation supersedes the static guess, so we keep one line per+-- statement. We keep the static finding when it is stronger than what+-- the dynamic pass saw — e.g. a non-concurrent @CREATE INDEX@ is WARN+-- statically (it blocks writes while building on a populated table),+-- but the dynamic pass, running against the linter's empty tables, only sees+-- a brief lock; the static signal is the one worth surfacing.+dedupe :: [Finding] -> [Finding]+dedupe fs =+ let+ -- Key on the full start position, not just the line: two DDL+ -- statements can share a source line, and the static and dynamic+ -- passes both derive the position from the same statement byte+ -- offset, so the same statement matches while siblings don't.+ loc f = (f.range.path, f.range.startLine, f.range.startCol)+ observedSevAt =+ Map.fromListWith+ max+ [ (loc f, severityRank f.severity)+ | f <- fs+ , isObservedLock f.rule+ ]+ keep f+ | isPredictedLock f.rule =+ case Map.lookup (loc f) observedSevAt of+ Just observedRank -> observedRank < severityRank f.severity+ Nothing -> True+ | otherwise = True+ in+ filter keep fs
+ src/Sqint/SetLocal.hs view
@@ -0,0 +1,210 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NoFieldSelectors #-}++-- | Flag transaction-scoped settings (@SET LOCAL@, @set_config(…, true)@) in a+-- plpgsql body that also COMMITs: only the first batch keeps them, later ones+-- fall back to cluster defaults. The fix is @set_config(name, value, false)@.+module Sqint.SetLocal (+ detectSetLocalAcrossCommit,+) where++import Data.Aeson qualified as Aeson+import Data.Aeson.KeyMap qualified as KeyMap+import Data.Char (isSpace)+import Data.String.Interpolate (iii)+import Data.Text qualified as T+import PgQuery qualified as Pg+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Plpgsql (decodePlpgsqlJson)+import Sqint.Rule (Rule (..))+++-- | One transaction-scoped setting found in a body.+data LocalSet = LocalSet+ { statement :: Text+ , bodyLine :: Int+ }+++-- | Findings for every plpgsql body mixing a transaction-scoped setting with a COMMIT.+detectSetLocalAcrossCommit :: FilePath -> Text -> IO [Finding]+detectSetLocalAcrossCommit path src = do+ result <- Pg.parseSql (T.unpack src)+ case result of+ Left _ -> pure []+ Right parsed ->+ concat <$> traverse (rawStmt path src) (parsed ^.. Pg.stmts . traverse)+++rawStmt :: FilePath -> Text -> Pg.RawStmt -> IO [Finding]+rawStmt path src raw+ | isPlpgsqlFunction raw = analyse path src raw False+ | isDoBlock raw = analyse path src raw True+ | otherwise = pure []+++isDoBlock :: Pg.RawStmt -> Bool+isDoBlock raw = isJust (view Pg.maybe'doStmt (raw ^. Pg.stmt))+++isPlpgsqlFunction :: Pg.RawStmt -> Bool+isPlpgsqlFunction raw =+ case view Pg.maybe'createFunctionStmt (raw ^. Pg.stmt) of+ Nothing -> False+ Just fn -> any langOptionIsPlpgsql (fn ^.. Pg.options . traverse)+ where+ langOptionIsPlpgsql node =+ case view Pg.maybe'defElem node of+ Nothing -> False+ Just de ->+ de+ ^. Pg.defname+ == "language"+ && (view Pg.sval <$> view Pg.maybe'string (de ^. Pg.arg))+ == Just "plpgsql"+++-- | libpg_query's plpgsql parser takes function definitions, not @DO@ blocks,+-- so a @DO@ body is wrapped in a synthetic function before parsing.+analyse :: FilePath -> Text -> Pg.RawStmt -> Bool -> IO [Finding]+analyse path src raw isDo = do+ let stmtText = sliceStmt src raw+ stmtStartLine = lineAt src (raw ^. Pg.stmtLocation)+ bodyOffset = findBodyStartOffset stmtText+ bodyStartLine = stmtStartLine + countNewlines (T.take bodyOffset stmtText)+ toParse+ | isDo = wrapDoBlock stmtText+ | otherwise = stmtText+ parsed <- Pg.parsePlpgsql (T.unpack toParse)+ case parsed of+ Left _ -> pure []+ Right json ->+ case decodePlpgsqlJson json of+ Nothing -> pure []+ Just value -> do+ let locals = collectLocalSets value []+ commits = hasCommit value+ pure+ [ finding path (bodyStartLine + l.bodyLine - 1) l.statement+ | commits+ , l <- locals+ ]+++-- | Wrap @do $$ … $$;@ as a function definition the plpgsql parser accepts.+wrapDoBlock :: Text -> Text+wrapDoBlock stmtText =+ let body = T.drop (findBodyStartOffset stmtText - 2) stmtText+ withoutTrailer = T.dropWhileEnd (\c -> c == ';' || isSpace c) body+ in [iii|create function __lint_do_block() returns void as #{withoutTrailer} language plpgsql;|]+++-- | Does this body contain a @COMMIT@ or @ROLLBACK@?+hasCommit :: Aeson.Value -> Bool+hasCommit = go+ where+ go (Aeson.Object o) =+ any isTxnKey (KeyMap.keys o) || any go (KeyMap.elems o)+ go (Aeson.Array xs) = any go xs+ go _ = False++ isTxnKey k = k == "PLpgSQL_stmt_commit" || k == "PLpgSQL_stmt_rollback"+++-- | Every transaction-scoped setting in the body (execsql or @PERFORM@).+collectLocalSets :: Aeson.Value -> [LocalSet] -> [LocalSet]+collectLocalSets = go+ where+ go (Aeson.Object o) acc =+ let here = mapMaybe (uncurry extract) (KeyMap.toList o)+ below = foldr go acc (KeyMap.elems o)+ in here <> below+ go (Aeson.Array xs) acc = foldr go acc xs+ go _ acc = acc++ extract key value = do+ guard (key == "PLpgSQL_stmt_execsql" || key == "PLpgSQL_stmt_perform")+ Aeson.Object stmt <- pure value+ query <- queryOf stmt+ guard (isTransactionScoped query)+ let lineno = case KeyMap.lookup "lineno" stmt of+ Just (Aeson.Number n) -> max 1 (truncate n)+ _ -> 1+ pure LocalSet{statement = T.strip query, bodyLine = lineno}++ queryOf stmt = do+ Aeson.Object inner <-+ KeyMap.lookup "sqlstmt" stmt <|> KeyMap.lookup "expr" stmt+ Aeson.Object expr <- KeyMap.lookup "PLpgSQL_expr" inner+ Aeson.String q <- KeyMap.lookup "query" expr+ pure q+++-- | @SET LOCAL@, or @set_config@ with a @true@ third argument; whitespace is+-- normalised first so the match does not depend on formatting.+isTransactionScoped :: Text -> Bool+isTransactionScoped query =+ ("set local " `T.isPrefixOf` normalised)+ || ("set_config(" `T.isInfixOf` normalised && ",true)" `T.isInfixOf` squashed)+ where+ normalised = T.strip (T.toLower (T.unwords (T.words query)))+ squashed = T.filter (not . isSpace) normalised+++finding :: FilePath -> Int -> Text -> Finding+finding path line statement =+ Finding+ { range =+ SourceRange+ { path+ , startLine = line+ , startCol = 1+ , endLine = line+ , endCol = 1+ }+ , severity = SeverityBlock+ , rule = TxnSetLocalAcrossCommit+ , title = "transaction-scoped setting in a block that COMMITs"+ , detail =+ [iii|+ `#{statement}` is scoped to the current transaction, and this block+ COMMITs. Only the first iteration runs with it; every one after+ that falls back to the cluster default (for lock_timeout, 0 --+ wait forever). Use session scope instead:+ set_config(name, value, false).+ |]+ , suppressedBy = Nothing+ }+++sliceStmt :: Text -> Pg.RawStmt -> Text+sliceStmt src raw =+ let off = intFromInt32 (raw ^. Pg.stmtLocation)+ len = intFromInt32 (raw ^. Pg.stmtLen)+ rest = T.drop off src+ in if len == 0 then rest else T.take len rest+++findBodyStartOffset :: Text -> Int+findBodyStartOffset stmtText =+ case T.breakOn "$" stmtText of+ (_, rest)+ | T.null rest -> 0+ | otherwise ->+ let afterTag = T.dropWhile (/= '$') (T.drop 1 rest)+ in if T.null afterTag+ then 0+ else T.length stmtText - T.length afterTag + 1+++lineAt :: Integral n => Text -> n -> Int+lineAt src offset = 1 + countNewlines (T.take (intFromInt32 offset) src)+++countNewlines :: Text -> Int+countNewlines = T.count "\n"+++intFromInt32 :: Integral n => n -> Int+intFromInt32 n = max 0 (fromIntegral n)
+ src/Sqint/Severity.hs view
@@ -0,0 +1,22 @@+module Sqint.Severity (+ Severity (..),+ severityRank,+) where++import RIO+++data Severity+ = SeverityBlock+ | SeverityWarn+ | SeverityInfo+ deriving stock (Eq, Show)+++-- | Higher rank = more severe. Used to keep the strongest finding when+-- the static and dynamic passes both flag one source location.+severityRank :: Severity -> Int+severityRank = \case+ SeverityBlock -> 2+ SeverityWarn -> 1+ SeverityInfo -> 0
+ src/Sqint/Suppression.hs view
@@ -0,0 +1,107 @@+{-# LANGUAGE NoFieldSelectors #-}++-- | Parse and apply @-- lint:ignore reason="…"@ annotations.+--+-- Annotation applies to the next non-comment, non-blank line. The+-- @reason="…"@ field is mandatory and surfaces in the audit log.+module Sqint.Suppression (+ Annotation (..),+ parseAnnotations,+ applyAnnotations,+) where++import Data.Text qualified as T+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (Rule (..))+++data Annotation = Annotation+ { line :: Int+ , reason :: Text+ }+++-- | Scan a SQL source for @-- lint:ignore reason="…"@ comments.+--+-- Each annotation is recorded at the *target* line — the next line+-- after the comment that has non-comment, non-whitespace content.+-- If the annotation sits at the end of a SQL line it applies to that+-- line directly.+--+-- Annotations missing a @reason="…"@ field are dropped and surfaced+-- as WARN-severity findings so the author knows the annotation did+-- not suppress anything.+parseAnnotations :: FilePath -> Text -> ([Annotation], [Finding])+parseAnnotations path src =+ let numbered = zip [1 :: Int ..] (T.lines src)+ extracted = mapMaybe extract numbered+ (valid, malformed) = partitionEithers (map validate extracted)+ in (resolveTargets numbered valid, map (malformedFinding path) malformed)+++extract :: (Int, Text) -> Maybe (Int, Bool, Maybe Text)+extract (lineNum, lineText) = do+ let (before, comment) = T.breakOn "-- lint:ignore" lineText+ guard (not (T.null comment))+ let rest = T.drop (T.length "-- lint:ignore") comment+ let reason = extractReason rest+ let trailing = T.strip before+ pure (lineNum, T.null trailing, reason)+++validate :: (Int, Bool, Maybe Text) -> Either (Int, Bool, Text) Int+validate (lineNum, isStandalone, mReason) = case mReason of+ Just reason | not (T.null reason) -> Left (lineNum, isStandalone, reason)+ _ -> Right lineNum+++extractReason :: Text -> Maybe Text+extractReason rest =+ case T.stripPrefix "reason=\"" (T.dropWhile (== ' ') rest) of+ Just inner ->+ let (quoted, _) = T.breakOn "\"" inner+ in Just quoted+ Nothing -> Nothing+++malformedFinding :: FilePath -> Int -> Finding+malformedFinding path lineNum =+ Finding+ { range = SourceRange{path, startLine = lineNum, startCol = 1, endLine = lineNum, endCol = 1}+ , severity = SeverityWarn+ , rule = SuppressionMissingReason+ , title = "lint:ignore annotation missing reason=\"…\""+ , detail = "Annotation is ignored. Add `reason=\"why this is safe\"` so the suppression is audited."+ , suppressedBy = Nothing+ }+++-- | If the annotation is on its own line, advance to the next non-blank,+-- non-comment line. If the annotation is trailing on a SQL line, it+-- applies to that line.+resolveTargets :: [(Int, Text)] -> [(Int, Bool, Text)] -> [Annotation]+resolveTargets allLines = map resolve+ where+ resolve (lineNum, isStandalone, reason)+ | isStandalone =+ case dropWhile isBlankOrComment (dropWhile ((<= lineNum) . fst) allLines) of+ ((target, _) : _) -> Annotation{line = target, reason}+ [] -> Annotation{line = lineNum, reason}+ | otherwise = Annotation{line = lineNum, reason}++ isBlankOrComment (_, txt) =+ let s = T.strip txt+ in T.null s || "--" `T.isPrefixOf` s+++-- | Mark findings as suppressed when an annotation lands on any line of+-- their range: the line below a standalone annotation is a statement's+-- first, and an annotation trailing a statement sits on its last.+applyAnnotations :: [Annotation] -> [Finding] -> [Finding]+applyAnnotations annotations = map mark+ where+ mark f =+ case [a | a <- annotations, f.range.startLine <= a.line, a.line <= f.range.endLine] of+ (a : _) -> f{suppressedBy = Just a.reason}+ [] -> f
+ test/Spec.hs view
@@ -0,0 +1,34 @@+module Main where++import RIO+import Sqint.CumulativeSpec qualified as CumulativeSpec+import Sqint.DeferredDependencySpec qualified as DeferredDependencySpec+import Sqint.DeploySpec qualified as DeploySpec+import Sqint.DomainsSpec qualified as DomainsSpec+import Sqint.LockSpec qualified as LockSpec+import Sqint.OutputSpec qualified as OutputSpec+import Sqint.PgAstSpec qualified as PgAstSpec+import Sqint.PlanCheckSpec qualified as PlanCheckSpec+import Sqint.QueryPlanSpec qualified as QueryPlanSpec+import Sqint.SetLocalSpec qualified as SetLocalSpec+import Sqint.SuppressionSpec qualified as SuppressionSpec+import Test.Tasty+++main :: IO ()+main =+ defaultMain+ $ testGroup+ "sqint"+ [ CumulativeSpec.tests+ , DeferredDependencySpec.tests+ , DeploySpec.tests+ , DomainsSpec.tests+ , LockSpec.tests+ , OutputSpec.tests+ , PgAstSpec.tests+ , PlanCheckSpec.tests+ , QueryPlanSpec.tests+ , SetLocalSpec.tests+ , SuppressionSpec.tests+ ]
+ test/Sqint/CumulativeSpec.hs view
@@ -0,0 +1,147 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.CumulativeSpec (tests) where++import Data.Map.Strict qualified as Map+import Data.String.Interpolate (i)+import Data.Text qualified as T+import RIO+import Sqint.Cumulative (BrokenFunction (..), FunctionCheck (..), brokenFunctionFinding, firstStatementLine, newChangesAfter, recordCheck, trackBrokenFunctions)+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (renderRule)+import Sqitch.Plan qualified as Plan+import Test.Tasty+import Test.Tasty.HUnit+++-- | Parse a plan body (header is prepended) or fail the test loudly.+plan :: Text -> Plan.Plan+plan body =+ let src = "%syntax-version=1.0.0\n%project=test\n\n" <> body+ in either (error . T.unpack . Plan.renderParseError) id (Plan.parsePlan src)+++changeNamesAfter :: Text -> Text -> Maybe [Text]+changeNamesAfter baseline body =+ map (.name) <$> newChangesAfter (plan body) baseline+++line :: Text -> Text+line name = [i|#{name} 2024-01-01T00:00:00Z a <a@x> \# #{name}|] <> "\n"+++tests :: TestTree+tests = testGroup "Cumulative" [newChangesAfterTests, brokenFunctionTests]+++newChangesAfterTests :: TestTree+newChangesAfterTests =+ testGroup+ "Cumulative.newChangesAfter"+ [ testCase "returns the changes strictly after the baseline, in plan order"+ $ changeNamesAfter "b" (line "a" <> line "b" <> line "c" <> line "d")+ @?= Just ["c", "d"]+ , testCase "baseline at the plan head yields no new changes"+ $ changeNamesAfter "c" (line "a" <> line "b" <> line "c")+ @?= Just []+ , testCase "missing baseline yields Nothing (skip, don't redeploy history)"+ $ changeNamesAfter "nope" (line "a" <> line "b")+ @?= Nothing+ , testCase "a rework after the baseline is the new occurrence, in order"+ $+ -- `t` was first created and tagged on the base branch (before+ -- the baseline), then reworked in this PR (after it). Only the+ -- reworked occurrence is new, and it sorts after the baseline.+ changeNamesAfter+ "base"+ ( line "t"+ <> "@v1 2024-01-01T00:00:00Z a <a@x> # tag\n"+ <> line "base"+ <> "t [t@v1] 2024-01-02T00:00:00Z a <a@x> # reworked t\n"+ <> line "z"+ )+ @?= Just ["t", "z"]+ ]+++-- | Run 'trackBrokenFunctions' over a sequence of (change, broken-now)+-- checks, as the cumulative pass does after each deploy.+track :: Map Text Text -> [(Text, Map Text Text)] -> [BrokenFunction]+track known = foldl' step []+ where+ step episodes (name, now) = trackBrokenFunctions known name [i|deploy/#{name}.sql|] 3 now episodes+++getter :: Text+getter = "shop.get_transaction_provider_details(shop.orders)"+++tooFew :: Text+tooFew = "return type mismatch in function declared to return shop.transaction_provider_details (Final statement returns too few columns.)"+++brokenFunctionTests :: TestTree+brokenFunctionTests =+ testGroup+ "Cumulative broken SQL functions"+ [ testCase "a function broken by one change and fixed by a later one is attributed to both"+ $+ -- The usual shape: the migration adds the column, the type rework is a+ -- no-op for the getter, the getter rework fixes it.+ track+ Map.empty+ [ ("migration", Map.singleton getter tooFew)+ , ("type-rework", Map.singleton getter tooFew)+ , ("getter-rework", Map.empty)+ ]+ @?= [ BrokenFunction+ { signature = getter+ , message = tooFew+ , brokenBy = "migration"+ , script = "deploy/migration.sql"+ , line = 3+ , fixedBy = Just "getter-rework"+ }+ ]+ , testCase "a function still broken after the last change has no fix"+ $ ((.fixedBy) <$> (track Map.empty [("a", Map.singleton getter tooFew), ("b", Map.singleton getter tooFew)]))+ @?= [Nothing]+ , testCase "functions already broken at the baseline are not reported"+ $ track (Map.singleton "settlement.f(bigint)" "excluded_1") [("a", Map.singleton "settlement.f(bigint)" "excluded_1")]+ @?= []+ , testCase "changes that break nothing report nothing"+ $ track Map.empty [("a", Map.empty), ("b", Map.empty)]+ @?= []+ , testCase "a function repaired and then broken again gets a second, open episode"+ $ [(f.brokenBy, f.fixedBy) | f <- track Map.empty [("a", Map.singleton getter tooFew), ("b", Map.empty), ("c", Map.singleton getter tooFew)]]+ @?= [("a", Just "b"), ("c", Nothing)]+ , testCase "a check that fails to run keeps earlier findings and stops later checks" $ do+ let start = FunctionCheck{known = Just Map.empty, episodes = []}+ (afterA, _) = recordCheck "a" "deploy/a.sql" 3 (Right (Map.singleton getter tooFew)) start+ (afterB, skipped) = recordCheck "b" "deploy/b.sql" 3 (Left "statement timeout") afterA+ (afterC, _) = recordCheck "c" "deploy/c.sql" 3 (Right (Map.singleton "x.f()" "broken")) afterB+ [renderRule f.rule | f <- skipped] @?= ["function/check-skipped"]+ afterB.known @?= Nothing+ [(f.signature, f.brokenBy, f.fixedBy) | f <- afterC.episodes] @?= [(getter, "a", Nothing)]+ , testCase "the finding blocks, points at the change's first statement, and names the fix" $ do+ let f =+ brokenFunctionFinding+ BrokenFunction+ { signature = getter+ , message = tooFew+ , brokenBy = "migration"+ , script = "deploy/migration.sql"+ , line = 3+ , fixedBy = Just "getter-rework"+ }+ f.severity @?= SeverityBlock+ renderRule f.rule @?= "function/broken-body"+ (f.range.path, f.range.startLine) @?= ("deploy/migration.sql", 3)+ assertBool "detail names the later change" ("until `getter-rework` deploys" `T.isInfixOf` f.detail)+ , testCase "firstStatementLine skips the sqitch header comment and blank lines"+ $ firstStatementLine "-- Deploy app:x to pg\n\nset lock_timeout to '50ms';\n"+ @?= 3+ , testCase "firstStatementLine of an empty file is 1"+ $ firstStatementLine ""+ @?= 1+ ]
+ test/Sqint/DeferredDependencySpec.hs view
@@ -0,0 +1,224 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.DeferredDependencySpec (tests) where++import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import RIO+import Sqint.DeferredDependency (detectUnfinishedDependency, registrationsIn)+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (renderRule)+import Test.Tasty+import Test.Tasty.HUnit+++tests :: TestTree+tests =+ testGroup+ "DeferredDependency"+ [ -- Nothing registered means nothing to depend on, so the classifier+ -- returns before parsing.+ testCase "no registered backfills yields no findings" $ do+ findings <- detectUnfinishedDependency Map.empty "v.sql" validateOrders+ findings @?= []+ , testCase "VALIDATE CONSTRAINT on a table with an open backfill is blocked" $ do+ findings <- detectUnfinishedDependency ordersRegistered "v.sql" validateOrders+ map (.severity) findings @?= [SeverityBlock]+ map (renderRule . (.rule)) findings @?= ["deferred/unfinished-backfill"]+ , -- The usual way to finish a backfill: the same change both+ -- finishes the backfill and validates.+ testCase "calling ensure_finished in the same change satisfies it" $ do+ let src =+ """+ call deferred.ensure_finished('orders_status_backfill', 'my_change');+ alter table shop.orders validate constraint orders_status_fkey;+ """+ findings <- detectUnfinishedDependency ordersRegistered "f.sql" src+ findings @?= []+ , testCase "SET NOT NULL also requires the data to conform" $ do+ let src = "alter table shop.orders alter column status set not null;"+ findings <- detectUnfinishedDependency ordersRegistered "n.sql" src+ map (.severity) findings @?= [SeverityBlock]+ , -- A different table's backfill is not this change's problem.+ testCase "a table with no registered backfill is fine" $ do+ let src = "alter table shop.refund validate constraint refund_fkey;"+ findings <- detectUnfinishedDependency ordersRegistered "r.sql" src+ findings @?= []+ , testCase "an unqualified table name is treated as public" $ do+ let src = "alter table thing validate constraint thing_fkey;"+ findings <- detectUnfinishedDependency (Map.singleton "public.thing" (Set.singleton "public_thing_done_backfill")) "t.sql" src+ map (.severity) findings @?= [SeverityBlock]+ , -- Only the two forms that read every row matter; ordinary DDL on the+ -- same table is unaffected by an in-flight backfill.+ testCase "ADD COLUMN on the backfilled table is fine" $ do+ let src = "alter table shop.orders add column note text;"+ findings <- detectUnfinishedDependency ordersRegistered "a.sql" src+ findings @?= []+ , testCase "adding a NOT VALID constraint is fine" $ do+ let src =+ """+ alter table shop.orders+ add constraint orders_status_fkey+ foreign key (status) references shop.order_status (name)+ not valid;+ """+ findings <- detectUnfinishedDependency ordersRegistered "a.sql" src+ findings @?= []+ , testCase "empty source yields no findings" $ do+ findings <- detectUnfinishedDependency ordersRegistered "e.sql" ""+ findings @?= []+ , testCase "unparseable source yields no findings" $ do+ findings <- detectUnfinishedDependency ordersRegistered "junk.sql" "not sql at all ("+ findings @?= []+ , testCase "two dependent statements are reported separately" $ do+ let src =+ """+ alter table shop.orders validate constraint orders_status_fkey;+ alter table shop.orders alter column status set not null;+ """+ findings <- detectUnfinishedDependency ordersRegistered "two.sql" src+ length findings @?= 2+ , -- Regresses if lineAt stops skipping the leading whitespace libpg_query+ -- leaves before a second statement.+ testCase "the finding points at the offending statement's line" $ do+ let src =+ """+ alter table shop.orders add column note text;+ alter table shop.orders validate constraint orders_status_fkey;+ """+ findings <- detectUnfinishedDependency ordersRegistered "l.sql" src+ map ((.startLine) . (.range)) findings @?= [2]+ , -- One table can carry a backfill per column; all must be finished.+ testCase "every backfill open on the table is reported" $ do+ findings <- detectUnfinishedDependency twoOnOrders "v.sql" validateOrders+ length findings @?= 2+ , testCase "finalising one of two backfills still leaves the other" $ do+ let src =+ """+ call deferred.ensure_finished('orders_status_backfill', 'my_change');+ alter table shop.orders validate constraint orders_status_fkey;+ """+ findings <- detectUnfinishedDependency twoOnOrders "f.sql" src+ map (.severity) findings @?= [SeverityBlock]+ , -- Cases a whole-file string co-occurrence check would wrongly wave through.+ testCase "a comment mentioning ensure_finished does not satisfy it" $ do+ let src =+ """+ -- TODO: call deferred.ensure_finished('orders_status_backfill', 'later')+ alter table shop.orders validate constraint orders_status_fkey;+ """+ findings <- detectUnfinishedDependency ordersRegistered "c.sql" src+ map (.severity) findings @?= [SeverityBlock]+ , -- Substring matching cannot tell these apart; a literal comparison can.+ testCase "finalising a backfill whose name contains this one's does not satisfy it" $ do+ let src =+ """+ call deferred.ensure_finished('orders_status_backfill_v2', 'my_change');+ alter table shop.orders validate constraint orders_status_fkey;+ """+ findings <- detectUnfinishedDependency ordersRegistered "s.sql" src+ map (.severity) findings @?= [SeverityBlock]+ , -- Must not become so strict it misses a correct finaliser written differently.+ testCase "named notation satisfies it" $ do+ let src =+ """+ call deferred.ensure_finished(+ migration_name := 'orders_status_backfill',+ finalized_by_change := 'my_change');+ alter table shop.orders validate constraint orders_status_fkey;+ """+ findings <- detectUnfinishedDependency ordersRegistered "named.sql" src+ findings @?= []+ , testCase "an unqualified call satisfies it" $ do+ let src =+ """+ call ensure_finished('orders_status_backfill', 'my_change');+ alter table shop.orders validate constraint orders_status_fkey;+ """+ findings <- detectUnfinishedDependency ordersRegistered "bare.sql" src+ findings @?= []+ , -- The table comes from source_table, not from parsing the name.+ testCase "a registering insert is discovered with its table" $ do+ let src =+ """+ insert into deferred.migration+ (name, enqueued_by, source_table, chunk_function,+ key_column, key_type, target_batch_ms, max_batch_size)+ values+ ( 'orders_status_backfill'+ , 'my_change'+ , 'shop.orders'+ , 'shop.backfill_orders_status'+ , 'id'+ , 'bigint'+ , 2000+ , 100000+ )+ on conflict (name) do nothing;+ """+ registrationsIn src @?= ordersRegistered+ , -- A hand-written registration may list columns in any order.+ testCase "the column order is not assumed" $ do+ let src =+ """+ insert into deferred.migration+ (source_table, key_type, name, enqueued_by, chunk_function, key_column)+ values+ ( 'shop.orders'+ , 'bigint'+ , 'orders_status_backfill'+ , 'my_change'+ , 'shop.backfill_orders_status'+ , 'id'+ );+ """+ registrationsIn src @?= ordersRegistered+ , testCase "two registering inserts in one file are both discovered" $ do+ let src =+ """+ insert into deferred.migration+ (name, enqueued_by, source_table, chunk_function, key_column, key_type)+ values+ ( 'orders_status_backfill', 'a', 'shop.orders'+ , 'shop.backfill_orders_status', 'id', 'bigint' );+ insert into deferred.migration+ (name, enqueued_by, source_table, chunk_function, key_column, key_type)+ values+ ( 'orders_channel_backfill', 'b', 'shop.orders'+ , 'shop.backfill_orders_channel', 'id', 'bigint' );+ """+ registrationsIn src @?= twoOnOrders+ , -- Keywords are matched case-insensitively.+ testCase "an uppercased insert is still discovered" $ do+ let src =+ """+ INSERT INTO deferred.migration+ (name, enqueued_by, source_table, chunk_function, key_column, key_type)+ VALUES+ ( 'orders_status_backfill', 'my_change', 'shop.orders'+ , 'shop.backfill_orders_status', 'id', 'bigint' );+ """+ registrationsIn src @?= ordersRegistered+ , testCase "a file with no registering insert registers nothing" $ do+ registrationsIn "alter table shop.orders add column note text;" @?= Map.empty+ , -- Only the insert creates a backfill.+ testCase "an update to the registry is not a registration" $ do+ registrationsIn "update deferred.migration set target_batch_ms = 4000 where name = 'x';"+ @?= Map.empty+ ]+++ordersRegistered :: Map Text (Set Text)+ordersRegistered =+ Map.singleton "shop.orders" (Set.singleton "orders_status_backfill")+++twoOnOrders :: Map Text (Set Text)+twoOnOrders =+ Map.singleton+ "shop.orders"+ (Set.fromList ["orders_status_backfill", "orders_channel_backfill"])+++validateOrders :: Text+validateOrders = "alter table shop.orders validate constraint orders_status_fkey;"
+ test/Sqint/DeploySpec.hs view
@@ -0,0 +1,74 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.DeploySpec (tests) where++import Data.Map.Strict qualified as Map+import Data.Set qualified as Set+import RIO+import Sqint.Deploy (RelOid (..), TableStat (..), computeImpacts, lockFindings)+import Sqint.Deploy.Connection (parseSettings)+import Sqint.Deploy.Introspector (RelFileNode (..), TableName (..))+import Sqint.Deploy.Observer (PidLock (..))+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (renderRule)+import Test.Tasty+import Test.Tasty.HUnit+++tests :: TestTree+tests =+ testGroup+ "Deploy"+ [ testGroup+ -- `parseSettings` defers syntactic validation to libpq, so+ -- the tests pin the contract we *do* enforce here: empty+ -- in → Left, anything non-empty → Right.+ "Connection.parseSettings (non-empty pass-through; format deferred to libpq)"+ [ testCase "accepts a postgres:// URI shape"+ $ isRight (parseSettings "postgres://user:pw@localhost:5432/dbname")+ @?= True+ , testCase "accepts a libpq key=value DSN shape"+ $ isRight (parseSettings "host=localhost user=app dbname=app")+ @?= True+ , testCase "accepts arbitrary non-empty text (libpq will reject at acquire time)"+ $ isRight (parseSettings "not-really-a-dsn")+ @?= True+ , testCase "rejects an empty string"+ $ isLeft (parseSettings "")+ @?= True+ ]+ , lockFindingsTests+ ]+++-- The inputs mirror what the dynamic pass observes for `create index`: the heap+-- scan raises seq_scan, and the observer only lists locks on committed tables.+lockFindingsTests :: TestTree+lockFindingsTests =+ testGroup+ "computeImpacts + lockFindings"+ [ testCase "create index on a table created earlier in the same change is not reported"+ $ findings Set.empty (scanned newTable newOid)+ @?= []+ , testCase "create index on a pre-existing table is reported"+ $ findings (Set.singleton (PidLock oldTable "ShareLock")) (scanned oldTable oldOid)+ @?= [("lock/observed-share", SeverityWarn)]+ , testCase "a scan of a pre-existing table locked by an earlier statement is still a BLOCK"+ $ findings Set.empty (scanned oldTable oldOid)+ @?= [("lock/observed-access-exclusive", SeverityBlock)]+ , testCase "a scan of a pre-existing table renamed earlier in the change is still a BLOCK"+ $ findings Set.empty (scanned (TableName "ledger.renamed_file") oldOid)+ @?= [("lock/observed-access-exclusive", SeverityBlock)]+ ]+ where+ oldTable = TableName "ledger.bank_statement_file"+ newTable = TableName "ledger.card_statement_file"+ oldOid = RelOid 1001+ newOid = RelOid 2002+ existing = Set.singleton oldOid+ stat oid scans = TableStat{relOid = oid, relFileNode = RelFileNode 1, seqScans = scans}+ scanned tname oid = (Map.singleton tname (stat oid 0), Map.singleton tname (stat oid 1))+ findings locks (statsBefore, statsAfter) =+ map summary (lockFindings range locks (computeImpacts existing statsBefore statsAfter))+ range = SourceRange{path = "test.sql", startLine = 1, startCol = 1, endLine = 1, endCol = 1}+ summary Finding{rule, severity} = (renderRule rule, severity)
+ test/Sqint/DomainsSpec.hs view
@@ -0,0 +1,111 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.DomainsSpec (tests) where++import Data.ByteString qualified as BS+import Data.Set qualified as Set+import RIO+import RIO.Directory (createDirectoryIfMissing)+import RIO.FilePath ((</>))+import Sqint.DeployTree (loadDeployTree)+import Sqint.Diagnostic (Finding (..))+import Sqint.Domains (DomainSet (..), loadDomainSet)+import Sqint.Rule (renderRule)+import Test.Tasty+import Test.Tasty.HUnit+++-- | A domain with no CHECK; the lock-class rule shouldn't care.+domainWithoutCheck :: Text+domainWithoutCheck =+ "create domain phone as text;"+++-- | A domain with a CHECK, the kind the ADD COLUMN rule looks for.+domainWithCheck :: Text+domainWithCheck =+ "create domain ssn as text check (length(value) = 11);"+++-- | A migration that creates a domain inline; the loader must look+-- outside @type/@ to find these.+inlineMigration :: Text+inlineMigration =+ "create domain canbeencrypted_20000 as text check (length(value) <= 20000);"+++-- | A file that mentions `create domain` (so it isn't skipped by the+-- text-prefilter) but is malformed enough to fail libpg_query —+-- A parse failure must surface as a 'WARN' finding.+unparseable :: Text+unparseable =+ "create domain broken as ¯\\_(ツ)_/¯"+++tests :: TestTree+tests =+ testGroup+ "Domains"+ [ testCase "non-existent root returns an empty set" $ do+ result <- loadDeployTree "/tmp/nonexistent-domains-fixture" >>= loadDomainSet+ result.withCheck @?= mempty+ result.parseFailures @?= []+ , testCase "loads check-bearing domains and skips plain ones"+ $ withSystemTempDirectory "lint-domains"+ $ \root -> do+ let typeDir = root </> "deploy" </> "type"+ createDirectoryIfMissing True typeDir+ writeFileUtf8 (typeDir </> "ssn.sql") domainWithCheck+ writeFileUtf8 (typeDir </> "phone.sql") domainWithoutCheck+ result <- loadDeployTree root >>= loadDomainSet+ result.withCheck @?= Set.fromList ["ssn"]+ result.parseFailures @?= []+ , testCase "scans every .sql under the root, not only type/"+ $ withSystemTempDirectory "lint-domains"+ $ \root -> do+ let typeDir = root </> "deploy" </> "type"+ migDir = root </> "deploy" </> "migrations" </> "2024" </> "11"+ createDirectoryIfMissing True typeDir+ createDirectoryIfMissing True migDir+ writeFileUtf8 (typeDir </> "ssn.sql") domainWithCheck+ writeFileUtf8 (migDir </> "inline.sql") inlineMigration+ result <- loadDeployTree root >>= loadDomainSet+ result.withCheck @?= Set.fromList ["canbeencrypted_20000", "ssn"]+ , testCase "siblings of deploy/ (revert, verify, test) are not scanned"+ $ withSystemTempDirectory "lint-domains"+ $ \root -> do+ let deployDir = root </> "deploy" </> "type"+ revertDir = root </> "revert" </> "type"+ createDirectoryIfMissing True deployDir+ createDirectoryIfMissing True revertDir+ writeFileUtf8 (deployDir </> "ssn.sql") domainWithCheck+ -- revert/ would not redefine the domain in real life,+ -- but if it did, the loader must ignore it.+ writeFileUtf8 (revertDir </> "ghost.sql") "create domain ghost as text check (length(value) > 0);"+ result <- loadDeployTree root >>= loadDomainSet+ result.withCheck @?= Set.fromList ["ssn"]+ , testCase "a deploy script that is not UTF-8 fails the run"+ $ withSystemTempDirectory "lint-domains"+ $ \root -> do+ let typeDir = root </> "deploy" </> "type"+ createDirectoryIfMissing True typeDir+ writeFileUtf8 (typeDir </> "ssn.sql") domainWithCheck+ BS.writeFile (typeDir </> "undecodable.sql") (BS.pack [0x63, 0x72, 0xff, 0xfe, 0x65])+ -- Skipping it quietly would let the ADD COLUMN rule report a+ -- clean bill of health for a file it never read. Every text+ -- file in the repository is UTF-8, so this is a broken tree,+ -- not a case to tolerate.+ loaded <- tryAny (loadDeployTree root >>= loadDomainSet)+ case loaded of+ Left _ -> pure ()+ Right _ -> assertFailure "expected the undecodable deploy script to fail the run"+ , testCase "parse failures surface a WARN finding"+ $ withSystemTempDirectory "lint-domains"+ $ \root -> do+ let typeDir = root </> "deploy" </> "type"+ createDirectoryIfMissing True typeDir+ writeFileUtf8 (typeDir </> "broken.sql") unparseable+ result <- loadDeployTree root >>= loadDomainSet+ length result.parseFailures @?= 1+ map (renderRule . (.rule)) result.parseFailures @?= ["setup/unparsable-domain-file"]+ ]
+ test/Sqint/LockSpec.hs view
@@ -0,0 +1,54 @@+module Sqint.LockSpec (tests) where++import RIO+import Sqint.Diagnostic (Severity (..))+import Sqint.Lock (LockClass (..), LockProfile (..), RewriteImpact (..), lockClassName, parseLockMode, severityFor)+import Test.Tasty+import Test.Tasty.HUnit+++tests :: TestTree+tests =+ testGroup+ "Lock"+ [ testCase "AccessExclusive + TableScan blocks"+ $ severityFor (LockProfile AccessExclusive TableScan)+ @?= SeverityBlock+ , testCase "AccessExclusive + TableRewrite blocks"+ $ severityFor (LockProfile AccessExclusive TableRewrite)+ @?= SeverityBlock+ , testCase "AccessExclusive + NoImpact is info (catalog-only, held briefly)"+ $ severityFor (LockProfile AccessExclusive NoImpact)+ @?= SeverityInfo+ , testCase "Share + TableScan warns"+ $ severityFor (LockProfile Share TableScan)+ @?= SeverityWarn+ , testCase "ShareUpdateExclusive + anything is info"+ $ severityFor (LockProfile ShareUpdateExclusive TableScan)+ @?= SeverityInfo+ , testCase "RowExclusive is info"+ $ severityFor (LockProfile RowExclusive NoImpact)+ @?= SeverityInfo+ , testGroup+ "parseLockMode covers every relation-level lock mode"+ [ testCase mode+ $ parseLockMode (fromString mode)+ @?= Just expected+ | (mode, expected) <-+ [ ("AccessShareLock", AccessShare)+ , ("RowShareLock", RowShare)+ , ("RowExclusiveLock", RowExclusive)+ , ("ShareUpdateExclusiveLock", ShareUpdateExclusive)+ , ("ShareLock", Share)+ , ("ShareRowExclusiveLock", ShareRowExclusive)+ , ("ExclusiveLock", Exclusive)+ , ("AccessExclusiveLock", AccessExclusive)+ ]+ ]+ , testCase "parseLockMode rejects unknown modes"+ $ parseLockMode "NoSuchLock"+ @?= Nothing+ , testCase "lockClassName for the most severe class is \"AccessExclusive\""+ $ lockClassName AccessExclusive+ @?= "AccessExclusive"+ ]
+ test/Sqint/OutputSpec.hs view
@@ -0,0 +1,62 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.OutputSpec (tests) where++import Data.Text qualified as T+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Output (OutputFormat (..), renderFindings)+import Sqint.Rule (Rule (..), renderRule)+import Test.Tasty+import Test.Tasty.HUnit+++finding :: Severity -> Rule -> Maybe Text -> Finding+finding severity rule suppressedBy =+ Finding+ { range = SourceRange{path = "f.sql", startLine = 1, startCol = 1, endLine = 1, endCol = 1}+ , severity+ , rule+ , title = renderRule rule <> " title"+ , detail = ""+ , suppressedBy+ }+++sample :: [Finding]+sample =+ [ finding SeverityBlock LockAddColumn Nothing+ , finding SeverityWarn TxnSetLocalAcrossCommit Nothing+ , finding SeverityInfo DeployNonTransactional Nothing+ , finding SeverityWarn IndexCastOnColumn (Just "acknowledged")+ ]+++render :: Bool -> Text+render verbose = renderFindings OutputText verbose sample+++tests :: TestTree+tests =+ testGroup+ "Output.renderFindings (text)"+ [ testCase "default shows only un-suppressed BLOCK/WARN" $ do+ let out = render False+ assertBool "shows BLOCK" ("lock/add-column" `T.isInfixOf` out)+ assertBool "shows WARN" ("txn/set-local-across-commit" `T.isInfixOf` out)+ assertBool "hides INFO" (not ("deploy/non-transactional" `T.isInfixOf` out))+ assertBool "hides suppressed" (not ("index/cast-on-column" `T.isInfixOf` out))+ , testCase "default footer counts the hidden findings"+ $ assertBool+ "footer mentions 2 hidden"+ ("2 informational or suppressed findings hidden" `T.isInfixOf` render False)+ , testCase "verbose shows everything and no footer" $ do+ let out = render True+ assertBool "shows INFO" ("deploy/non-transactional" `T.isInfixOf` out)+ assertBool "shows suppressed" ("index/cast-on-column" `T.isInfixOf` out)+ assertBool "no hidden footer" (not ("hidden — pass --verbose" `T.isInfixOf` out))+ , testCase "no footer when nothing is hidden" $ do+ let out = renderFindings OutputText False [finding SeverityBlock DeployFailed Nothing]+ assertBool "shows the block" ("deploy/failed" `T.isInfixOf` out)+ assertBool "no footer" (not ("hidden" `T.isInfixOf` out))+ ]
+ test/Sqint/PgAstSpec.hs view
@@ -0,0 +1,147 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.PgAstSpec (tests) where++import Data.Set qualified as Set+import Data.Text qualified as T+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.PgAst (classifySql)+import Test.Tasty+import Test.Tasty.HUnit+++-- | Most tests don't exercise the CHECK-domain rule.+noDomains :: FilePath -> Text -> IO [Finding]+noDomains = classifySql mempty+++withDomains :: [Text] -> FilePath -> Text -> IO [Finding]+withDomains domains = classifySql (Set.fromList domains)+++tests :: TestTree+tests =+ testGroup+ "PgAst"+ [ testGroup+ "empty / trivial"+ [ testCase "empty source yields no findings" $ do+ findings <- noDomains "empty.sql" ""+ findings @?= []+ , testCase "plain SELECT yields no findings" $ do+ findings <- noDomains "select.sql" "select 1;"+ findings @?= []+ , testCase "CREATE TABLE is not a lock concern" $ do+ findings <- noDomains "create.sql" "create table foo (id int primary key);"+ findings @?= []+ ]+ , testGroup+ "ADD COLUMN"+ [ testCase "ADD COLUMN NOT NULL without DEFAULT blocks (PMA-1)" $ do+ let sql = "alter table foo add column created_at timestamptz not null;"+ findings <- noDomains "add-not-null.sql" sql+ map (.severity) findings @?= [SeverityBlock]+ , testCase "ADD COLUMN NOT NULL with DEFAULT is info (catalog-only)" $ do+ let sql = "alter table foo add column created_at timestamptz not null default now();"+ findings <- noDomains "add-with-default.sql" sql+ map (.severity) findings @?= [SeverityInfo]+ , testCase "ADD COLUMN nullable is info (catalog-only)" $ do+ let sql = "alter table foo add column note text;"+ findings <- noDomains "add-nullable.sql" sql+ map (.severity) findings @?= [SeverityInfo]+ , testCase "ADD COLUMN of a CHECK-bearing domain blocks (R6)" $ do+ let sql = "alter table foo add column code ssn;"+ findings <- withDomains ["ssn"] "add-domain.sql" sql+ map (.severity) findings @?= [SeverityBlock]+ , testCase "ADD COLUMN of a non-CHECK domain does not upgrade severity" $ do+ let sql = "alter table foo add column code ssn;"+ findings <- withDomains [] "add-plain-domain.sql" sql+ map (.severity) findings @?= [SeverityInfo]+ ]+ , testGroup+ "ADD CONSTRAINT"+ [ testCase "ADD CHECK without NOT VALID blocks" $ do+ let sql = "alter table foo add constraint c check (x > 0);"+ findings <- noDomains "add-check.sql" sql+ map (.severity) findings @?= [SeverityBlock]+ , testCase "ADD CHECK ... NOT VALID is info (catalog-only)" $ do+ let sql = "alter table foo add constraint c check (x > 0) not valid;"+ findings <- noDomains "add-check-not-valid.sql" sql+ map (.severity) findings @?= [SeverityInfo]+ , testCase "ADD FOREIGN KEY without NOT VALID blocks" $ do+ let sql =+ "alter table orders add constraint fk_customer "+ <> "foreign key (customer_id) references customers (id);"+ findings <- noDomains "add-fk.sql" sql+ map (.severity) findings @?= [SeverityBlock]+ , testCase "ADD FOREIGN KEY ... NOT VALID is info (catalog-only)" $ do+ let sql =+ "alter table orders add constraint fk_customer "+ <> "foreign key (customer_id) references customers (id) not valid;"+ findings <- noDomains "add-fk-not-valid.sql" sql+ map (.severity) findings @?= [SeverityInfo]+ ]+ , testGroup+ "ALTER COLUMN TYPE"+ [ testCase "ALTER COLUMN TYPE blocks" $ do+ let sql = "alter table foo alter column note type text;"+ findings <- noDomains "alter-type.sql" sql+ map (.severity) findings @?= [SeverityBlock]+ ]+ , testGroup+ "CREATE INDEX"+ [ testCase "CREATE INDEX (non-concurrent) warns" $ do+ findings <- noDomains "create-index.sql" "create index foo_idx on foo (x);"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "CREATE INDEX CONCURRENTLY is allowed" $ do+ let sql = "create index concurrently foo_idx on foo (x);"+ findings <- noDomains "create-index-concurrent.sql" sql+ map (.severity) findings @?= [SeverityInfo]+ ]+ , testGroup+ "DROP INDEX"+ [ testCase "DROP INDEX (non-concurrent) is info (brief catalog-only lock)" $ do+ findings <- noDomains "drop-index.sql" "drop index foo_idx;"+ map (.severity) findings @?= [SeverityInfo]+ , testCase "DROP INDEX CONCURRENTLY is allowed" $ do+ findings <- noDomains "drop-index-concurrent.sql" "drop index concurrently foo_idx;"+ map (.severity) findings @?= [SeverityInfo]+ ]+ , testGroup+ "ALTER DOMAIN"+ [ testCase "ALTER DOMAIN ADD CONSTRAINT without NOT VALID blocks" $ do+ let sql = "alter domain ssn add constraint c check (length(value) = 11);"+ findings <- noDomains "alter-domain.sql" sql+ map (.severity) findings @?= [SeverityBlock]+ , testCase "ALTER DOMAIN ADD CONSTRAINT ... NOT VALID is info (catalog-only)" $ do+ let sql = "alter domain ssn add constraint c check (length(value) = 11) not valid;"+ findings <- noDomains "alter-domain-not-valid.sql" sql+ map (.severity) findings @?= [SeverityInfo]+ ]+ , testGroup+ "Source range tracking"+ [ testCase "first-statement range starts at line 1" $ do+ let sql = "create index foo_idx on foo (x);"+ findings <- noDomains "ranges.sql" sql+ map (\f -> f.range.startLine) findings @?= [1]+ , testCase "a later statement spans its own lines, not the gap before it" $ do+ -- libpg_query starts every statement but the first just past+ -- the previous semicolon, so the header, the blank lines and+ -- the comment here all belong to the index's raw span.+ let sql =+ T.unlines+ [ "-- Deploy app:widgets to pg" -- 1+ , "" -- 2+ , "begin;" -- 3+ , "" -- 4+ , "-- for lookups by name" -- 5+ , "create index widgets_name" -- 6+ , " on widgets (name);" -- 7+ , "" -- 8+ , "commit;" -- 9+ ]+ findings <- noDomains "ranges.sql" sql+ map (\f -> (f.range.startLine, f.range.endLine)) findings @?= [(6, 7)]+ ]+ ]
+ test/Sqint/PlanCheckSpec.hs view
@@ -0,0 +1,114 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.PlanCheckSpec (tests) where++import RIO+import Sqint.Deploy.PlanCheck (Candidate (..), Plan (..), diffPlans, stripPartitionSuffix)+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Test.Tasty+import Test.Tasty.HUnit+++tests :: TestTree+tests =+ testGroup+ "PlanCheck"+ [ stripPartitionSuffixTests+ , diffPlansTests+ ]+++-- ---------------------------------------------------------------------+-- stripPartitionSuffix+-- ---------------------------------------------------------------------++stripPartitionSuffixTests :: TestTree+stripPartitionSuffixTests =+ testGroup+ "stripPartitionSuffix"+ [ testCase "strips a _p<digits> partition suffix"+ $ stripPartitionSuffix "checkout_session_p20260201"+ @?= "checkout_session"+ , testCase "strips _default"+ $ stripPartitionSuffix "checkout_session_default"+ @?= "checkout_session"+ , testCase "leaves an unsuffixed relation alone"+ $ stripPartitionSuffix "shop.orders"+ @?= "shop.orders"+ , testCase "does not strip _p followed by non-digits"+ $ stripPartitionSuffix "table_partial"+ @?= "table_partial"+ , testCase "preserves schema-qualified names"+ $ stripPartitionSuffix "shop.checkout_session_p20260201"+ @?= "shop.checkout_session"+ ]+++-- ---------------------------------------------------------------------+-- diffPlans+-- ---------------------------------------------------------------------++dummyCandidate :: Candidate+dummyCandidate =+ Candidate+ { sql = "select 1;"+ , range = SourceRange{path = "test.sql", startLine = 1, startCol = 1, endLine = 1, endCol = 1}+ }+++seqScanOn :: Text -> Plan+seqScanOn rel = Plan{nodeType = "Seq Scan", relationName = Just rel, indexName = Nothing, plans = []}+++indexScanOn :: Text -> Plan+indexScanOn rel =+ Plan{nodeType = "Index Scan", relationName = Just rel, indexName = Just (rel <> "_pkey"), plans = []}+++-- Wrap a list of leaf scans under an Append-like parent so we can test+-- multi-scan plans without inventing more node-type strings.+container :: [Plan] -> Plan+container children = Plan{nodeType = "Append", relationName = Nothing, indexName = Nothing, plans = children}+++diffPlansTests :: TestTree+diffPlansTests =+ testGroup+ "diffPlans"+ [ testCase "Seq Scan becoming Index Scan emits one BLOCK" $ do+ let castPlan = seqScanOn "checkout_session"+ noCastPlan = indexScanOn "checkout_session"+ map (.severity) (diffPlans dummyCandidate castPlan noCastPlan) @?= [SeverityBlock]+ , testCase "matching Seq Scans on both sides do not flag" $ do+ let castPlan = seqScanOn "checkout_session"+ noCastPlan = seqScanOn "checkout_session"+ diffPlans dummyCandidate castPlan noCastPlan @?= []+ , testCase "matching Index Scans on both sides do not flag" $ do+ let castPlan = indexScanOn "checkout_session"+ noCastPlan = indexScanOn "checkout_session"+ diffPlans dummyCandidate castPlan noCastPlan @?= []+ , testCase "self-join: cast has 2 Seq Scans, no-cast has 1 Seq + 1 Index — flag" $ do+ let castPlan = container [seqScanOn "orders", seqScanOn "orders"]+ noCastPlan = container [seqScanOn "orders", indexScanOn "orders"]+ map (.severity) (diffPlans dummyCandidate castPlan noCastPlan) @?= [SeverityBlock]+ , testCase "self-join: cast and no-cast both have 2 Seq Scans — do not flag" $ do+ let castPlan = container [seqScanOn "orders", seqScanOn "orders"]+ noCastPlan = container [seqScanOn "orders", seqScanOn "orders"]+ diffPlans dummyCandidate castPlan noCastPlan @?= []+ , testCase "partitioned: cast has Seq Scans on partitions, no-cast has Index Scans — flag" $ do+ let castPlan =+ container+ [seqScanOn "checkout_session_p20260201", seqScanOn "checkout_session_p20260301"]+ noCastPlan =+ container+ [indexScanOn "checkout_session_p20260201", indexScanOn "checkout_session_p20260301"]+ findings = diffPlans dummyCandidate castPlan noCastPlan+ map (.severity) findings @?= [SeverityBlock]+ -- the title rolls partitions up to a single root via stripPartitionSuffix+ map (.title) findings @?= ["Cast on a column forces a sequential scan on checkout_session"]+ , testCase "multi-relation: only the regressed relation is named" $ do+ let castPlan = container [seqScanOn "orders", seqScanOn "customer"]+ noCastPlan = container [indexScanOn "orders", seqScanOn "customer"]+ findings = diffPlans dummyCandidate castPlan noCastPlan+ map (.title) findings @?= ["Cast on a column forces a sequential scan on orders"]+ ]
+ test/Sqint/QueryPlanSpec.hs view
@@ -0,0 +1,166 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.QueryPlanSpec (tests) where++import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.QueryPlan (detectIndexedCasts)+import Sqint.Rule (renderRule)+import Test.Tasty+import Test.Tasty.HUnit+++tests :: TestTree+tests =+ testGroup+ "QueryPlan"+ [ testCase "empty source yields no findings" $ do+ findings <- detectIndexedCasts "empty.sql" ""+ findings @?= []+ , testCase "plain WHERE on a column does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where id = 5;"+ findings @?= []+ , testCase "WHERE id::text = ... warns (PMA-2 shape)" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where id::text = 'foo';"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "UPDATE ... WHERE id::text = ... warns" $ do+ findings <- detectIndexedCasts "p.sql" "update orders set y = 1 where id::text = 'foo';"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "DELETE ... WHERE id::text = ... warns" $ do+ findings <- detectIndexedCasts "p.sql" "delete from orders where id::text = 'foo';"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "cast on a literal does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where id = '5'::int;"+ findings @?= []+ , testCase "nested boolean: AND with column cast warns" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where status = 'paid' and id::text = 'foo';"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "JOIN ... ON a.id::text = b.ref warns (ON predicate context)" $ do+ findings <- detectIndexedCasts "p.sql" "select * from a join b on a.id::text = b.ref;"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "WHERE id::text IN (...) warns" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where id::text in ('a', 'b');"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "WHERE id::text NOT IN (...) warns" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where id::text not in ('a', 'b');"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "cast in the SELECT projection does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "select id::text from orders;"+ findings @?= []+ , testCase "cast in a CTE projection does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "with c as (select id::text as i from orders) select * from c;"+ findings @?= []+ , testCase "filtering on a CTE's cast projection output does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "with c as (select id::text as i from orders) select * from c where i = 'x';"+ findings @?= []+ , testCase "comparison in the projection (not a scan qual) does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "select id::text = 'x' as m from orders;"+ findings @?= []+ , testCase "cast in a RETURNING list does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "update orders set y = 1 where x = 2 returning id::text;"+ findings @?= []+ , testCase "cast in an UPDATE SET assignment does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "update orders set ref = id::text where x = 2;"+ findings @?= []+ , testCase "cast in HAVING does not warn (post-aggregation, off the scan path)" $ do+ findings <- detectIndexedCasts "p.sql" "select m from orders group by m having m::text = 'x';"+ findings @?= []+ , testCase "aggregate in HAVING does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "select m from orders group by m having count(*) > 5;"+ findings @?= []+ , testCase "WHERE lower(id) = ... warns as index/function-on-column" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where lower(id) = 'foo';"+ map (.severity) findings @?= [SeverityWarn]+ map (renderRule . (.rule)) findings @?= ["index/function-on-column"]+ , testCase "WHERE date_trunc on a column warns" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where date_trunc('day', created_at) = '2026-01-01';"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "JOIN ... ON lower(a.id) = b.k warns" $ do+ findings <- detectIndexedCasts "p.sql" "select * from a join b on lower(a.id) = b.k;"+ map (renderRule . (.rule)) findings @?= ["index/function-on-column"]+ , testCase "function on a constant does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where created_at > now();"+ findings @?= []+ , testCase "function call in the SELECT projection does not warn" $ do+ findings <- detectIndexedCasts "p.sql" "select lower(id) from orders;"+ findings @?= []+ , testCase "cast in a partial-index predicate warns" $ do+ findings <- detectIndexedCasts "p.sql" "create index on orders (m) where id::text = 'x';"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "cast in a subquery's WHERE warns" $ do+ findings <- detectIndexedCasts "p.sql" "select * from a where x = (select count(*) from b where b.id::text = 'k');"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "cast in a MERGE ... ON predicate warns (generic walk descends MERGE)" $ do+ findings <- detectIndexedCasts "p.sql" "merge into t using s on t.id::text = s.k when matched then update set a = 1;"+ map (.severity) findings @?= [SeverityWarn]+ , testCase "rule id is index/cast-on-column" $ do+ findings <- detectIndexedCasts "p.sql" "select * from orders where id::text = 'foo';"+ map (renderRule . (.rule)) findings @?= ["index/cast-on-column"]+ , testCase "cast inside a plpgsql trigger body warns at the body line" $ do+ let body =+ """+ create or replace function f() returns trigger as+ $$+ begin+ update shop.checkout_session+ set tally = tally + 1+ where customer_id = new.customer_id+ and id::text = new.order_reference;+ return new;+ end+ $$ language plpgsql;+ """+ findings <- detectIndexedCasts "trigger.sql" body+ map (.severity) findings @?= [SeverityWarn]+ map ((.startLine) . (.range)) findings @?= [4]+ , testCase "cast inside an IF/THEN inside plpgsql still warns" $ do+ let body =+ """+ create or replace function f() returns void as+ $$+ begin+ if true then+ update orders set y = 1 where id::text = 'foo';+ end if;+ end+ $$ language plpgsql;+ """+ findings <- detectIndexedCasts "guard.sql" body+ map (.severity) findings @?= [SeverityWarn]+ , testCase "no warn when plpgsql body has no column-ref cast" $ do+ let body =+ """+ create or replace function f() returns trigger as+ $$+ begin+ update orders set y = 1 where id = new.id;+ return new;+ end+ $$ language plpgsql;+ """+ findings <- detectIndexedCasts "clean.sql" body+ findings @?= []+ , testCase "cast inside a BEGIN ATOMIC function body warns" $ do+ let body =+ """+ create or replace function f(p text) returns setof orders+ begin atomic+ select * from orders where id::text = p;+ end;+ """+ findings <- detectIndexedCasts "atomic.sql" body+ map (.severity) findings @?= [SeverityWarn]+ , testCase "dollar-tagged plpgsql body still works" $ do+ let body =+ """+ create or replace function f() returns trigger as+ $func$+ begin+ update orders set y = 1 where id::text = 'foo';+ return new;+ end+ $func$ language plpgsql;+ """+ findings <- detectIndexedCasts "tagged.sql" body+ map (.severity) findings @?= [SeverityWarn]+ ]
+ test/Sqint/SetLocalSpec.hs view
@@ -0,0 +1,141 @@+{-# LANGUAGE OverloadedStrings #-}++module Sqint.SetLocalSpec (tests) where++import Data.String.Interpolate (i)+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.Rule (renderRule)+import Sqint.SetLocal (detectSetLocalAcrossCommit)+import Test.Tasty+import Test.Tasty.HUnit+++tests :: TestTree+tests =+ testGroup+ "SetLocal"+ [ testCase "empty source yields no findings" $ do+ findings <- detectSetLocalAcrossCommit "empty.sql" ""+ findings @?= []+ , testCase "SET LOCAL in a DO block that COMMITs is blocked" $ do+ findings <- detectSetLocalAcrossCommit "b.sql" batchingDoBlock+ map (.severity) findings @?= [SeverityBlock]+ map (renderRule . (.rule)) findings @?= ["txn/set-local-across-commit"]+ , testCase "set_config(.., true) in a block that COMMITs is blocked" $ do+ findings <- detectSetLocalAcrossCommit "b.sql" (batchingWith "perform set_config('lock_timeout', '50ms', true);")+ map (.severity) findings @?= [SeverityBlock]+ , -- The correct shape (bulk_update.tmpl): session scope survives COMMIT.+ testCase "set_config(.., false) in a block that COMMITs is fine" $ do+ findings <- detectSetLocalAcrossCommit "b.sql" (batchingWith "perform set_config('lock_timeout', '50ms', false);")+ findings @?= []+ , -- Without a COMMIT the transaction scope is the whole block.+ testCase "SET LOCAL with no COMMIT anywhere is fine" $ do+ let body =+ """+ do $$+ begin+ set local lock_timeout to '50ms';+ update orders set y = 1;+ end $$;+ """+ findings <- detectSetLocalAcrossCommit "b.sql" body+ findings @?= []+ , testCase "ROLLBACK ends the transaction just as effectively" $ do+ let body =+ """+ do $$+ begin+ set local lock_timeout to '50ms';+ loop+ update orders set y = 1;+ rollback;+ end loop;+ end $$;+ """+ findings <- detectSetLocalAcrossCommit "b.sql" body+ map (.severity) findings @?= [SeverityBlock]+ , testCase "a plpgsql function body is checked, not just DO blocks" $ do+ let body =+ """+ create or replace procedure p() as+ $$+ begin+ set local lock_timeout to '50ms';+ loop+ update orders set y = 1;+ commit;+ end loop;+ end+ $$ language plpgsql;+ """+ findings <- detectSetLocalAcrossCommit "p.sql" body+ map (.severity) findings @?= [SeverityBlock]+ , -- Formatting must not smuggle a transaction-scoped set_config past the match.+ testCase "set_config spread over several lines is still matched" $ do+ let body =+ """+ do $$+ begin+ perform set_config('lock_timeout',+ '50ms',+ true);+ loop+ update orders set y = 1;+ commit;+ end loop;+ end $$;+ """+ findings <- detectSetLocalAcrossCommit "b.sql" body+ map (.severity) findings @?= [SeverityBlock]+ , testCase "a SQL-language function is not inspected" $ do+ let body =+ """+ create or replace function f() returns int as+ $$ select 1 $$ language sql;+ """+ findings <- detectSetLocalAcrossCommit "f.sql" body+ findings @?= []+ , -- Unparseable bodies produce no findings rather than aborting the linter.+ testCase "unparseable source yields no findings" $ do+ findings <- detectSetLocalAcrossCommit "junk.sql" "this is not sql at all ("+ findings @?= []+ , testCase "both settings in one block are reported separately" $ do+ let body =+ """+ do $$+ begin+ set local lock_timeout to '50ms';+ perform set_config('synchronous_commit', 'remote_apply', true);+ loop+ update orders set y = 1;+ commit;+ end loop;+ end $$;+ """+ findings <- detectSetLocalAcrossCommit "b.sql" body+ length findings @?= 2+ , testCase "the finding points at the offending line, not the block" $ do+ findings <- detectSetLocalAcrossCommit "b.sql" batchingDoBlock+ map ((.startLine) . (.range)) findings @?= [3]+ ]+++-- | A transaction-scoped setting above a loop that COMMITs per batch.+batchingDoBlock :: Text+batchingDoBlock = batchingWith "set local lock_timeout to '50ms';"+++-- | A batching DO block whose first statement is the given one.+batchingWith :: Text -> Text+batchingWith setting =+ [i|do $$+begin+ #{setting}+ loop+ update orders set y = 1 where x = 2;+ exit when not found;+ commit;+ end loop;+end $$;+|]
+ test/Sqint/SuppressionSpec.hs view
@@ -0,0 +1,107 @@+module Sqint.SuppressionSpec (tests) where++import Data.Text qualified as T+import RIO+import Sqint.Diagnostic (Finding (..), Severity (..), SourceRange (..))+import Sqint.PgAst (classifySql)+import Sqint.Rule (Rule (..), renderRule)+import Sqint.Suppression (Annotation (..), applyAnnotations, parseAnnotations)+import Test.Tasty+import Test.Tasty.HUnit+++tests :: TestTree+tests =+ testGroup+ "Suppression"+ [ testCase "standalone annotation targets next non-blank line" do+ let src =+ """+ -- lint:ignore reason="empty table"++ create index on foo(x);+ """+ let (annotations, _) = parseAnnotations "file.sql" src+ map (\a -> a.line) annotations @?= [3]+ , testCase "trailing annotation targets its own line" do+ let src = T.unlines ["create index on foo(x); -- lint:ignore reason=\"empty\""]+ let (annotations, _) = parseAnnotations "file.sql" src+ map (\a -> a.line) annotations @?= [1]+ , testCase "reason is extracted" do+ let src = "-- lint:ignore reason=\"because reasons\"\ncreate index on foo(x);\n"+ let (annotations, _) = parseAnnotations "file.sql" src+ map (\a -> a.reason) annotations @?= ["because reasons"]+ , testCase "annotation without reason yields a warn finding" do+ let src =+ """+ -- lint:ignore+ create index on foo(x);+ """+ let (annotations, malformed) = parseAnnotations "file.sql" src+ length annotations @?= 0+ map (\f -> f.severity) malformed @?= [SeverityWarn]+ map (\f -> f.range.startLine) malformed @?= [1]+ map (\f -> renderRule f.rule) malformed @?= ["suppression/missing-reason"]+ , testCase "annotation with empty reason yields a warn finding" do+ let src =+ """+ -- lint:ignore reason=""+ create index on foo(x);+ """+ let (annotations, malformed) = parseAnnotations "file.sql" src+ length annotations @?= 0+ map (\f -> renderRule f.rule) malformed @?= ["suppression/missing-reason"]+ , testCase "matching annotation marks finding suppressed" do+ let f =+ Finding+ { range = SourceRange "file.sql" 3 1 3 30+ , severity = SeverityBlock+ , rule = LockAddConstraint+ , title = "AccessExclusive + TableScan"+ , detail = ""+ , suppressedBy = Nothing+ }+ let annotations = [Annotation{line = 3, reason = "because"}]+ map (\g -> g.suppressedBy) (applyAnnotations annotations [f]) @?= [Just "because"]+ , testCase "non-matching annotation leaves finding active" do+ let f =+ Finding+ { range = SourceRange "file.sql" 3 1 3 30+ , severity = SeverityBlock+ , rule = LockAddColumn+ , title = "t"+ , detail = ""+ , suppressedBy = Nothing+ }+ let annotations = [Annotation{line = 7, reason = "wrong"}]+ map (\g -> g.suppressedBy) (applyAnnotations annotations [f]) @?= [Nothing]+ , testCase "each annotation silences the statement it is written against" do+ -- Above a statement, or trailing any of its lines; never the+ -- statement after it.+ let src =+ T.unlines+ [ "-- Deploy app:widgets to pg" -- 1+ , "" -- 2+ , "begin;" -- 3+ , "" -- 4+ , "alter table a add column x int not null; -- lint:ignore reason=\"trailing\"" -- 5+ , "" -- 6+ , "-- lint:ignore reason=\"above\"" -- 7+ , "create index a_x" -- 8+ , " on a (x);" -- 9+ , "" -- 10+ , "create index b_x" -- 11+ , " on b (x); -- lint:ignore reason=\"on its last line\"" -- 12+ , "" -- 13+ , "create index c_x on c (x);" -- 14+ , "commit;" -- 15+ ]+ findings <- classifySql mempty "file.sql" src+ let (annotations, _) = parseAnnotations "file.sql" src+ [(f.range.startLine, f.suppressedBy) | f <- applyAnnotations annotations findings]+ @?= [ (5, Just "trailing")+ , (8, Just "above")+ , (11, Just "on its last line")+ , (14, Nothing)+ ]+ ]