Markers¶
A marker is a SQL comment, so annotated SQL still runs unchanged. /**ASSERT ...**/ states a Property sqlassert must prove; /**DECLARE ...**/ states one it may assume. Markers are the stable contract of sqlassert.
Join cardinality¶
Joins often accidentally multiply rows. A query may look correct against today’s data but silently break when a relation later contains multiple matching rows.
sqlassert lets you mark the cardinality a join is expected to have. The words read in FROM order: the left input is everything before the join, the right its joined source.
| Marker | Proved when | Rows the join may repeat |
|---|---|---|
/**ASSERT UNIQUE**/ (or NOT MANY TO MANY) |
either input is unique on the join key | one input's at most |
/**ASSERT MANY TO ONE**/ |
the right input is unique on the join key | the right input's only |
/**ASSERT ONE TO MANY**/ |
the left input is unique on the join key | the left input's only |
/**ASSERT ONE TO ONE**/ |
both are | none |
select *
from customers
/**ASSERT ONE TO MANY**/ join orders
on orders.customer_id = customers.id;
UNIQUE catches the fan trap, a many-to-many join that multiplies both sides. A direction says which side is safe to aggregate: after customers JOIN orders, sum(orders.amount) is right but sum(customers.credit) counts each customer once per order. When UNIQUE is proved, its explanation names the input that was unique.
The marker is just a SQL comment. Your SQL remains valid SQL and can still run normally. sqlassert reads the query separately and validates that the input is provably unique for the join keys. A SEMI or ANTI join outputs no right rows, so no cardinality marker applies to it (cardinality-on-filtering-join).
Unique Set and Non-Null Unique Set¶
A Select Expression can assert that specific output columns form a Unique Set. Use UNIQUE when the columns may be null, or NOT NULL UNIQUE when every column must also be non-null:
create table users (
id integer primary key,
email varchar unique
);
create view active_users as
select id, email
from users
where id > 0
/**ASSERT NOT NULL UNIQUE(id)**/;
select * from active_users;
The trailing marker applies to the relation produced by that Select Expression. After the last token of a query with UNION, INTERSECT or EXCEPT (its ORDER BY and LIMIT included), it applies to the whole query; to mark its last operand alone, put that operand in parentheses. A marker between two operands applies to the one before it. /**ASSERT NOT NULL UNIQUE(id)**/ asserts that (id) is a specific non-null Unique Set of active_users; /**ASSERT UNIQUE(email)**/ would assert nullable-tolerant uniqueness instead. The assertion is proved from the SQL Program, not trusted as a declaration. If it cannot be proved, its outcome is UNKNOWN.
Unique Set Assertions can be attached to a Root Select, view, CTE, or FROM subquery. A proved assertion on a named relation is also available to later statements in the same SQL Program.
A NOT NULL UNIQUE assertion is proved when the columns are a Unique Set and each one is non-null.
Uniqueness is proved through functional dependencies, so a key does not have to pass through unchanged. A column pinned to a constant drops out of a key (select id from items where tenant_id = 5 is unique on id when (tenant_id, id) is), a column equal to a key column stands in for it (an inner join on o.user_id = u.id lets u.id replace o.user_id), and grouping columns another grouping column determines are not needed (group by u.id, u.name is unique on id).
PRIMARY KEY is accepted as a convenience alias for NOT NULL UNIQUE (/**ASSERT PRIMARY KEY(id)**/, /**DECLARE PRIMARY KEY(id)**/). Unlike SQL's PRIMARY KEY, it does not mean one key per relation: a relation may have several Non-Null Unique Sets, and nothing checks that only one is marked.
Not Null¶
/**ASSERT NOT NULL(col, ...)**/ proves that every listed output column is non-null. One assertion covers the whole list, and an UNKNOWN explanation names each column that could not be proved. Non-nullness comes from NOT NULL and PRIMARY KEY constraints, declarations, non-null literals, coalesce/ifnull/nvl with at least one non-null argument, and null-rejecting conditions: a WHERE or inner-join ON conjunct col = ... or col IS NOT NULL. It follows pass-through and renamed columns through filters, projections, grouping keys, views, CTEs, and subqueries. The null-extended side of a LEFT, RIGHT, or FULL join is padded with NULLs, and a null-rejecting WHERE conjunct on any padded column (where u.id = 5) proves that join matched, so every column it padded is non-null again unless it is nullable for its own reasons. An UNKNOWN explanation names each source, such as "nickname is nullable in users" and "nickname is padded by the LEFT JOIN". Non-nullness is never guessed for other computed expressions or for set operations.
Not Null Elements¶
/**ASSERT NOT NULL ELEMENTS(col, ...)**/ proves that no listed column's value (an ARRAY, ROW or MAP) holds a NULL element, nested ones included; the value itself may still be NULL. No catalog states it, so it comes only from /**DECLARE NOT NULL ELEMENTS(col, ...)**/, followed through pass-through columns, coalesce and CASE. It matters for comparisons: ARRAY[1, NULL] <> ARRAY[1, NULL] and ROW(1, NULL) = ROW(1, NULL) are NULL in Trino, so a comparison of composites is non-null only when no element is NULL either. A comparison of a composite column or CAST warns (composite-comparison) unless its elements are declared. To declare them for a table, select it in a CTE or view that carries the declaration:
create table posts (id integer, tags array(varchar) not null, old_tags array(varchar) not null);
with tagged as (select id, tags, old_tags from posts /**DECLARE NOT NULL ELEMENTS(tags, old_tags)**/)
select id, tags <> old_tags as retagged from tagged /**ASSERT NOT NULL(retagged)**/
If an operand's type is unknown, a comparison may require evidence that its elements are non-null. Declare the source type or supply a catalog connection to resolve it.
Foreign Key¶
/**ASSERT FOREIGN KEY(col, ...) REFERENCES relation(col, ...)**/ proves that the listed output columns reference a Unique Set of a named table, view, or CTE. Columns pair by position, so FOREIGN KEY(org, owner) REFERENCES users(org, name) pairs org with org and owner with name; listing the pairs in another order means the same Foreign Key.
create table users (id integer primary key);
create table orders (
id integer,
user_id integer references users(id)
);
select * from orders
/**ASSERT FOREIGN KEY(user_id) REFERENCES users(id)**/;
A Foreign Key needs two things, and an UNKNOWN explanation names whichever is missing:
- Referential coverage: every row whose referencing columns are all non-null has a matching referenced row. It comes from column-level
REFERENCESand table-levelFOREIGN KEYconstraints inCREATE TABLE(a constraint without columns references the primary key), from catalog foreign keys, and fromDECLARE FOREIGN KEY. It holds on the table itself and on a directselect * from table; it is not yet carried through filters, projections, joins, or views. - A Unique Set on the referenced columns, proved or declared like any other.
Nulls follow SQL's MATCH SIMPLE: a row with a null in any referencing column is exempt, so nullable referencing columns do not weaken a Foreign Key. Assert NOT NULL separately when every row must match.
LIMIT preserves facts about the rows it retains, including outgoing Foreign Keys, uniqueness, non-nullness, and Enumerated Domains. It may remove a required referenced row, so coverage onto its input does not establish coverage onto its result. The same boundary applies to OFFSET. A hard limit of at most one row also proves uniqueness without an input key.
Equality Groups merge columns only when their declared comparison types are known and match. Mixed or unknown types leave value propagation unproved, even when SQL would compare them using implicit casts.
/**DECLARE FOREIGN KEY(...) REFERENCES relation(...)**/ states the coverage as trusted evidence (Declared ReferentialCoverage in explanations); it never vouches for the referenced Unique Set, which is still proved separately. A marker naming a column the referenced relation does not have is reported as unknown-referenced-column.
Exactly One Join¶
/**ASSERT EXACTLY ONE**/ before a join proves that every left row matches exactly one right row: the join neither multiplies nor drops left rows, and a LEFT join null-extends none of them.
create table users (id integer primary key);
create table orders (
id integer,
user_id integer not null references users(id)
);
select * from orders
/**ASSERT EXACTLY ONE**/ join users
on orders.user_id = users.id;
It is supported on INNER and LEFT joins whose predicate is a single column-to-column equality (ON or a one-column USING). It needs three things, and an UNKNOWN explanation names each one that is missing:
- At most one match: the right predicate column covers a Unique Set, as for
/**ASSERT MANY TO ONE**/. - At least one match: Referential Coverage from the left column onto that exact right column, as for a Foreign Key. Coverage onto a table is not coverage onto a filtered view or CTE of it.
- A non-null left column, since a null matches nothing.
Any additional conjunct in the predicate, even another equality, makes the assertion UNKNOWN: it could remove the guaranteed match. Composite keys and joins over derived relations are not supported yet.
Every assertion is written with an explicit ASSERT. A bare /**UNIQUE**/ is rejected with a diagnostic that names the explicit spelling.
Functional Dependency¶
/**ASSERT DETERMINES(a, b -> c, d)**/ proves that rows agreeing on a and b agree on c and d. Like a Unique Set it is lax: rows with a null in a or b are exempt; agreement on c and d counts NULL as equal to NULL.
select p.part_id, s.rating
from part p
left join supply s on p.part_id = s.part_id and s.rating = 'A'
/**ASSERT DETERMINES(part_id -> rating)**/;
Dependencies come from keys, equalities and constants in WHERE and ON, grouping, and DISTINCT. On an outer join, the preserved side's ON columns determine the null-supplying columns the condition binds; a dependency of the null-supplying side survives only when the join cannot pad a row that agrees with a matched one.
/**DECLARE DETERMINES(zip -> city)**/ states a business rule no schema shows. Closure uses it like any other dependency, so (zip, street) is unique when (city, street) is and city is non-null.
Enum¶
/**ASSERT ENUM(status IN ('new', 'paid'))**/ proves that every non-null value of status is one of the listed values. NULL is never in the set: NOT NULL governs it separately. So a column that is always NULL, like CAST(NULL AS INTEGER) + 1, satisfies every ENUM; the proof then warns always-null-column, as does any proved UNIQUE, DETERMINES determinant, FOREIGN KEY, NOT NULL ELEMENTS or EXHAUSTIVE operand that holds only because a column it names is always NULL. One marker names one column, and lists distinct, non-null string, numeric, and boolean literals, which may be mixed: /**ASSERT ENUM(priority IN (1, 2, 3))**/, /**DECLARE ENUM(active IN (TRUE))**/. Anything else -- NULL, an empty list, a repeated value, DATE '2020-01-01', a column, an expression -- is reported as a malformed marker.
with o as (
select * from orders
/**DECLARE ENUM(status IN ('new', 'paid', 'void'))**/
)
select status from o where status <> 'void' and status in ('new', 'paid')
/**ASSERT ENUM(status IN ('new', 'paid'))**/;
Domains come from DECLARE ENUM and external Knowledge, literals, coalesce of enumerated arguments, and simple CASE expressions (see below), and follow pass-through and renamed columns through filters, joins, aliases, grouping keys, DISTINCT, views, CTEs, and subqueries. A WHERE or inner-join ON conjunct status = 'paid' or status IN ('new', 'paid') narrows it, as does an outer join's ON on the side it pads. A domain crosses equalities: after WHERE a = b (or an inner-join ON a = b), b's domain is a's intersected with its own. An asserted set larger than the known domain is proved; an UNKNOWN explanation lists each possible value the assertion does not cover, such as "status may be 'void', which the assertion does not cover". A declaration does not claim that every listed value occurs. UNION columns, aggregates other than grouping keys, and other computed expressions are not enumerated.
A value keeps its SQL type: numeric 1, string '1', and TRUE are three values, and none covers another. A number is identified by how it is written, because that is its SQL type: 007 is 7, but 1.0 (a decimal) and 1e0 (a double) are not 1, so asserting ENUM(n IN (1)) of a column known to be 1.0 is UNKNOWN. Narrowing is more careful than identity: SQL compares a column with a literal after implicit casts, so one value can equal two different literals -- a FLOAT equals both 0.1 and 0.100000001, a VARCHAR '1.4' equals both 1 and 1.4, and an INTEGER equals both 1 and '1'. Domains therefore never lose a value that might equal one on the other side. Distinct strings, too, can equal one value -- an INTEGER equals '01' and '1', a MySQL VARCHAR equals 'a' and 'A' -- so they narrow each other only on a column declared VARCHAR or TEXT compared by identity: in DuckDB, PostgreSQL or Trino (whose default collation is binary). A column of unknown type is not narrowed that way. A MySQL ENUM column's domain is its members without trailing spaces, as MySQL stores them (under its default strict sql_mode).
Exhaustive CASE¶
/**ASSERT EXHAUSTIVE**/, written immediately before a simple CASE, proves that every value in the operand's known Enumerated Domain has a WHEN arm of its own:
with o as (
select * from orders
/**DECLARE ENUM(status IN ('new', 'paid', 'void'))**/
)
select id,
/**ASSERT EXHAUSTIVE**/ case status when 'new' then 'open' when 'paid' then 'closed' when 'void' then 'closed' end as state
from o;
ELSE never stands in for an arm: add a status to the declaration without a matching WHEN, and the assertion is UNKNOWN with "status may be 'refunded', which no WHEN arm lists". Arms cover values by identity, as for ENUM: WHEN 1 does not cover '1' or 1.0. A NULL operand matches no arm; that is NOT NULL's business, asserted separately. With no known domain for the operand, the assertion is UNKNOWN.
The marker may mark a CASE anywhere it is lowered: a select list, WHERE, or a join's ON. A CASE nested inside a function call or an aggregate is reported as unanalyzed. A searched CASE WHEN ..., a WHEN value that is not a string, numeric, or boolean literal (including NULL), a repeated WHEN value, and a marker not immediately followed by CASE are reported as malformed markers. Exhaustiveness can only be asserted: /**DECLARE EXHAUSTIVE**/ is reported.
A simple CASE takes one of its THEN values or its ELSE value (NULL when it has none), so its result has an Enumerated Domain when they all do. When the CASE is exhaustive and its operand NOT NULL, ELSE is unreachable and drops out: above, with status also declared NOT NULL, state is proved ENUM(state IN ('open', 'closed')) even if the CASE had ELSE 'unknown'.
Declaring what you know¶
When you know a fact the SQL cannot show -- say, an upstream job guarantees one row per user_id -- state it with DECLARE instead of ASSERT:
with latest as (
select user_id, max(ts) as ts from events group by all
/**DECLARE UNIQUE(user_id)**/
)
select * from orders
/**ASSERT MANY TO ONE**/ join latest on orders.user_id = latest.user_id;
A declaration is an assumption, not a proof. It produces no assertion result, and it is trusted evidence for later proofs; explanations show it as Declared UniqueSet. Every column marker has a DECLARE form -- DECLARE UNIQUE, DECLARE NOT NULL, DECLARE NOT NULL UNIQUE, DECLARE DETERMINES, and DECLARE ENUM -- attached wherever its ASSERT form can be. DECLARE NOT NULL UNIQUE(a, b) declares the Unique Set and also each column non-null, so a stays non-null after b is projected away.
Join Cardinality Syntax¶
Place a cardinality marker (UNIQUE, NOT MANY TO MANY, MANY TO ONE, ONE TO MANY, ONE TO ONE) immediately before the join it checks:
select *
from lhs
/**ASSERT UNIQUE**/ left join rhs
on lhs.rhs_id = rhs.id;
ON and USING are both supported:
select *
from users
/**ASSERT UNIQUE**/ join user_profiles
using (id);
The marker applies to the next join after the comment.