Skip to content

postgres

Postgres migrations: the locking and breaking changes that Squawk reports, a fixed order, no edits to frozen migrations, row-level security, explicit grants, an index under every foreign key, the size and shape of functions, and at level all a fixed layout of sections, grants, lists, and policy names. It requires sql. Guide: SQL.

A scope has a file prisma/schema.prisma whose text matches the regular expression (?:^|\n)[\t ]*provider[\t ]*=[\t ]*"postgresql", or a dependency on pg, postgres, psycopg*, asyncpg, or @neondatabase/serverless. Also when supabase requires it.

Checks every migration for changes that lock or rewrite a table, or break the running application.

Runs at the commit stage.

A migration that takes an exclusive lock on a large table stops the application for as long as it runs.

Follow the advice squawk prints for the rule.

A migration that adds a constraint with a full table scan reports a finding. Create the constraint first, and validate it in a separate migration.

gspot ignore postgres/squawk --paths "<path>" --reason "<why>"
gspot ignore postgres/squawk --rule <rule> --reason "<why>"

Checks that every migration has a version, that no two share one, and that a new migration sorts after the committed ones.

Runs at the commit stage, once per scope.

A migration that sorts before an applied one never runs on databases already past it.

Rename the new migration with a version later than the newest committed one.

A new migration numbered below the latest committed one reports a finding. Give it a later version, and leave applied migrations unchanged.

Rule What it checks What to do
order A new migration sorts after every committed migration. Rename the new migration with a version after the newest committed one.
version Each migration file name starts with a version number. Rename the file with a version prefix, such as a timestamp.
duplicate-version Each migration has its own version. Give one of the files a new version.
syntax A file that the check reads parses without errors. Fix the syntax at the reported line.
gspot ignore postgres/migration-order --paths "<path>" --reason "<why>"
gspot ignore postgres/migration-order --rule order --reason "<why>"

Checks that no migration of the base revision differs from its committed text, and that migrations after postgres.frozen_through use IF NOT EXISTS only on CREATE INDEX CONCURRENTLY.

Runs at the commit stage, once per scope.

An applied migration never runs again, so an edit reaches only new databases, and environments drift apart. IF NOT EXISTS hides that drift.

Restore the file with git checkout, and write the change as a new migration. Keep IF NOT EXISTS only on CREATE INDEX CONCURRENTLY.

An edit to a committed migration reports a finding. Restore the original file, and write the change as a new migration.

Rule What it checks What to do
frozen A committed migration keeps its committed text. Undo the edit, and put the change in a new migration.
drift-guard No migration after postgres.frozen_through uses IF NOT EXISTS, except CREATE INDEX CONCURRENTLY. Remove IF NOT EXISTS, so that the migration fails when the object already exists.
gspot ignore postgres/edited-migrations --paths "<path>" --reason "<why>"
gspot ignore postgres/edited-migrations --rule frozen --reason "<why>"

Checks that client tables turn on row-level security, client views keep it, and policies after the frozen migrations name their roles and explain USING (true).

Runs at the commit stage, once per scope. It skips until you set postgres.client_schemas.

A client that reaches the schema reads and writes every row of a table without row security.

Enable row-level security on the table, name the roles of each policy, wrap identity calls in (select ...), say why a policy is USING (true), and set security_invoker = true on client views.

A new table without row-level security reports a finding. Add ALTER TABLE ... ENABLE ROW LEVEL SECURITY for it.

Rule What it checks What to do
row-security Each table in a schema of postgres.client_schemas turns on row level security. Run ALTER TABLE <table> ENABLE ROW LEVEL SECURITY; in a migration, and add policies.
view-without-security-invoker Each view in a client schema sets security_invoker = true. Create the view WITH (security_invoker = true).
policy-without-roles After the frozen migrations, each policy names its roles with TO. Name the roles after TO, such as TO authenticated.
per-row-identity-call After the frozen migrations, a policy wraps auth.uid() and current_setting() in (select ...). Write (select auth.uid()) instead of auth.uid().
open-policy After the frozen migrations, a USING (true) policy has a comment that gives the reason. Write a -- comment next to the policy with the reason.
gspot ignore postgres/row-level-security --paths "<path>" --reason "<why>"
gspot ignore postgres/row-level-security --rule row-security --reason "<why>"

