Skip to content

Latest commit

 

History

History
539 lines (439 loc) · 24 KB

postgres-sql-statement-policy.md

File metadata and controls

539 lines (439 loc) · 24 KB

postgres-sql-statement-policy

executorNames replaces the default [query, read, write] list; it does not extend it. Use extraExecutorNames: [readPool, writePool] to keep the defaults and add names. Setting both options is a configuration error. When a replacement omits a default name imported from importSpecifier and called in scoped files, check emits a configuration warning naming the rule or project, the omitted name, an example call site, and the fix. See executor selection. excludeExecutorNames: [query] removes names after replacement or default-plus-extra selection and acknowledges intentional omitted defaults. check warns about exclusions that are not default names or are never imported from the selected module and called in scoped files.

A projects: [<name>] entry inherits projects.<name>.postgres when that block is set. Do not restate importSpecifier, executorNames, extraExecutorNames, excludeExecutorNames, executorFactoryNames, executorTypeNames, trustedSqlTags, schemaCatalogPath, or unanalyzableSql on the rule. include, exclude, and sqlInclude may only narrow the project scope.

Flags configured PostgreSQL statement kinds, settings, and clauses in matching SQL files and configured JavaScript/TypeScript executor calls. Use this to keep tests, helpers, or seed files from changing shared database state or bypassing constraints, or to stop migrations from adding explicit transaction-control statements when the migration runner already owns the transaction. The rule recognizes 37 statement kinds: 29 DDL/truncate kinds (CREATE TABLE, ALTER TABLE, CREATE INDEX, CREATE VIEW, TRUNCATE, DROP INDEX, DROP VIEW, CREATE DATABASE, DROP DATABASE, ALTER DATABASE, ALTER SYSTEM, CREATE SCHEMA, ALTER SCHEMA, DROP SCHEMA, CREATE TRIGGER, DROP TRIGGER, CREATE FUNCTION, CREATE PROCEDURE, DROP FUNCTION, DROP PROCEDURE, DROP TABLE, CREATE TYPE, DROP TYPE, ALTER VIEW, ALTER TRIGGER, ALTER FUNCTION, ALTER PROCEDURE, ALTER INDEX, and ALTER TYPE) and 8 transaction-control kinds (BEGIN, START TRANSACTION, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE SAVEPOINT, and ROLLBACK TO SAVEPOINT). CREATE UNIQUE INDEX counts as CREATE INDEX; materialized views count as CREATE VIEW / DROP VIEW; and CREATE TEMP TABLE counts as CREATE TABLE. ALTER TABLE also covers ENABLE and DISABLE TRIGGER. CREATE OR REPLACE FUNCTION and CREATE OR REPLACE PROCEDURE map to their respective CREATE kinds. PL/pgSQL BEGIN and END block delimiters inside DO, function, and procedure bodies are not reported as transaction-control statements, while explicit COMMIT or ROLLBACK statements inside routine bodies are still reported.

The rule uses shared schema facts (extract_migration_facts, collect_postgres_facts) including direct statements peeled out of executable PL/pgSQL DO, function, and procedure bodies and statically recoverable EXECUTE strings, qualified or unqualified format() templates, and assigned string variables. Routine bodies may be dollar, plain, escaped, Unicode (with custom UESCAPE), or newline-concatenated strings. Ordinary strings, comments, non-PL/pgSQL functions, and runtime-built expressions remain inert. It does not re-parse SQL with a private parser.

The rule checks every complete SQL alternative of a branching executor call, up to 16 versions. Choosing between SELECT and a banned TRUNCATE, or appending a banned setting on only one path, still reports that path. All allowed versions pass without an unanalyzable finding. Findings map to the physical branch fragments for suppressions; opaque or over-cap calls retain unanalyzableSql behavior.

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    options:
      sqlInclude: ["db/config-driven/**/*.sql"]
      bannedStatements:
        - CREATE TABLE
        - ALTER TABLE
        - CREATE INDEX
        - CREATE VIEW
        - TRUNCATE
        - DROP INDEX
        - DROP VIEW

