Skip to main content

Check PostgreSQL scripts

Scan a SQL directory​

Install the PostgreSQL parser in the same environment as the Skylos CLI.

pip install "skylos[postgres]"

For a project with PostgreSQL scripts in db/postgres/, put this in db/postgres/skylos.toml.

[sql]
dialect = "postgresql"

You can also set dialect in [tool.skylos.sql] in pyproject.toml. A Prisma migrations/migration_lock.toml with provider = "postgresql" supplies the dialect for that migration tree. In a mixed repository, give each database directory its own setting.

Scan from the repository root and inspect the SQL coverage and findings.

skylos . --quality --danger --format json --output report.json
jq '.analysis_summary.sql_analysis' report.json
jq '[.quality[]?, .danger[]?] | map(select(.file | ascii_downcase | endswith(".sql")))' report.json

Review a filter​

Suppose this query should find orders that are still open.

SELECT id FROM orders
WHERE status NOT IN ('closed', NULL);

Skylos reports SKY-Q505 on line 2. Under ordinary PostgreSQL equality, 'closed' fails because it matches the list. A different status gives an unknown result because the list contains NULL. A WHERE clause keeps only true results, so the query returns no orders. Choose the form that matches how the application treats an order with a missing status.

Intended rowsFilter
Known statuses other than closedWHERE status <> 'closed'
Every order except those known to be closedWHERE status IS DISTINCT FROM 'closed'

Skylos also follows unused CTE chains (SKY-Q503), checks comparisons such as WHERE deleted_at = NULL (SKY-Q504), and reports shadowed CASE arms (SKY-Q509). For a conditional count, COUNT(CASE WHEN paid THEN 1 ELSE 0 END) counts every row because both 1 and 0 are present values (SKY-Q510). Use COUNT(*) FILTER (WHERE paid) to count only paid orders.

Review a migration​

BEGIN;
CREATE INDEX CONCURRENTLY orders_status ON orders(status);
COMMIT;

SKY-Q506 points to the index command. PostgreSQL requires a concurrent index build or drop to run outside an explicit transaction. Run the concurrent step separately and check whether the migration runner itself opens a transaction. SKY-Q507 covers concurrent drops that name several indexes or use CASCADE. SKY-Q508 checks the number of columns in an explicit foreign key, such as FOREIGN KEY (tenant_id, owner_id) REFERENCES owners(id). It cannot infer the columns of an omitted primary key from a live database.

Review a privileged routine​

SKY-D417 means the SQL creates a SECURITY DEFINER function or procedure without a fixed local search path, or explicitly removes that path while selecting SECURITY DEFINER in one ALTER statement. Check the names the routine resolves and who can create objects in those schemas. If the routine uses fully qualified application objects and only needs built-ins, an example of a fixed path is SET search_path TO pg_catalog, pg_temp. A captured SET search_path FROM CURRENT fixes the value too. Review the actual schemas in that value.

Review role and schema grants​

RuleWhat to look for
SKY-D418Does every role need to create objects in this schema?
SKY-D419Should this login role bypass row-level security when it accesses a table?
SKY-D420Does every role need the specified table or column write permissions?

For example, ALTER DEFAULT PRIVILEGES IN SCHEMA app GRANT UPDATE ON TABLES TO PUBLIC applies to future tables covered by the grant. Check which role will create those tables and whether a named writer role would be sufficient. Effective access to existing tables depends on their grants, schema access and row-level policies.

Scan a plain-text dump​

\restrict DumpKey42
COPY statuses (label) FROM stdin;
open
closed
\.
\unrestrict DumpKey42

Skylos reads the SQL header and resumes checking statements after the end marker. Each row between the header and \. is data. The dump guard keys must match. CSV or binary COPY input, missing terminators and unmatched guards mark the whole file unchecked. Ordinary SQL has a 4,000,000-byte parser limit. A text dump can be up to 16,000,000 bytes when its SQL fits that limit after Skylos removes COPY data and keeps line placeholders. In these larger dumps each COPY header must also fit within 65,536 bytes.

Read a clean result​

Check checked_files, unchecked_files and each entry in files under analysis_summary.sql_analysis. A file marked checked was parsed. A missing parser, invalid SQL or an unsupported client command gives unparsed with a reason. Unknown, conflicting and unsupported dialects have separate statuses. MySQL and SQL Server files are outside current standalone SQL coverage.

Skylos reads literal psql database switches such as \c billing and \connect reporting on their own lines between complete statements. It then scans the SQL in each session and reports original line numbers. Standalone \d, \d+, \dt and \dt+ with a simple literal name are accepted as metadata. Includes, conditionals and psql variables such as :database leave the file unchecked. A backslash before a quote in an ordinary string can change its boundary with the server's string settings. Use explicit escape strings or dollar quoting for such values in psql scripts. In a reconnect script, compact syntax such as items[1:2] can refer to a psql variable. A space after the colon, as in items[1: 2], makes this slice unambiguous. Skylos reads files locally without opening a database connection.

The full report lists all twelve checks. GitHub keeps the eight query and migration quality advisories out of PR feedback. It groups the four security checks by rule, with each location available in the full report. The default and strict findings gates treat all twelve as advisory. A strict coverage gate can still fail on an unchecked file.

Protect a production migration directory​

Put the policy in the root pyproject.toml on your target branch. Use the directories your deployment actually reads.

[tool.skylos.sql.production]
directories = ["db/production"]
forbid_public_writes = true

Run the command from the repository root with full Git commit IDs.

skylos cicd postgres-check --base "$BASE_SHA" --head "$HEAD_SHA" --format json
ChangeResult
Skylos cannot read or parse a changed production SQL fileFail, with the path and reason
A production migration adds a PUBLIC table write or widens an existing grantFail when forbid_public_writes is enabled
A production migration grants PUBLIC read access onlyPass
An existing table grant moves down a few lines in the same migrationPass
An ordinary grant is split into separate statements for the same tables, columns and rightsPass
A change replaces ROLLBACK with COMMIT and makes a PUBLIC write effectiveFail when the write prohibition is enabled
A query has a quality finding, or an explicit backup login has BYPASSRLSPass this policy check. The backup role still appears in security review
A change only touches SQL outside the specified directoriesPass this policy check

Omit forbid_public_writes to require parsing alone. For an intentional exception, use the file path and SHA-256 fingerprint printed for the grant. Add an allow_public_writes entry with those two fields on the trusted target branch before merging the migration. Changes to the policy in the migration PR take effect after it lands.

The write check covers explicit INSERT, UPDATE, DELETE, TRUNCATE and ALL table grants. SQL constructed at runtime, role membership, and permissions from other migrations or server configuration can also change who has access. Skylos follows explicit transactions and savepoints in the file. It assumes that statements outside those transactions commit individually. Use your own migration runner for access tests if it wraps or batches statements. A public write at a commit can fail the check even when a later transaction revokes it. An unresolved or two-phase transaction involving these writes also fails because Skylos cannot establish its outcome. Very large permission rewrites can need manual review when they exceed the limit for comparing individual rights.

With the reusable GitHub Action, check out with fetch-depth: 0, pin the action to a trusted commit, and set postgres-policy: 'true' in gate or review mode. Run the workflow on pull_request. If you use a merge queue, also enable merge_group. A push-only workflow skips the migration check. Require the job through branch protection and require owner review for edits to the workflow and policy.

For tenant isolation, apply your migrations to a disposable database and exercise your actual application roles. For example, check that each tenant sees only its own rows, that a writer can insert a row for its tenant, and that the same writer is denied a row for another tenant. An owner or backup role can see a different result. PostgreSQL row security policies