Reports a migration that grants all privileges, a SECURITY DEFINER function that PUBLIC can run (at level all, any function), and an EXECUTE grant on a trigger function.

Runs at the commit stage, once per scope.

A full grant includes privileges that nobody meant to give, a definer function that PUBLIC can run lets every role act with its owner’s rights, and a grant on a trigger function lets clients call it directly.

Name the privileges the role needs, such as SELECT alone. Revoke EXECUTE from PUBLIC on a SECURITY DEFINER function, and revoke each grant on a trigger function.

The statement GRANT ALL ON TABLE public.items TO app_reader; reports a broad grant. If the role only reads rows, use GRANT SELECT ON TABLE public.items TO app_reader;.

Rule What it checks What to do
grant-all A migration names the privileges it grants instead of ALL. Name the privileges that the role needs, such as SELECT alone.
public-execute PUBLIC cannot run a SECURITY DEFINER function, and at level all, no function. Revoke EXECUTE from PUBLIC on the function, then grant it to the roles that call it.
trigger-execute-grant No role holds an EXECUTE grant on a trigger function. Revoke the grant in a new migration.
gspot ignore postgres/grants --paths "<path>" --reason "<why>"
gspot ignore postgres/grants --rule grant-all --reason "<why>"

Checks that every SECURITY DEFINER function sets its search_path to a value that the migration states and that names neither public nor "$user".

Runs at the commit stage, once per scope.

A definer function runs with its owner’s rights, and a caller who controls the search path chooses the objects it touches.

Set search_path = '' in the definition, and qualify every name inside it. A search_path that names public or "$user", or that FROM CURRENT copies, still reports.

A SECURITY DEFINER function without SET search_path, or with SET search_path = public, reports a finding. Add SET search_path = '' to the definition, and schema-qualify the objects in its body.

gspot ignore postgres/definer-search-path --paths "<path>" --reason "<why>"

Checks that an index, a primary key, or a unique key starts with all columns of each foreign key.

Runs at the commit stage, once per scope.

Deleting a parent row scans the whole child table when the foreign key has no index.

Create an index that starts with all columns of the foreign key.

A foreign key on orders.customer_id without an index starting with that column reports a missing index. Add SET lock_timeout = '5s'; SET statement_timeout = '60s'; CREATE INDEX orders_customer_id_idx ON orders (customer_id); in the migration set.

gspot ignore postgres/foreign-key-indexes --paths "<path>" --reason "<why>"

Checks each function defined after the frozen migrations against the size limits of limits.sql: code lines, statements, nesting, and parameters.

Runs at the commit stage, only at the all level, once per scope.

A long database function does several jobs, and none of them can be read, tested, or reviewed alone.

Split the function into helper functions or a view, or raise the named limits.sql setting with a reason.

A PL/pgSQL function of 140 code lines reports function-lines. Move each job into a helper function, or the query that builds the result into a view.

Rule What it checks What to do
function-lines A function has at most limits.sql.max_function_lines code lines. Move each job into a helper function, or the query that builds the result into a view.
function-statements A function has at most limits.sql.max_function_statements statements. Group the steps that belong together into a helper function.
block-nesting Blocks nest at most limits.sql.max_block_nesting levels deep in a function. Return early, or move the inner block into a helper function.
function-parameters A function takes at most limits.sql.max_function_parameters parameters. Pass a composite type or a jsonb document, or split the function.
gspot ignore postgres/function-size --paths "<path>" --reason "<why>"
gspot ignore postgres/function-size --rule function-lines --reason "<why>"

Finds functions defined after the frozen migrations with limits.sql.trivial_function_lines code lines or fewer that no trigger runs, no grant exposes, and at most one place in the repository names.

Runs at the commit stage, only at the all level, once per scope.

A tiny function with one caller adds a name and a jump to read, and hides what the caller does.

Move the code into its one caller and drop the function, or lower limits.sql.trivial_function_lines with a reason.

A one-line app.double(p int) that only app.total() calls reports trivial-function. Write p * 2 in app.total(), and drop app.double in a new migration.