sqlInclude defaults to **/*.sql. Omitting bannedStatements selects the seven default kinds above; setting bannedStatements: [] explicitly disables statement-kind findings. Settings and clauses can still be checked independently. For example, this policy flags statement_timeout changes but permits every statement kind:

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    options:
      importSpecifier: '@scope/psql'
      bannedStatements: []
      bannedSettings: [statement_timeout]
      unanalyzableSql: ignore

bannedSettings is independent: it continues to apply when statement kinds are disabled, and bannedSettings: [] disables setting checks. Embedded SQL is opt-in through importSpecifier or explicit executorNames. With importSpecifier, executor names default to query, read, and write. executorFactoryNames enables local handles returned by configured named factory imports, and executorTypeNames enables parameters annotated with configured imported executor types. trustedSqlTags accepts { module, name } entries, as in postgres-sql-shape-policy.

When supplied, bannedStatements accepts any recognized statement kind, the case-insensitive ddl group (which expands to all 29 DDL/truncate kinds), or the case-insensitive transaction-control group (which expands to all 8 transaction-control kinds). An explicit empty list disables all statement-kind checks. Kind names ignore case and repeated whitespace. An unknown kind or group is a configuration error.

include and exclude may be set on the rule entry or under options. Both placements narrow SQL files and JavaScript/TypeScript executor sources. When both are present, the scopes intersect: a file must pass both include filters and neither exclude filter. Empty include lists leave that layer unrestricted. sqlInclude additionally selects only SQL files.

For example, these nested globs select backend sources while excluding tests:

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    options:
      importSpecifier: '@example/db'
      include: ['backend/**']
      exclude: ['**/__tests__/**']
      bannedSettings: [statement_timeout]
      unanalyzableSql: ignore

unanalyzableSql defaults to fail; ignore skips unanalyzable calls, and fail reports dynamic executor arguments without complete alternatives and unparseable recovered SQL. No executor module or factory is inferred from project conventions.

bannedSettings is an optional list of PostgreSQL configuration parameter names and defaults to empty. Names match case-insensitively in SET, SET LOCAL, SET SESSION, set_config('name', ...), and ALTER DATABASE or ALTER SYSTEM ... SET statements. set_config must be unqualified or called through pg_catalog, and its first argument must be a static string literal. SET TIME ZONE (including LOCAL or SESSION) matches the parameter timezone. Settings findings use target setting:<name>. Dynamic setting names are not matched. Statement kinds and settings found in recoverable routine bodies or static EXECUTE strings are checked like top-level SQL. Statement bans also check SQL-standard BEGIN ATOMIC routine bodies. Nested statements report on their own lines, including repeated COMMIT or ROLLBACK in a dollar-quoted DO block. If parsing fails, recognized kinds and settings are still checked; unanalyzableSql controls any remaining unanalyzable SQL.

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    include: ['**/*.test.ts', 'test-helpers/**']
    options:
      importSpecifier: '@example/db'
      trustedSqlTags: [{module: '@example/db', name: sql}]
      executorFactoryNames: [beginTransaction]
      executorTypeNames: [TransactionQuery]
      bannedStatements: [ddl]
      bannedSettings: [session_replication_role]
      unanalyzableSql: fail

For example, this test helper takes schema locks that can stall parallel tests:

import { query, sql } from '@example/db';
await query(sql`ALTER TABLE orders ADD CONSTRAINT reject_writes CHECK (false)`);

Inject failures through an executor seam instead:

const failingQuery: TransactionQuery = async statement => {
  if (statement.text.startsWith('UPDATE orders')) throw new Error('injected');
  return query(statement);
};

The same rule options work through the asynchronous Node check() API.

Counterexample: schema DDL in a config-driven file.

CREATE TABLE foo (id uuid PRIMARY KEY);
SET LOCAL session_replication_role = replica;

Fix: keep schema DDL in migrations, and inject failures through an executor seam instead of changing shared schema or database settings.

INSERT INTO foo (id) VALUES ('00000000-0000-0000-0000-000000000001')
  ON CONFLICT (id) DO NOTHING;

Use no-mistakes-disable-next-line postgres-sql-statement-policy or no-mistakes-disable-line for a one-off, or no-mistakes-disable-file when a whole file is an intentional exception.

Clause policy example

A development database may already have an extension version that a fresh server image no longer ships. A cascading drop can also remove dependent objects that the migration never names. Ban both clauses in migrations while allowing the underlying statement kinds.

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    options:
      sqlInclude: ['db/migrations/**/*.sql']
      bannedStatements: []
      bannedClauses: [create-extension-version, drop-cascade]

Both statements below are findings with this configuration.

