Skip to content

Quickstart

Install

pip install sqlassert   # Python 3.13+

Mark what a query must guarantee

Every order has one user, and every user one email, so this query should return one row per order. Say so, with a marker before each join:

create table users (id integer primary key, name varchar);
create table orders (id integer primary key, user_id integer, amount decimal(10, 2));
create table user_emails (user_id integer, email varchar);

select o.id, u.name, e.email
from orders o
/**ASSERT MANY TO ONE**/ join users u on u.id = o.user_id
/**ASSERT MANY TO ONE**/ join user_emails e on e.user_id = u.id;

A marker is a SQL comment: the query still runs unchanged on your database.

Check it

$ sqlassert check orders.sql
orders.sql:8:1: error unproved-many-to-one-join: /**ASSERT MANY TO ONE**/ is not proved (UNKNOWN)
    orders.sql:8:26: JOIN user_emails AS e ON e.user_id = u.id is not many-to-one  [declare] no-unique-set (undeclared-key)
        user_emails AS e: (user_id) is not a key
        it has no Unique Set: declare one if it holds
1 file checked: 2 assertions (1 PROVED, 1 UNKNOWN), 1 error, 0 warnings

The first join is proved by users' primary key. The second is not: nothing makes user_emails.user_id unique, so a user with two emails would repeat their orders. Each line under the finding is a Cause, tagged with who can act on it: [declare] means the tables do not declare what the proof needs.

Fix it

Make user_id the key of user_emails (or deduplicate it with GROUP BY, DISTINCT or QUALIFY row_number() ... = 1), and both joins are proved:

$ sqlassert check orders.sql
1 file checked: 2 assertions (2 PROVED, 0 UNKNOWN), 0 errors, 0 warnings

check exits 0 only when every assertion is proved, so in CI a later change that breaks a marker fails the build. See CLI for output formats (SARIF, GitHub annotations) and configuration.

Start from what is already proved

On SQL with no markers, suggest lists what sqlassert can prove, each with the marker to paste, plus rewrites and hazards:

$ sqlassert suggest orders.sql
marker  line 7  JOIN users AS u        Many To One Join     /**ASSERT MANY TO ONE**/
marker  line 8  JOIN user_emails AS e  Many To One Join     /**ASSERT MANY TO ONE**/
marker  line 8  Root Select            Non-Null Unique Set  /**ASSERT NOT NULL UNIQUE(id)**/

--annotate pastes them into the file.

Next