Rule What it checks What to do
trivial-function A function of limits.sql.trivial_function_lines code lines or fewer has more than one caller, a trigger, or a grant. Move its code into the one place that calls it, and drop the function in a new migration.
gspot ignore postgres/trivial-functions --paths "<path>" --reason "<why>"
gspot ignore postgres/trivial-functions --rule trivial-function --reason "<why>"

Checks the functions defined after the frozen migrations for a body between single quotes, and the PL/pgSQL ones for a value assigned only to be returned, a copied parameter, a variable that holds one literal, an unread variable or parameter, and a WHEN OTHERS handler that drops the error.

Runs at the commit stage, only at the all level, once per scope.

Each of these adds names and steps that a reader has to follow, a dropped error hides why the work failed, and gspot and SQLFluff skip a body between single quotes.

Apply the fix that the rule names, such as returning the expression directly, deleting the unread variable, or writing the body between $$ quotes.

v_valid := p_text ~* pattern; RETURN v_valid; reports immediate-return. Write RETURN p_text ~* pattern;. AS 'SELECT 1' reports quoted-body. Write AS $$ SELECT 1 $$.

Rule What it checks What to do
immediate-return A PL/pgSQL function returns an expression instead of assigning it to a variable first. Write RETURN <expression>; and delete the variable.
copied-parameter No variable copies a parameter that it never changes. Use the parameter, and delete the variable.
literal-variable A variable that holds one literal for one reader is a CONSTANT or the literal itself. Write the literal where the variable is read, or declare the variable CONSTANT.
unused-variable A PL/pgSQL function reads each variable that it declares. Use the variable where the function needs it, or delete it.
unused-parameter A PL/pgSQL function reads each parameter, unless its name starts with _ because callers must still pass it. Use the parameter, delete it in a new migration, or rename it with a leading _.
lost-error A WHEN OTHERS handler re-raises the error, or reads SQLERRM or SQLSTATE. Re-raise with RAISE;, or put SQLERRM and SQLSTATE in the warning or the result.
quoted-body A function after the frozen migrations writes its body between dollar quotes, such as $$. A function in LANGUAGE c or LANGUAGE internal names compiled code instead, and is exempt. Write the body between $$ quotes, and turn each doubled quote '' inside it back into one quote.
gspot ignore postgres/function-shape --paths "<path>" --reason "<why>"
gspot ignore postgres/function-shape --rule immediate-return --reason "<why>"

Reports an EXECUTE in a PL/pgSQL function that builds its SQL with ||, or with %s in format().

Runs at the commit stage, once per scope.

Text joined into SQL lets a value that holds a quote change the statement, which is SQL injection.

Build the statement with format() and %I for names and %L for values, or pass values with EXECUTE ... USING.

EXECUTE 'SELECT * FROM ' || p_table; reports dynamic-sql. Write EXECUTE format('SELECT * FROM %I', p_table);.

Rule What it checks What to do
dynamic-sql An EXECUTE in a function builds its SQL with format() and %I or %L, or passes values with USING. Write format() with %I for names and %L for values, or pass the values with EXECUTE ... USING.
gspot ignore postgres/dynamic-sql --paths "<path>" --reason "<why>"
gspot ignore postgres/dynamic-sql --rule dynamic-sql --reason "<why>"

Checks that every function sets a search_path that names no schema but pg_catalog and pg_temp, and that every function other than a trigger function or a procedure declares its volatility. A procedure that commits or rolls back, a SQL function that the planner inlines, and a function with a SQL-standard body need no search_path.

Runs at the commit stage, only at the all level, once per scope.

A function that resolves names through the caller’s search path runs the objects that the caller puts first, and Postgres calls an undeclared function again for every row.

Add SET search_path = '' and IMMUTABLE, STABLE, or VOLATILE to the definition, and qualify every name in the body, or run ALTER FUNCTION in a new migration for a function that a migration already created.

CREATE FUNCTION app.count_items() RETURNS bigint LANGUAGE sql AS $$ SELECT count(*) FROM app.items $$; reports search-path and volatility. Add STABLE SET search_path = '' to the definition.