CREATE EXTENSION IF NOT EXISTS widgets VERSION '1.4';
DROP VIEW widget_summary CASCADE;

The explicit empty bannedStatements list makes this a clause-only policy. Omitting that option also enables the seven default statement-kind bans.

Omit VERSION to use the server's default extension version. Drop dependent objects explicitly in dependency order, then use RESTRICT on the original drop so unexpected dependencies stop the migration.

CREATE EXTENSION IF NOT EXISTS widgets;
DROP VIEW widget_dashboard RESTRICT;
DROP VIEW widget_summary RESTRICT;

For an intentional exception, use a next-line directive above the statement, a line directive on the statement's first line, or a file directive for a dedicated exception file.

-- no-mistakes-disable-next-line postgres-sql-statement-policy
CREATE EXTENSION IF NOT EXISTS widgets VERSION '1.4';
DROP VIEW widget_summary CASCADE; -- no-mistakes-disable-line postgres-sql-statement-policy
-- no-mistakes-disable-file postgres-sql-statement-policy
DROP VIEW widget_summary CASCADE;

Transaction-control policy example

When a migration runner already wraps each migration file in a transaction, adding BEGIN, COMMIT, ROLLBACK, or savepoints inside a migration breaks transactional guarantees or conflicts with the runner. Scope the ban to migration files so standalone scripts outside that glob remain unaffected.

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    options:
      sqlInclude: ['migrations/**/*.sql']
      bannedStatements: [transaction-control]

Counterexample: explicit transaction control in a runner-managed migration.

-- migrations/001_create_widgets.sql
BEGIN;
CREATE TABLE widgets (id uuid PRIMARY KEY);
COMMIT;

Fix: remove explicit transaction-control statements so the migration runner owns the transaction.

-- migrations/001_create_widgets.sql
CREATE TABLE widgets (id uuid PRIMARY KEY);

For an intentional exception (such as a migration configured to run outside a transaction), suppress the statement or file:

-- no-mistakes-disable-next-line postgres-sql-statement-policy
BEGIN;
COMMIT; -- no-mistakes-disable-line postgres-sql-statement-policy
-- no-mistakes-disable-file postgres-sql-statement-policy
BEGIN;
COMMIT;

Single-statement transactions

Use a separate advisory application for standalone scripts so the transaction hint has its own severity.

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    severity: advisory
    options:
      sqlInclude: ['db/jobs/**/*.sql']
      bannedStatements: []
      singleStatementTransactions: true

The option defaults to false. The advisory points to the opening BEGIN or START TRANSACTION when one parsed query, insert, update, or delete is followed by a plain COMMIT or END. It requires default transaction settings and a fully parsed SQL file. Transaction options, savepoints, chained commits, and rollbacks can change semantics.

BEGIN;
UPDATE jobs SET claimed = true WHERE id = 42;
COMMIT;

PostgreSQL already executes an individual statement atomically. Run the update on its own to avoid extra transaction commands when the wrapper has no separate purpose. Use the ordinary rule suppression directive on the opening statement for intentional exceptions.

Why and when

Statement kinds come from SQL statements, not comment banners or identifiers containing words such as table. Findings point to their own statement.

Use this rule on seed, config, or runtime SQL directories where schema DDL must remain in migrations and the file's allowed purpose should be machine-checked.

What it catches/requires

The rule reports each configured banned statement kind, setting, and clause in included SQL and configured executor calls. This includes statically recoverable statements inside supported PL/pgSQL bodies and static EXECUTE strings.

Options and defaults

unanalyzableSql: advise reports residual uncertainty in non-failing advisories. --include-sql-verdicts adds per-subcheck SQL verdicts.

