Skip to content

SQL

gspot lints SQL files with SQLFluff, and installs SQLFluff itself, so your project needs no Python packages. The postgres configuration adds checks of your migrations and of the tables, policies, and functions that they define:

Check Stage Level What it does
postgres/squawk commit basic Checks every migration for changes that lock or rewrite a table, or break the running application.
postgres/migration-order commit basic Checks that every migration has a version, that no two share one, and that a new migration sorts after the committed ones.
postgres/edited-migrations commit basic 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.
postgres/row-level-security commit basic 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).
postgres/grants commit basic 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.
postgres/definer-search-path commit basic Checks that every SECURITY DEFINER function sets its search_path to a value that the migration states and that names neither public nor "$user".
postgres/foreign-key-indexes commit basic Checks that an index, a primary key, or a unique key starts with all columns of each foreign key.
postgres/function-size commit all Checks each function defined after the frozen migrations against the size limits of limits.sql: code lines, statements, nesting, and parameters.
postgres/trivial-functions commit all 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.
postgres/function-shape commit all 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.
postgres/dynamic-sql commit basic Reports an EXECUTE in a PL/pgSQL function that builds its SQL with ||, or with %s in format().
postgres/function-declarations commit all 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.
postgres/sections commit all Checks that each migration after the frozen ones puts its statements under section banners, in the fixed order of the sections.
postgres/policy-names commit all Checks that each policy that a migration after the frozen ones creates is named for its role, its action, and what it guards.
postgres/statement-layout commit all 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.
postgres/grant-order commit all 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.
postgres/list-layout commit all 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.
postgres/comment-layout commit all 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.
sql/sqlfluff commit basic Lints every SQL file for layout, capitalization, aliasing, and ambiguous references, in the dialect that sql.dialect names.
sql/keywords commit basic Checks, in the Postgres dialects, the keywords that SQLFluff does not read: the keywords and built-in types of PL/pgSQL, ANY, ALL, SOME, EXISTS, NOT, DISTINCT, and ARRAY before a bracket with their space, and the case of NEW, OLD, and the other PL/pgSQL names.

SQLFluff parses the dialect that sql.dialect names, ansi by default, so set it to your database, such as postgres, mysql, or sqlite:

gspot set sql.dialect postgres

The postgres configuration sets it for you. SQLFluff reads each file as plain SQL, and does not expand Jinja or other templates.

SQLFluff reads a function body between $$ quotes as one string. Under the postgres dialect, gspot also gives it the SQL inside each body: every statement and every expression. An expression is the condition of an IF, the value of an assignment, or an argument of a RAISE. It reports their findings at their line and column in the file. In a body, gspot skips the rules about indentation, blank lines, and references, because PL/pgSQL sets the indent and its variables look like unknown columns. The SQLFluff fixer leaves a body unchanged, so fix those findings by hand.

sql/keywords checks what SQLFluff does not read, and gspot check --fix writes each of them:

  • The keywords of PL/pgSQL, such as BEGIN, IF, INTO, PERFORM, and RETURN, and the built-in types of a DECLARE section, stand in upper case.
  • ANY, ALL, SOME, EXISTS, NOT, and DISTINCT before a bracket stand in upper case with one space before the bracket, and ARRAY with none. SQLFluff reads them as function calls there.
  • NEW, OLD, FOUND, SQLERRM, SQLSTATE, and the TG_ names of a trigger function stand in upper case, as the Postgres manual writes them, or in lower case. gspot reports a mix such as New.

gspot drops the SQLFluff findings that misread valid Postgres:

  • ST05 skips a LATERAL subquery that reads a row of its statement, which a common table expression cannot replace.
  • SQLFluff cannot parse ROWS FROM, so gspot drops the findings that it anchors on that clause.
  • A branch after UNION, INTERSECT, or EXCEPT, and the SELECT of an INSERT, take their column names from elsewhere, so they need no column aliases.
  • In a body, a query that fills scalar variables or the function result, such as SELECT ... INTO or RETURN QUERY, needs no column names. A query that fills a RECORD keeps those rules, because the record takes their names.
  • The gap where gspot blanks an INTO target draws no spacing finding.
  • A type behind a schema, such as accounts.cards, is the name of your type and stays lower case.

When one folder holds another dialect, such as SQLite migrations beside a Postgres database, set the dialect in the scope of that folder:

[[scope]]
path = "d1"
sql.dialect = "sqlite"

naming/identifiers reads SQL names with a Postgres parser. Under a dialect other than postgres, which includes the default ansi, it checks the files that this parser can read, and reports no syntax finding for the others.

Keywords, literals, and types are upper case, and identifiers and functions are lower case, so select id from user_accounts; gets a CP01 finding for each lowercase keyword.

SQLFluff takes its line length from format.print_width, and its indent from the format settings of SQL files. When the rest of your repository uses another indent, gspot init writes a [[format.override]] record that indents SQL files by four spaces, and you change the SQL indent in that record.

At level basic, gspot turns off six SQLFluff rules about joins, casts, subqueries, and LIMIT: AM05, AM09, CV11, ST05, ST07, and ST09. Level all runs them.

The postgres configuration reads the functions that your migrations define. At level all:

  • postgres/function-size allows each function 100 code lines, 30 statements, 3 levels of nesting, and 7 parameters. A code line is a line of the body that holds more than a blank, a comment, or a bare DECLARE, BEGIN, or END.
  • postgres/trivial-functions reports a function of 3 code lines or fewer that at most one place names, unless a trigger runs it or a grant exposes it. A call such as .rpc('get_profile') in your app code counts as a place.
  • postgres/function-shape reports PL/pgSQL that hides what it does, such as a variable that only carries a value to RETURN. It also reports a parameter that nothing reads, and a WHEN OTHERS handler that drops the error.
  • postgres/function-shape also reports a body between single quotes, because gspot and SQLFluff read only a body between $$ quotes.
  • postgres/function-declarations reports a function without SET search_path or a volatility. It also reports a search_path that names a schema other than pg_catalog and pg_temp, such as SET search_path = public.