Rule What it checks What to do
search-path Each function sets a search_path that names no schema but pg_catalog and pg_temp, such as SET search_path = ''. A procedure that commits or rolls back needs none, because Postgres refuses transaction control in a procedure with a SET clause. A SQL function that the planner inlines needs none, because a SET clause of any setting stops the inlining. A function with a SQL-standard body, BEGIN ATOMIC ... END or RETURN, needs none, because Postgres resolves its names when it creates the function. Add SET search_path = '' to the definition and qualify every name in the body, or run ALTER FUNCTION ... SET search_path = '' in a new migration. In a SQL function that the planner inlines, qualify every name instead.
volatility Each function that is not a trigger function or a procedure declares IMMUTABLE, STABLE, or VOLATILE. Mark the function IMMUTABLE or STABLE when it only reads, and VOLATILE when it writes, or run ALTER FUNCTION ... STABLE in a new migration.
gspot ignore postgres/function-declarations --paths "<path>" --reason "<why>"
gspot ignore postgres/function-declarations --rule search-path --reason "<why>"

Checks that each migration after the frozen ones puts its statements under section banners, in the fixed order of the sections.

Runs at the commit stage, only at the all level, once per scope.

Migrations that keep one layout let a reader find the tables, functions, and grants of any file at once, and the order lets each section read only what the sections above it create.

Put each statement under the banner of its section, and keep the sections in the order that gspot explain postgres/sections section-order lists.

A migration that puts its Indexes section above its Internal functions reports section-order. Move the Indexes section, with its banner, below the Trigger functions and RPC functions sections.

Rule What it checks What to do
section-banner Each section of a migration opens with a banner: a line of -- and 76 =, one title line, and the same line again. The title names a section in the case of the list below, with : <topic> after it for a topic. The titles of the file header, Migration: and Purpose:, may take any case. Write the banner lines as --, a space, and 76 =, and title the banner with one of: Extensions, Schema, Roles, Types, Check functions, Tables, Internal functions, Trigger functions, RPC functions, Views, Indexes, Triggers, Row Level Security, Comments, Grants, Rows, Buckets, Cron, Realtime, Data API.
section-order The sections of a migration keep the order Extensions, Schema, Roles, Types, Check functions, Tables, Internal functions, Trigger functions, RPC functions, Views, Indexes, Triggers, Row Level Security, Comments, Grants, Rows, Buckets, Cron, Realtime, Data API, and the topics of a section sit next to each other. Move the section, with its banner and statements, to its place in the order.
empty-section Each section banner has at least one statement under it. Delete the banner, or move the statements of that section under it.
misplaced-statement Each statement sits in the section of its kind, and only SET statements come before the first banner. Move the statement under the banner of the section that the finding names.
check-function A function sits above Tables, under Check functions, only when a table of the migration calls it in a check, a default, or a generated column, or when such a check function calls it. Move the function to Internal functions, or call it from the table that needs it.
table-alteration A migration never alters a table that it creates, except to turn on row level security. Move the column, constraint, or default into the CREATE TABLE statement.
row-security-order Row Level Security turns on row level security for every table first, then holds the policies. The lines that turn it on, and the policies of each role, keep the order in which the migration creates the tables. Move the ENABLE ROW LEVEL SECURITY lines above the first policy, and order both by table.
gspot ignore postgres/sections --paths "<path>" --reason "<why>"
gspot ignore postgres/sections --rule section-banner --reason "<why>"

Checks that each policy that a migration after the frozen ones creates is named for its role, its action, and what it guards.

Runs at the commit stage, only at the all level, once per scope.

A name that says who may do what lets a reader find the policy of a role and an action without reading its expressions.

Name each policy <role>_can_<action>_<subject>, with read, insert, update, delete, or manage for FOR ALL. user may stand for authenticated.

CREATE POLICY reads_orders ON app.orders FOR SELECT TO shopper USING (true); reports a name that leaves the template. Name it shopper_can_read_orders.

Rule What it checks What to do
policy-name A policy is named <role>_can_<action>_<subject>: its role, read, insert, update, delete, or manage for FOR ALL, and what it guards. user may stand for the authenticated role. Rename the policy in the migration that creates it, or with ALTER POLICY ... RENAME TO in a new migration.
gspot ignore postgres/policy-names --paths "<path>" --reason "<why>"
gspot ignore postgres/policy-names --rule policy-name --reason "<why>"