sqlInclude defaults to **/*.sql. bannedStatements defaults to CREATE TABLE, ALTER TABLE, CREATE INDEX, CREATE VIEW, TRUNCATE, DROP INDEX, and DROP VIEW; CREATE UNIQUE INDEX and materialized views map to those categories. ddl expands to all 29 DDL/truncate kinds; transaction-control expands to all 8 transaction-control kinds (BEGIN, START TRANSACTION, COMMIT, END, ROLLBACK, SAVEPOINT, RELEASE SAVEPOINT, and ROLLBACK TO SAVEPOINT). bannedStatements: [] disables statement-kind checks; bannedSettings defaults to [] and matches literal setting names in SET, SET LOCAL, SET SESSION, supported set_config() calls, and database/system SET statements. Kind and group names are case-insensitive and ignore repeated whitespace; unknown kinds and groups are configuration errors.

bannedClauses defaults to [] and applies independently of bannedStatements and bannedSettings. Use these exact names. An unknown name is a configuration error.

Clause name SQL matched
create-extension-version An explicit VERSION option in CREATE EXTENSION.
drop-cascade CASCADE on DROP VIEW, DROP MATERIALIZED VIEW, DROP TABLE, DROP FUNCTION, DROP TYPE, DROP SCHEMA, DROP INDEX, DROP EXTENSION, DROP SEQUENCE, single-name DROP DOMAIN, DROP TRIGGER ... ON ..., ALTER TABLE ... DROP [COLUMN] ..., ALTER TABLE ... DROP CONSTRAINT ..., and TRUNCATE.

Clause coverage excludes ALTER EXTENSION ... UPDATE TO, DROP OWNED ... CASCADE, and multi-name DROP DOMAIN ... CASCADE. CREATE EXTENSION ... CASCADE installs required extensions and falls outside the cascading-drop policy. See PostgreSQL's CREATE EXTENSION documentation.

The rule reports a matched clause once per statement at the statement's start with target clause:<name>. It checks SQL files selected by sqlInclude and each complete SQL alternative at configured executor calls. The clause checks use parsed extension options and cascading operations. Unsupported SQL syntax follows the existing unanalyzableSql policy.

Valid example

-- db/config-driven/seed.sql
INSERT INTO foo (id) VALUES ('00000000-0000-0000-0000-000000000001')
  ON CONFLICT (id) DO NOTHING;

Counterexample

-- db/config-driven/seed.sql
CREATE TABLE foo (id uuid PRIMARY KEY);
SELECT pg_catalog.set_config('session_replication_role', 'replica', true);

Fix

Move schema DDL to a migration directory, or narrow sqlInclude and the banned set to match the file's intentional role.

Analysis

Effort

Runs at max only. Configuring effort: low (rule option, repository effort, or the invocation override) is not an error: the rule has no low implementation, so the check warns requested effort low; effective effort max because this rule has no low implementation and runs at max. At max it evaluates executor calls in TS/JS (helpers, builders, and up to 16 finite SQL alternatives per call) and SQL files selected by sqlInclude.

Unanalyzable inputs

Valid PostgreSQL can still be unsupported by this analyzer. When it cannot recover statements such as ALTER DEFAULT PRIVILEGES, CREATE PUBLICATION, or REFRESH MATERIALIZED VIEW, it diagnoses them under options.unanalyzable. The same diagnostic also catches rejected syntax such as CREATE RECURSIVE VIEW without its required explicit column list; it reports missing analyzer facts, not a PostgreSQL validity verdict.

Following recall over precision (how analysis works), inputs this rule cannot prove are never treated as clean; they follow options.unanalyzable.

  • Inputs this rule cannot prove: executor calls whose SQL has no complete recovered alternative or exceeds the 16-alternative cap (for example query(buildSql(filters)) with an unrecoverable helper), and SQL, embedded or in a sqlInclude file, that fails to parse. They follow options.unanalyzable:

    • report (default): fails as a finding, e.g. executed SQL is not statically recoverable for statement policy.
    • advise: a non-failing advisory {file}:{line}: postgres-sql-statement-policy has unresolved SQL for {checks}: {reasons} (for example opaque-sql-tail or invalid-sql), not a copy of the report sentence. Schema-file diagnostics keep one message at either severity.
    • ignore: omitted.

    Definite violations remain findings under every policy. The legacy unanalyzableSql: fail spelling means report; advise and ignore keep their names.

Raw SQL parse failures are reported on the line of each failing statement's first code token. Separate statements produce separate findings, and a no-mistakes-disable-next-line directive immediately above one statement suppresses that failure independently. Successfully parsed sibling statements remain analyzable. Unsupported syntax, including expressions with COLLATE, still follows options.unanalyzable; this location behavior does not make that syntax parse successfully. A real DISCARD ALL statement does not trigger a recovery diagnostic. Rewrite unsupported syntax into a supported static statement or suppress the specific diagnostic with a reason.

For schema parse failures, the implicit default advises for any statement that cannot be analyzed inside a recognized DO, PL/pgSQL function, or procedure body. This includes malformed body statements: an advisory means analysis is incomplete, not that PostgreSQL accepts the SQL. Successfully parsed body statements still contribute facts and rule findings. At the top level, examples of complete recognized forms that advise include the list below. The list is not exhaustive: CREATE PUBLICATION name without FOR, ALTER PUBLICATION add, drop, rename, owner, and set forms, DROP PUBLICATION, and supported REVOKE also advise. Malformed and unrecognized statements retain findings.

  • Complete CREATE EXTENSION [IF NOT EXISTS] name with optional WITH, SCHEMA, VERSION, and CASCADE options; each option may occur at most once.
  • CREATE USER name [WITH] with boolean login, inheritance, role/database creation, superuser, replication, or row-security bypass flags. Other user options still require separate parser support.
  • REFRESH MATERIALIZED VIEW [CONCURRENTLY] view [WITH [NO] DATA]
  • CREATE PUBLICATION name FOR ALL TABLES
  • CREATE PUBLICATION name FOR TABLE table [, table ...]
  • ALTER DEFAULT PRIVILEGES [FOR {ROLE | USER} role [, role ...]] [IN SCHEMA schema [, schema ...]] GRANT {ALL [PRIVILEGES] | privilege [, privilege ...]} ON {TABLES | SEQUENCES | FUNCTIONS | ROUTINES | TYPES | SCHEMAS} TO grantee [, grantee ...] [WITH GRANT OPTION]

Privileges are SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, USAGE, CREATE, EXECUTE, and MAINTAIN. view and each table may be schema-qualified; name, role, schema, and grantee may not. CONCURRENTLY precedes the view name, and WITH requires DATA. A matching prefix with extra tokens is not recognized. Explicit rule or repository unanalyzable policies override these defaults. See the schema diagnostic migration.

CREATE SCHEMA is recovered inside DO and PL/pgSQL bodies just as at the top level. Integer FOR ranges accept compact .. delimiters and expression bounds, including 1..array_length(parts, 1) - 1. Malformed bounds remain unanalyzable; diagnostic heads retain the original punctuation rather than spelling .. as separate dots. Recognized forms do not exempt actual table, constraint, or statement-policy violations.

Suppression

Use no-mistakes-disable-next-line postgres-sql-statement-policy or no-mistakes-disable-line postgres-sql-statement-policy for an approved statement exception. Use no-mistakes-disable-file postgres-sql-statement-policy for an approved file exception.

SQL recovered from an imported helper is reported in the helper's module at the helper's line. A directive in the helper's file suppresses it, and so does a directive in the calling file (file-level, on the executor call, or on the imported-helper call). See Helper-line attribution and suppression.

Related rules

postgres-no-add-column governs migration column shape; postgres-constraint-validate checks phased constraint rollout.

With unanalyzableSql: advise, opaque or parse-failed SQL produces one residual advisory per executor call and configured application, including all unresolved statement kinds/settings. The advisory uses the executor call line, and its target lists sorted unresolved checks. Proven violations retain their SQL origin lines. The optional SQL verdict ledger still records every obligation.

Invalid UTF-8

Source text this rule reads, including standalone SQL, is decoded lossily, so a stray byte does not drop the file or replace it with an encoding failure. Other read errors contribute no source text. unanalyzableSql still applies to SQL the statement pass cannot parse.

Plan scenario evidence

Use planEvidence to require a checked-in JSON plan for selected query shapes in standalone SQL files. This check is opt-in.

rules:
  - rule: postgres-sql-statement-policy
    scope: repository
    options:
      sqlInclude: ['db/queries/**/*.sql']
      bannedStatements: []
      planEvidence:
        directory: db/plans
        shapes: [materialized, lateral, union, distinct, recursive-cte]

The line directly above each matching statement must contain a -- plan-scenario: <id> comment. The identifier may contain ASCII letters, digits, hyphens, or underscores. The file <id>.json must exist in the configured repository-relative directory and parse as JSON. Use a saved plan for the query and scenario under review. This check validates the reference and artifact syntax.

-- plan-scenario: pending-jobs-by-owner
WITH candidates AS MATERIALIZED (SELECT id FROM jobs WHERE owner_id = $1 LIMIT 50)
SELECT id FROM candidates;

With the configuration above, the example requires db/plans/pending-jobs-by-owner.json. Add the actual scenario plan or simplify the query. For an intentional exception, use file suppression or place the next-line suppression on the statement with the reason on the directive.