At every level, postgres/definer-search-path reports a SECURITY DEFINER function whose search_path is missing, comes FROM CURRENT, or names public or "$user". postgres/dynamic-sql reports an EXECUTE that builds SQL by joining text, and postgres/grants reports a SECURITY DEFINER function that PUBLIC can run and an EXECUTE grant on a trigger function. At level all, postgres/grants also reports every other function that PUBLIC can run, so each function revokes EXECUTE from PUBLIC.

A procedure takes no volatility. A procedure that commits or rolls back takes no SET clause, because Postgres refuses transaction control beside one. A SQL function that the planner inlines takes no SET clause either, because the clause stops the inlining, so qualify every name in it instead. A function with a SQL-standard body, BEGIN ATOMIC ... END or RETURN, needs no SET search_path, because Postgres resolves its names when it creates the function.

The limits.sql settings change these limits. Raising a size limit, or lowering limits.sql.trivial_function_lines, needs a reason:

gspot set limits.sql.max_function_lines 120 --reason "The billing function keeps its steps in one transaction."

An applied migration never runs again, so the size, trivial, and shape checks read a function only when its last definition sits in a migration after postgres.frozen_through. The other function checks read every migration, because a new migration fixes what they report, with ALTER FUNCTION, REVOKE, or CREATE OR REPLACE FUNCTION.

At level all, six checks hold each migration after postgres.frozen_through to one layout. postgres/sections reads the banners that open its sections:

-- ============================================================================
-- Internal functions: Text
-- ============================================================================

A banner line is --, a space, and 76 =. The title names a section, and : <topic> after it splits a section into topics that sit next to each other. A title in another case, such as tables, draws a finding that names the title to write. The sections keep this order, and a migration leaves out the ones it does not need:

  1. Extensions, Schema, Roles, then Types.
  2. Check functions, then Tables. Check functions holds only the functions that a table of the migration calls in a check, a default, or a generated column.
  3. Internal functions, Trigger functions, then RPC functions.
  4. Views, Indexes, then Triggers.
  5. Row Level Security, Comments, then Grants.
  6. Rows, Buckets, Cron, Realtime, then Data API.

Each statement sits in the section of its kind, and only SET statements come before the first banner. A migration never alters a table that it creates, except to turn on row level security, and Row Level Security turns it on for every table before the first policy.

postgres/grant-order orders the Grants section as schema grants, table grants, function revokes, then function grants. It also checks privileges in the order SELECT, INSERT, UPDATE, DELETE, granted columns in the order of their table, and each run of revokes or grants by length, shortest first. A blank line or a comment ends a run.

postgres/list-layout joins a list of columns, parameters, or argument types onto one line when that line fits format.print_width, and puts each item on its own line otherwise.

postgres/policy-names reads each policy name as <role>_can_<action>_<subject>, such as shopper_can_read_orders. The action is read, insert, update, delete, or manage for FOR ALL, and user may stand for the authenticated role.

postgres/statement-layout lays out the statements that SQLFluff leaves alone:

  • A trigger puts each clause on its own line, flush left, and a policy does too, with FOR and TO on one line.
  • A grant or a revoke names one object. It stands on one line when it fits format.print_width, and otherwise each privilege starts its own line, with ON and the roles on the last line.
  • A CHECK stands on one line when it fits, and otherwise puts each condition on its own line with AND or OR first. The AND of a BETWEEN, and each AND or OR inside a CASE, stay in their condition.
  • The VALUES of an INSERT start their own line, with one row per line, flush left.
  • A trigger, a policy, or a grant that holds a comment keeps its layout, and statement-comment reports the comment, which belongs above the statement.
CREATE TRIGGER trg_items_touch
BEFORE UPDATE ON app.items
FOR EACH ROW
EXECUTE FUNCTION app.touch();
CREATE POLICY reader_can_read_items ON app.items
FOR SELECT TO reader
USING (app.is_visible(owner_id));

postgres/comment-layout refills a comment line past postgres.comment_width, or past format.print_width without that setting. It puts one space after --, and deletes a bare -- line inside a comment block. Outside function bodies, it puts a blank line before a comment that follows a line of code. A comment inside a statement, as between the columns of a table, takes none. A -- line inside a string, such as the text of COMMENT ON or a string of a function body, is no comment and stays as it is:

gspot set postgres.comment_width 120

gspot check --fix sorts the runs of revokes and grants, lays out the lists, statements, and comments, and splits a grant on several objects. It writes a migration only when its statements stay the same, and it keeps the CRLF line ends of a file that has them. The other layout rules only report, because moving a statement to another section can leave behind the comment that explains it.

gspot init deletes .sqlfluff and .sqlfluffignore, because gspot reads only the SQLFluff settings that it writes, and sql.dialect and format are the only settings it has for them. A SQLFluff table in pyproject.toml, setup.cfg, or tox.ini stays, and gspot/conflicting-configs reports it until you delete it.

To turn one rule off, ignore it with a reason, or allow one statement with a comment, such as SELECT * FROM orders -- noqa: AM04 -- reason: the view mirrors every column:

gspot ignore sql/sqlfluff --rule AM04 --reason "The reporting views mirror every column of their table."