Checks the layout of the triggers, policies, grants, CHECK constraints, and VALUES in the migrations after the frozen ones: each clause of a trigger or a policy on its own line, flush left, one object per grant, a grant or a CHECK on one line when it fits the print width, one row of VALUES per line, and no comment inside a trigger, a policy, or a grant.

Runs at the commit stage, only at the all level, once per scope.

One clause per line shows when a trigger fires and whom a policy serves at a glance, and SQLFluff refuses the clause lines indented.

Run gspot check --fix --only postgres/statement-layout, or put each clause of the statement on its own line, flush left at the indent of the statement, and write one grant for each object. Move a comment inside a trigger, a policy, or a grant above the statement.

CREATE TRIGGER trg_items_touch BEFORE UPDATE ON app.items FOR EACH ROW EXECUTE FUNCTION app.touch(); reports trigger-layout. Run gspot check --fix to put each clause on its own line.

Rule What it checks What to do
trigger-layout A trigger puts each clause on its own line, flush left: the name, the timing and events with ON and the table, then FROM, the deferral, REFERENCING, FOR EACH ROW, WHEN, and EXECUTE FUNCTION. Run gspot check --fix, which puts each clause on its own line at the indent of the statement. A trigger that holds a comment keeps its layout, and statement-comment reports the comment.
policy-layout A policy puts each clause on its own line, flush left: CREATE POLICY with ON and the table, then AS, FOR and TO on one line, USING, and WITH CHECK. Run gspot check --fix, which puts each clause on its own line at the indent of the statement, and keeps the lines inside its brackets. A policy that holds a comment keeps its layout, and statement-comment reports the comment.
statement-comment A trigger, a policy, or a grant holds no comment between its first and its last word. A statement with a string that spans lines keeps its layout and draws no finding. Move the comment above the statement, then run gspot check --fix to lay the statement out.
grant-object A grant or a revoke names one object, so a grant on two tables becomes two grants. Run gspot check --fix, which writes one statement for each object, with the same privileges and roles.
grant-layout A grant stands on one line when it fits the print width. Otherwise each privilege starts its own line, flush left, and ON with the roles starts the last line. Run gspot check --fix, which joins a grant that fits and breaks one that does not. postgres/list-layout lays out the column lists inside.
check-layout A CHECK stands on one line when that line fits the print width. Otherwise CHECK ( ends its line, each condition takes a line one step deeper with AND or OR first, and ) returns to the indent of the opening line. Run gspot check --fix. The AND of a BETWEEN, and each AND or OR inside a CASE, stay in their condition, and a CHECK that holds a comment keeps its layout.
values-layout The VALUES of an INSERT start their own line. One row stays beside VALUES; several rows take a line each, flush left. A row past the print width puts each value on its own line, one step deeper. Run gspot check --fix. An INSERT whose values hold a comment, or a value that spans lines, keeps its layout.
gspot ignore postgres/statement-layout --paths "<path>" --reason "<why>"
gspot ignore postgres/statement-layout --rule trigger-layout --reason "<why>"

Checks that the Grants section of each migration after the frozen ones keeps its groups, its privileges, and its columns in order, and sorts its runs of function revokes and grants by length.

Runs at the commit stage, only at the all level, once per scope.

Grants in one order let a reader see at once what each role may do, and a missing or repeated function stands out.

Order the Grants section as schema grants, table grants, function revokes, then function grants; list privileges and columns in their order; and sort each run of revokes or grants by length, shortest first.

GRANT EXECUTE ON FUNCTION app.read_items() TO reader; above REVOKE ALL ON FUNCTION app.count_items() FROM public; reports the revoke. Move the revoke up to the other function revokes.

