CLI¶
Every Finding has a code; Diagnostic codes lists them.
sqlassert check¶
check analyzes each SQL file as one SQL Program, from its SQL alone, and fails when any assertion is UNKNOWN or a Diagnostic is reported. Connection Warnings (a table with no CREATE, say) are printed but never fail it.
$ sqlassert check models/ 'queries/**/*.sql'
queries/sessions.sql:4:3: error unproved-many-to-one-join: /**ASSERT MANY TO ONE**/ is not proved (UNKNOWN)
models/events.sql: warning undeclared-table: table events has no CREATE TABLE in the program, ...
5 files checked: 9 assertions (8 PROVED, 1 UNKNOWN), 1 error, 1 warning
A path is a file, a directory (every *.sql under it), or a glob (** crosses directories); - reads stdin. A path that matches nothing is a usage error rather than an empty pass. Each Finding is placed at the marker itself, line and column.
| Exit status | Meaning |
|---|---|
0 |
Every assertion PROVED and no Diagnostic (warnings allowed). |
1 |
An assertion is UNKNOWN, or a Diagnostic was reported. |
2 |
Bad arguments or configuration, or a file that could not be read. Nothing was checked. |
Options:
--format text|json|sarif|github:text(default) ispath:line:column: severity code: messageplus a summary;jsonlists every assertion's outcome and every Finding with its span;sarifis a SARIF 2.1.0 log for GitHub code scanning;githubprints::error/::warningworkflow commands, which GitHub Actions shows as annotations on the marker.--explain: print eachUNKNOWNassertion's explanation (injsonandsariftoo): the relations its columns pass through, one line each, down to the Causes.
Every UNKNOWN assertion lists its Causes under the finding, with or without --explain: where the Property is lost, at path:line:column, tagged with who can act ([sql]: the query as written loses it; [declare]: a key, NOT NULL, Foreign Key or domain the tables do not declare; [sqlassert]: something sqlassert does not see through). By marker:
UNIQUE,PRIMARY KEY,DETERMINES, and the join markers: a join that repeats rows (with why it is not many-to-one in that direction, or where its key's type is lost and why: a call sqlassert knows no result type for also warnsunknown-functionwhere it is written, and aCASTto the type it returns fixes it), a UNION no asserted column separates, a computed column, or a table,GROUP BYorDISTINCTwhose keys the columns miss, with the closest minimal keys and what each lacks.NOT NULL(and theNULLhalf ofPRIMARY KEYandEXACTLY ONE): the join that pads the column, the nullable table column where it is read, aCASEwith noELSE, aNULLliteral.FOREIGN KEY(andEXACTLY ONE's match): the table with no Foreign Key, where it is read; a relation that drops referenced rows; a computed referencing column.ENUM,EXHAUSTIVE: the column with no domain, where it is read; or the values not listed, each with the literal,CHECKorDECLARE ENUMit comes from.
A UNIQUE that a join and an undeclared key lose:
q.sql:61:1: error unproved-unique: /**ASSERT UNIQUE(transaction_id, account_id, is_card, user_id)**/ is not proved (UNKNOWN)
q.sql:32:10: account_transactions AS t: (transaction_id, account_id) is not a key [sql] missing-key-columns
closest minimal key (transaction_id, account_id, user_id), missing user_id
q.sql:33:5: LEFT JOIN accounts AS a USING (account_id) is not many-to-one [sql] no-unique-set (partial-key)
accounts AS a: (account_id, user_id) is not a key
closest minimal key (account_id, organisation_id, user_id), missing organisation_id
json gives them as causes, sarif as relatedLocations, and github as a ::notice where each is written.
- --ignore CODE: also drop Findings with this code, on top of the configured ignore (repeatable, or comma-separated). The codes are the Diagnostic codes plus one per marker for an assertion that is not proved: unproved-unique, unproved-not-null-unique (also PRIMARY KEY), unproved-not-null, unproved-not-null-elements, unproved-foreign-key, unproved-determines, unproved-enum, unproved-exhaustive, unproved-unique-join, unproved-many-to-one-join, unproved-one-to-many-join, unproved-one-to-one-join, unproved-exactly-one-join.
- --only-ignore CODE: drop Findings with these codes instead of the configured ignore; --only-ignore '' ignores nothing.
- --dialect NAME: the SQLGlot dialect (default duckdb).
Defaults live in pyproject.toml; check reads the nearest one with a [tool.sqlassert] table, searching up from the working directory. Each flag, when given, replaces its setting (--ignore adds to ignore; --only-ignore replaces it), and paths given on the command line replace paths:
[tool.sqlassert]
dialect = "duckdb"
paths = ["models", "queries/**/*.sql"] # relative to this pyproject.toml
ignore = ["undeclared-table"]
In GitHub Actions, annotate the pull request directly, or upload SARIF to code scanning:
- run: sqlassert check --format github
# or
- run: sqlassert check --format sarif > sqlassert.sarif
- uses: github/codeql-action/upload-sarif@v3
if: always()
with:
sarif_file: sqlassert.sarif
sqlassert suggest¶
You rarely start from a blank page. suggest reads unannotated SQL and lists what sqlassert can already prove, each with the marker to paste:
$ sqlassert suggest query.sql # or: python -m sqlassert suggest query.sql
line 7 view active_users Non-Null Unique Set /**ASSERT NOT NULL UNIQUE(id)**/
line 7 view active_users Unique Set /**ASSERT UNIQUE(email)**/
line 7 view active_users Not Null /**ASSERT NOT NULL(name)**/
line 11 JOIN active_users AS u Many To One Join /**ASSERT MANY TO ONE**/
A column marker goes at the end of the Select Expression on that line; a join marker goes right before the join. Pick the facts you want locked in: a later change that breaks one turns it UNKNOWN. --explain prints each proof; --annotate pastes every suggested marker into the file (for -, it prints the annotated SQL).
From Python, suggest(sql) returns the same suggestions, each with its site, property, marker, and evidence; report.annotated() returns the SQL with every marker pasted in. Only proved properties are suggested, each Unique Set in its strongest form (NOT NULL UNIQUE over UNIQUE) and minimal (no superset of another suggestion), and each join in its most specific proved form: EXACTLY ONE, then ONE TO ONE, then MANY TO ONE or ONE TO MANY. Unique Sets are searched exhaustively up to max_size columns (default 3); a wider one is still found when no smaller one exists. Properties the SQL already asserts or declares are not suggested again.
Rewrites and hazards¶
Before any marker, suggest lists rewrites to the SQL itself (type rewrite; markers are marker). Each is a rewrite a proof shows leaves the result unchanged, row for row, printed as the reason and a unified diff of the exact edits that make it. The edits are placed from the SQL's tokens and change only what the rewrite needs: the rest of the text, comments and markers included, stays as written. One that may change an output column's type or precision, or overflow where the original did not, is a rewrite with caveat, listed after the others: its message ends with a Caveat: naming the column and the risk (sqlassert has no result-type model per dialect, so precision and type differences are caveated, never refused). A plain rewrite never turns a query that runs into one that fails.
create table users (id integer primary key, name varchar);
create table coupons (id integer primary key, code varchar);
create table orders (id integer primary key, user_id integer not null references users (id), coupon_id integer);
with big as (select * from orders where user_id > 100)
select o.id, u.name, u.id as user_id
from orders o
left join users u on u.id = o.user_id
left join coupons c on c.id = o.coupon_id
group by o.id, u.name, u.id;
$ sqlassert suggest orders.sql
rewrite line 4 CTE big Unused CTE CTE big is never referenced, so it never runs and its markers go unchecked: delete it
--- orders.sql
+++ orders.sql (rewritten)
@@ -2,5 +2,4 @@
create table coupons (id integer primary key, code varchar);
create table orders (id integer primary key, user_id integer not null references users (id), coupon_id integer);
-with big as (select * from orders where user_id > 100)
select o.id, u.name, u.id as user_id
from orders o
rewrite line 7 LEFT JOIN users AS u INNER JOIN every left row matches exactly one right row, so the LEFT JOIN pads nothing: write JOIN
...
rewrite line 9 Root Select GROUP BY of one row per group no two rows agree on ('o.id', 'u.name', 'u.id'), NULL equal to NULL, so every group is one row: drop GROUP BY and write each aggregate as its value over that row
--- orders.sql
+++ orders.sql (rewritten)
@@ -6,4 +6,3 @@
from orders o
left join users u on u.id = o.user_id
-left join coupons c on c.id = o.coupon_id
-group by o.id, u.name, u.id;
+left join coupons c on c.id = o.coupon_id;
marker line 7 LEFT JOIN users AS u Exactly One Join /**ASSERT EXACTLY ONE**/
...
Each diff is of that rewrite alone, against the original SQL.
| Rewrite | When |
|---|---|
INNER JOIN |
A LEFT (or RIGHT) JOIN that never keeps a padded row: it matches exactly one row, or a later inner join's ON, a WHERE EXISTS/IN subquery, or the WHERE clause of the same Select rejects NULL in a column it pads, directly or through a later LEFT JOIN whose ON rejects that column (so it pads the same rows). |
| Redundant Join | No column of the joined relation is used outside its own ON, and the join keeps every left row once: a LEFT JOIN with at most one match, or an Exactly One inner JOIN. |
| Filter-Only Join | The same for an inner JOIN with at most one match: it only filters, so it moves into the WHERE as EXISTS (SELECT 1 FROM <relation> WHERE <its ON>). Not suggested when a RIGHT or FULL JOIN follows it. |
| Redundant DISTINCT | No two rows agree on the selected columns, NULL equal to NULL. |
| Redundant ORDER BY key | The ORDER BY keys before it determine it, NULL equal to NULL: it never breaks a tie. Silent when a key is an expression or a name sqlassert cannot map to one column. |
| Redundant GROUP BY | The remaining grouping columns determine this one, NULL equal to NULL. One grouping column always stays. |
| GROUP BY of one row per group | No two input rows agree on the grouping columns, NULL equal to NULL: every group is one row, so GROUP BY goes and each aggregate is its value over that row (count(*) is 1, count(x) a CASE, sum, avg, min, max, any_value, bool_and, bool_or of x are x), in the select list and in HAVING, whose condition then moves into WHERE (HAVING count(*) > 1 becomes WHERE 1 > 1). A rewrite with caveat when a type or precision changes: sum(x) of an INTEGER is a HUGEINT in DuckDB, x an INTEGER; sum(x) + 1 may overflow as x + 1; avg(x) of a BIGINT, HUGEINT, UBIGINT or DECIMAL is x, its exact value, where avg's DOUBLE may round it. None where the value may differ otherwise (sum of a BOOLEAN, avg of an integer inside an expression, which may divide as an integer) or the argument's type is unknown, nor beside a call SQLGlot does not know (DuckDB's mean or arbitrary), which may be an aggregate the analysis does not model. Every spelling of a call it models is rewritten: with ALL or DISTINCT, IGNORE or RESPECT NULLS, BigQuery's HAVING MAX, or as an ODBC {fn ...} escape. |
| Redundant EXISTS | A WHERE EXISTS, IN subquery or SEMI JOIN every row passes: each row matches exactly one row of it (a non-null Foreign Key onto a key, and an ON of column equalities only). |
| Unused CTE | Nothing in its WITH reaches it, directly or through another CTE. Its markers are never checked either. |
report.rewrites holds them, each with its site, kind, message, edits (each an Edit(start, end, replacement) on the original SQL's offsets), evidence, and suggest_type (SuggestType.REWRITE or SuggestType.REWRITE_WITH_CAVEAT); rewrite.rewritten(report.sql) is the rewritten SQL and rewrite.diff(report.sql) its diff. --explain prints the proofs. Padding is only followed within the join's own Select Expression: past it, a LIMIT, window, or aggregate may see the padded rows before a filter removes them.
Hazards come last: places whose result the SQL leaves unspecified. report.hazards holds them, each with its site, concern, message, and the failed proof as evidence.
| Hazard | When |
|---|---|
| Arbitrary LIMIT | A LIMIT or OFFSET whose ORDER BY (if any) does not determine every selected column, NULL equal to NULL: rows tied on the sort keys may come in any order, so which rows are kept can change between runs. Silent when an ORDER BY key is an expression or a name sqlassert cannot map to one column. |
| Scalar subquery | A scalar subquery not proved to return at most one row, a runtime error when it returns more: uncorrelated, its body is not proved to have at most one row; correlated, the columns its WHERE binds to the outer row are not proved a Unique Set. |
| Lossy comparison | An equality (=, <>, IS [NOT] DISTINCT FROM, an IN list or subquery) whose operands both have a known type and that loses information: a float on either side (a column, an expression or a literal: floats round, so x = 0.1 misses a DOUBLE computed as 0.1 + 0.2 - 0.2, a.id = d.x of a BIGINT and a DOUBLE matches two ids above 2^53, and so does b = a + 1e0 of BIGINTs), or text compared with another type (the text is cast, so different strings may match one value: '01' and '1' both equal 1). No cardinality or dependency is proved across it either. In a join's ON, a WHERE or HAVING, and an IN or EXISTS correlation. Silent for an ordering (<, >), an operand whose type is unknown, and a string literal beside a date, boolean or UUID (read as that type); beside a number it is lossy too (int_col = '5'). Compare within a tolerance, cast explicitly, or use an exact type. |
| Fan Trap | An aggregate over a join that is not proved to repeat rows of only one input, when its argument (or, for count(*), either input) comes from rows the join may repeat: sum(p.amount) over orders JOIN payments USING (customer_id). |
| Chasm Trap | An aggregate over a one-to-many join whose argument is on the side with one row per key: sum(c.credit) over customers JOIN orders. Every aggregate counts, min and max included. Silent when the repeated input has no known Unique Set, or the argument reads both inputs. |
| Star with GROUP BY | SELECT *, count(*) FROM t GROUP BY k: the star selects every column, and the SQL standard rejects any that is neither grouped nor aggregated. Read from the syntax, whatever the star selects (every column grouped, or DuckDB's GROUP BY ALL, included). List the grouped columns and the aggregates. |
| QUALIFY beside an aggregate | A QUALIFY on a select that aggregates without GROUP BY filters the one row the aggregate returns, keeping it or dropping it: SELECT count(*) AS n FROM t QUALIFY row_number() OVER () = 1. Filter it with HAVING, or GROUP BY a key to rank the groups. |
| Constant partition key | A window anywhere in a select (its list, QUALIFY or ORDER BY) that partitions by a literal (PARTITION BY 1, 'a'): every row is in one partition and nothing is partitioned: SELECT id, row_number() OVER (PARTITION BY 1 ORDER BY ts) AS rn FROM t. Partition by a column, or drop PARTITION BY. |
| Duplicate output name | A select whose output columns are all known outputs one name twice: SELECT *, 1 AS w FROM t where t has a column w, two items of one name, or two stars sharing a column name. A reference by that name reads only the first, and the engine renames the others (DuckDB's w_1) or rejects them. Reported for every select whose names are read: the root's reach its consumer; not an IN, EXISTS or scalar subquery's, nor a set operation's operand after the first (its columns are paired by position), except under BY NAME. Silent when a star cannot be expanded (the table has no CREATE): its names are unknown. Alias each output column. |
| Many-to-many join | A join with no join marker that is not proved to repeat rows of only one input, both inputs having a known Unique Set: orders JOIN payments USING (customer_id) repeats each order once per payment and each payment once per order. A many-to-many join is rarely meant. Silent for an explicit CROSS JOIN, a semi or anti join, a join in the FROM of a Select whose DISTINCT or GROUP BY merges the repeats (an aggregate's trap says what they do to it), and a join whose ON equates every column of a known key of one input, when only an unknown column type or an expression keeps the proof from binding it. Write the join marker you expect (/**ASSERT MANY TO ONE**/, ...) and check proves it or says why not. |
NATURAL JOIN is unsupported: its presence anywhere in the program produces an unsupported-natural-join diagnostic, and suggest returns no suggestions. Write explicit ON or USING conditions instead.