Rule What it checks What to do
grant-order The Grants section holds schema grants and default privileges first, then table grants, then function revokes, then function grants. Move the statement up to the other statements of its group.
privilege-order A table grant lists its privileges in the order SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, and the grants on one table follow that order too. Reorder the privileges of the statement, or move the statement above the grant whose first privilege comes later.
column-order A granted column list keeps the order in which its table defines the columns. Reorder the columns of the list to match the table.
length-order Each run of function revokes or function grants, the lines that no blank line or comment splits, is sorted by length, shortest first. Sort the run by length, shortest first.
gspot ignore postgres/grant-order --paths "<path>" --reason "<why>"
gspot ignore postgres/grant-order --rule grant-order --reason "<why>"

Checks that each list of columns, parameters, or argument types in the migrations after the frozen ones stands on one line when it fits the print width, and holds one item per line otherwise.

Runs at the commit stage, only at the all level, once per scope.

One form for each length keeps the migrations alike: a short list reads at a glance, and a long one shows each item on its own line, where a change touches one line.

Run gspot check --fix --only postgres/list-layout. A list that fits the print width stands on one line; otherwise put each item on its own line, one indent deeper than the line that opens it.

GRANT INSERT ( id, name ) ON TABLE app.items TO editor; reports a list that fits on one line. Run gspot check --fix to join it.

Rule What it checks What to do
list-layout A list of granted or inserted columns, of function parameters, or of argument types stands on one line when that line fits the print width, and holds one item per line otherwise. Run gspot check --fix, which joins a list that fits, and otherwise puts the ( at the end of its line, each item on its own line one indent deeper, and the ) on its own line.
gspot ignore postgres/list-layout --paths "<path>" --reason "<why>"
gspot ignore postgres/list-layout --rule list-layout --reason "<why>"

Checks that the comments of the migrations after the frozen ones fit within postgres.comment_width, put one space after --, hold no bare -- line, and, outside function bodies, follow a blank line when they follow code.

Runs at the commit stage, only at the all level, once per scope.

Comments at one width with one kind of break read as prose, and a blank line shows which statements a comment opens.

Run gspot check --fix --only postgres/comment-layout, or refill the long comment, put one space after --, delete the bare -- line, or put a blank line before the comment.

A -- line of 130 characters at a comment width of 120 reports comment-width. Run gspot check --fix to refill its paragraph.

Rule What it checks What to do
comment-width A comment line of a migration fits within postgres.comment_width, or the print width of SQL files without it. A -- line inside a string, such as the text of COMMENT ON, a cron command, or a string of a function body, is no comment, and the rules of this check leave it as it is. Run gspot check --fix, which refills the paragraph of the long line. A label line such as -- Purpose: or -- note:, a list item, an empty comment line, and a banner each end a paragraph, and the lines of a list item hang under its text.
empty-comment-line A comment block holds no bare -- line between two comment lines. Run gspot check --fix, which deletes the line.
comment-spacing A blank line stands before a comment block that follows a line of code, between two statements. A comment inside a statement, as between the columns of a table or the rows of VALUES, explains its next part and takes none, and so does a comment in a function body. A line of a block comment counts as a comment, not as code. Run gspot check --fix, which inserts the blank line.
comment-space One space stands between -- and the text of a comment. More spaces may indent the text, and a bare -- and a banner line need none. Run gspot check --fix, which writes one space in place of no space, or of a tab and the white space after it.
gspot ignore postgres/comment-layout --paths "<path>" --reason "<why>"
gspot ignore postgres/comment-layout --rule comment-width --reason "<why>"
Setting What it sets
limits.trivial_function_lines A SQL function with this many code lines or fewer, not counting DECLARE, BEGIN, and END, is reported when at most one place names it.
postgres.client_schemas The schemas clients reach, where every table needs row level security. Empty turns the check off.
postgres.frozen_through The last migration version that has run everywhere (none, all, or a version); Squawk and the checks that ask for an edit to a migration skip those migrations.
postgres.assume_in_transaction Whether the migration runner wraps every migration in a transaction.
postgres.migrations_folder The migrations folder; without it, the checks use the migration files of this configuration.
postgres.comment_width The width that postgres/comment-layout refills migration comments to; without it, the print width of SQL files.
Setting Value
sql.dialect "postgres"
Rule file Installed when
.gspot/rules/POSTGRES.md Always
Tool Version
squawk 2.70.0

.gspot/configurations/postgres/squawk.toml