Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Elinvar and SQL

Status: describes what is built, 2026-12-02. Covers reading a SQL schema into a model and the verbs that work on SQL: import, accepts, fuzz, audit, discover, and ci.

Elinvar reads the rules of a SQL database schema (keys, foreign keys, checks, unique indexes, triggers) and writes an Alloy 6 model in Elinvar’s subset (LOGIC.md section 15). The other verbs check that model against scripts, a real database, a data dump, or candidate invariants. The importer is in crates/elinvar-als/src/sql.rs; the verbs are in the cli module of crates/elinvar. This file says what they do now. The command line in general is DESIGN.md section 9.3, and results as data are DESIGN.md section 9.5.

Contents: 1 Input · 2 What is read · 3 What is not read · 4 The generated model · 5 SQL in the other verbs · 6 import · 7 accepts · 8 fuzz · 9 audit · 10 discover · 11 ci · 12 Codes

1. Input

1.1 Files and directories

A schema is a .sql file or a directory. A directory is read as a list of migrations: its regular files whose extension is sql, in any case, are sorted by file name in byte order and joined, each preceded by a line -- migration: NAME and followed by an empty line. A directory with no such file is cli.input. A place in a result or a message, in JSON and in text, names the migration file and the line in it, and so do the comments of a generated model and the reasons in them.

--with FILE, repeatable, adds a sidecar. A sidecar whose name ends in .sql is appended to the schema text, so it can add views and named queries. Any other sidecar is Alloy text appended to the generated model, so it can add promises (assert and check) and predicates. When an Alloy sidecar contains a run or check command, the generated run Show command is left out.

1.2 Lexing

Statements end at ;, except inside a trigger’s BEGIN ... END. Comments are -- ... to the end of the line and /* ... */. A line that starts with \ (a psql meta-command written by pg_dump) is passed over. Strings are single-quoted, with '' for a quote. Identifiers may be quoted with ", backquotes, or [ ]. Keywords are read in any case. Names are compared without regard to case; a schema qualifier (public.users) is dropped.

An unterminated string, or an integer that does not fit in 64 bits, is als.syntax, and nothing is imported. So is a schema with no CREATE TABLE.

2. What is read

2.1 Statements

StatementRead as
CREATE [OR REPLACE] [TEMP|TEMPORARY] TABLE [IF NOT EXISTS] t (...)a table (section 2.2, section 2.3); options after the closing parenthesis are passed over
CREATE TYPE t AS ENUM ('a', ...)a closed set of values for columns of type t
CREATE DOMAIN d [AS] base_type [NOT NULL] [DEFAULT literal] [CHECK (expr)]a reusable column type whose base kind, NOT NULL, literal DEFAULT, and CHECK constraints (with VALUE bound to the column) are inherited by columns of type d
CREATE UNIQUE INDEX n ON t (cols) [WHERE cond]a uniqueness rule, partial when it has WHERE (section 4.4)
CREATE VIEW v [(cols)] AS SELECT ...a function of the state (section 4.5); a later view of the same name replaces an earlier one
-- name: q (or query:) on the line before a top-level SELECTa named query, read like a view
CREATE TRIGGER ...with --temporal, a guard or an action on a step (section 4.7)
ALTER TABLEchanges the table read so far (section 2.4)
DROP TABLE, DROP INDEX, DROP TRIGGER, DROP VIEWremoves what was read so far under that name; a trigger the static shape skipped leaves the skipped list

The rules a schema ends with are those left after every statement has been applied in order. A migrations directory therefore gives the schema of its last migration.

2.2 Columns

Column typeKind
INT, INTEGER, INT2, INT4, INT8, BIGINT, SMALLINT, TINYINT, SERIAL, BIGSERIAL, SMALLSERIAL, NUMERIC, DECIMAL, REAL, DOUBLE [PRECISION]integer
TIMESTAMP, TIMESTAMPTZ, DATETIME, DATE, TIME, TIMETZtime
BOOL, BOOLEANboolean
the name of a CREATE TYPE ... AS ENUMclosed set of its values
the name of a CREATE DOMAINinherits the domain’s base kind, NOT NULL, literal DEFAULT, and CHECK constraints
any other type (TEXT, VARCHAR(n), CHARACTER VARYING, unknown names)text

Lengths (n), array brackets, schema qualifiers, and WITH/WITHOUT TIME ZONE after a type are passed over. Columns of NUMERIC, DECIMAL, REAL, and DOUBLE hold integers in the model.

Column clauseRead as
NOT NULLthe field has exactly one value
NULL, or no clausethe field has at most one value
PRIMARY KEY [AUTOINCREMENT]not null and unique
UNIQUEunique among rows that have a value
REFERENCES u [(c)] [ON DELETE action]a foreign key (section 2.3)
CHECK (expr)a check on the row (section 2.5)
DEFAULT literalthe value accepts, fuzz, and audit give a column an INSERT leaves out; the model itself does not use it
GENERATED {ALWAYS|BY DEFAULT} AS IDENTITY [...]marks the column NOT NULL and passes over sequence options
GENERATED ALWAYS AS (expr) [STORED|VIRTUAL]when expr is supported (section 2.5), read as a row check col IS (expr); otherwise skipped
CONSTRAINT namenames the constraint, so ALTER TABLE ... DROP CONSTRAINT can remove it
COLLATE x, STORAGE x, COMPRESSION x, ASC, DESC, DEFERRABLE, INITIALLY DEFERRED, INITIALLY IMMEDIATEpassed over

2.3 Table constraints

[CONSTRAINT name] may precede each.

ConstraintRead as
PRIMARY KEY (c1, ...)each column not null; the columns together unique
UNIQUE (c1, ...)the columns together unique among rows where all of them have values
FOREIGN KEY (c1, ...) REFERENCES u [(d1, ...)] [ON DELETE action]a foreign key; with no target columns, the primary key of u when it has as many columns
CHECK (expr)a check on the row

A foreign key from one column becomes the type of the field: the field holds a row of the target table, not the target’s key value. A foreign key from several columns becomes a fact (section 4.4).

The ON DELETE actions read are CASCADE, SET NULL, RESTRICT, and NO ACTION; the last two, and no action at all, refuse the delete of a referenced row. Their effect is on the delete step (section 4.6).

2.4 Changes to tables

ALTER TABLE [IF EXISTS] [ONLY] t is read with these clauses:

ClauseEffect
ADD [CONSTRAINT n] PRIMARY KEY / UNIQUE / FOREIGN KEY / CHECKadds the constraint
ADD [COLUMN] defadds the column
RENAME TO urenames the table, and the foreign keys, indexes, and triggers that name it
RENAME [COLUMN] a TO brenames the column in the table’s own keys, foreign keys, checks, and indexes
DROP CONSTRAINT nremoves the named check, foreign key, unique constraint, or primary key
DROP [COLUMN] cremoves the column and every key, foreign key, check, and unique index that uses it
ALTER [COLUMN] c SET NOT NULL, DROP NOT NULLchanges whether the column may be null
ALTER [COLUMN] c SET DEFAULT literal, DROP DEFAULTchanges the default
OWNER TO, VALIDATE, ENABLE, DISABLE, CLUSTER, REPLICA, other SETignored

2.5 Expressions

Checks, partial-index filters, trigger conditions, and views use one expression language:

  • AND, OR, NOT, parentheses, and CASE [x] WHEN ... THEN ... [ELSE ...] END;
  • comparisons =, !=, <>, <, <=, >, >=, and IS [NOT] x;
  • x IS [NOT] NULL, x [NOT] IN (literals), x [NOT] IN (SELECT ...), x [NOT] BETWEEN lo AND hi, EXISTS (SELECT ...), and a scalar subquery;
  • + and - of a literal, COALESCE and IFNULL;
  • text shapes: GLOB, LIKE, length, char_length, trim, lower, upper, substr, compared with a literal;
  • SQLite dates: strftime(format, x [, shift]) and date(...);
  • query parameters :name, $name, $1, ?1, ? (in named queries);
  • literals: integers, strings, TRUE, FALSE, NULL; Postgres casts ::type are passed over.

Integer literals must lie in -32768..32767, the largest bitwidth Elinvar has (LOGIC.md section 16). A rule that uses a larger one is not read.

3. What is not read

Every statement falls into one of three groups.

  • Read: carried into the model (section 2).
  • Ignored: a statement that holds no rule, so leaving it out loses nothing. These are CREATE INDEX (not unique), CREATE SEQUENCE, CREATE SCHEMA, CREATE EXTENSION, ALTER SEQUENCE, ALTER TYPE, ALTER SCHEMA, ALTER VIEW, ALTER FUNCTION, ALTER DATABASE, other DROP forms, PRAGMA, BEGIN, COMMIT, END, ANALYZE, VACUUM, COMMENT, SET, GRANT, REVOKE, and SELECT set_config(...).
  • Skipped: a statement or clause that may hold a rule the model then lacks.

The import result lists ignored statements under ignored and skipped ones under skipped, each with its place, its SQL text, and a reason. The generated model carries each skipped item as a comment -- not read: FILE:LINE: SQL -- reason.

Skipped items include, with the reasons the importer gives:

WhatReason
a statement of no known form (CREATE FUNCTION, INSERT)statement is not read by SQL import
CREATE TYPE that is not AS ENUMunsupported CREATE TYPE definition (only AS ENUM is read)
a check, filter, or condition outside section 2.5unsupported CHECK expression (stopped at FILE:LINE:COL near TOKEN) and similar
a rule with an integer outside -32768..32767integer literal N exceeds Elinvar's 16-bit Int range (-32768..32767)
GENERATED ... on a column with an unsupported expressionGENERATED column expression is not read
a DEFAULT that is not a literal (now()), but for nextval(...) on a primary keyDEFAULT that is not a literal is not read: ...
any other column clause, such as SQLite’s ON CONFLICT REPLACEcolumn clause is not read
EXCLUDE USING ...EXCLUDE constraint is not read
ON DELETE SET DEFAULT, read as refusing the deleteON DELETE SET DEFAULT is not read: ...
a foreign key to a table not in the schema, or to columns that cannot be foundreferenced table X is not in the schema, and similar
a composite foreign key between columns of different kindscomposite FOREIGN KEY links columns of incompatible types
a view or named query with GROUP BY, HAVING, ORDER BY, LIMIT (other than LIMIT 1 on a constant), outer joins, or aggregatesunsupported SELECT query in CREATE VIEW, unsupported named SELECT query
ALTER TABLE and ALTER COLUMN clauses not in section 2.4unsupported ALTER TABLE clause, unsupported ALTER COLUMN clause
CREATE TRIGGER without --temporaltriggers are not read in static mode (use --temporal)
a trigger outside section 4.7the reason names the part not read

import --strict turns every skipped item into an error sql.skipped (section 6). The other verbs report how many rules were not read as unread_rules in their result, and say in their text that the verdict does not cover them.

4. The generated model

4.1 Two shapes

Without --temporal, the model is static: each table is a signature, each row an atom, and an instance is one state of the database.

With --temporal, the model is a model of time (LOGIC.md section 13, DESIGN.md section 8): the rows of each table change from state to state by insert, update, and delete steps, and triggers constrain or extend the steps.

Every model starts with -- Generated by Elinvar from SQL DDL, then a comment for each table or trigger the slice left out (section 4.10). It ends with the skipped items as comments and a command:

-- N Int fits every number in the schema (min..max)
run Show {} for 3 [but 4 steps] [, N Int] [, k S]

N is the smallest bitwidth from 4 to 16 that holds every integer literal the model uses; the comment and N Int appear when the model uses Int. 4 steps appears in the temporal shape. A text signature with three or more named values gets a scope of one more than their number.

4.2 Tables and columns

A table t becomes, in the static shape:

sig t {
  c: one K,      -- NOT NULL or PRIMARY KEY
  d: lone K      -- nullable
} {
  ...checks...
}

In the temporal shape:

sig t_row {}
var sig t in t_row { var c: one K, var d: lone K }
var sig t_retired in t_row {}

t_row holds every atom that may ever be a row of t. t holds the rows present in a state, and t_retired the rows that have been deleted. fact t_no_row_reuse says no atom is in both, so a deleted row’s atom is never inserted again. fact t_domain says atoms not in t have no column values.

--only-ruled leaves out every column no rule mentions: not in a key, a foreign key (at either end), a check, a unique index, a trigger, or a view.

4.3 Column kinds

The type K of a column’s field is chosen from how the schema uses the column. Columns that a rule compares with each other (in a check, a composite foreign key, an index filter, a trigger, a trigger’s insert, or a view) are grouped, and a group gets one type. The first case that applies decides:

CaseType
a single-column foreign keythe target table’s signature (t_row in the temporal shape)
a group of integer, time, or text columns compared by <, <=, >, >=, not with integer literals, with no fixed set of valuesan ordered signature t_c_ord, or time_ord or date_ord for a group of several columns, with open util/ordering[S] as ord_S
an integer group, not a key, used without arithmetic, compared with a literal outside -32..31 and with at most 32 distinct cut pointsan enumeration of regions enum t_c_int_enum { t_c_lt_N, t_c_eq_N, t_c_btw_N_M, t_c_gt_N }, a negative N written mN
a group of several closed-set columns, or of text columnsa shared enumeration of the union of their values, or a shared signature t_c_val
a text column with a check c IN ('a', ...) at the top level, or a Postgres enum typeenum t_c_enum { t_c_a, ... }
an integer columnInt
a boolean columnenum SqlBool { SqlTrue, SqlFalse }
a text or time columnsig t_c_val {}, with one sig t_c_LIT extends t_c_val {} for each string literal a rule compares it with

An enumeration from a CHECK ... IN keeps the check as a rule as well. A text check that names a shape (GLOB, LIKE, length, and the others in section 2.5) becomes a subset signature sig t_c_chk_N in t_c_val {} for the values that pass it; the import result’s sample_values gives a real value for each such subset, for fuzz and tests --sql to write. Columns used with strftime or date share an ordered signature of dates, with functions SqlDateFn and SqlOrdFn for formatting and for shifting by a constant.

4.4 Rules

A check is read with SQL’s three-valued logic: a row is refused only when the check is FALSE, and a NULL that makes it UNKNOWN lets the row through. The formula is therefore not of “the check is FALSE”. In the static shape checks sit in the signature’s fact block; in the temporal shape they are fact t_checks { always { all this: t | ... } }.

RuleFact
unique column cfact t_unique_c { all disj a, b: t | a.c != b.c }, with some a.c implies before the inequality when c is nullable
unique columns, or a composite primary keyfact t_unique_N { no disj a, b: t | a.c1 = b.c1 and ... }, where a nullable column adds some a.c and
CREATE UNIQUE INDEX n ... [WHERE f]fact t_uniq_n { no disj a, b: t | f(a) and f(b) and ... }; a row is covered when f is TRUE for it; ifnull(c, lit) or coalesce(c, lit) in the column list makes NULL equal to lit
composite foreign key to ufact t_fk_u_N { all x: t | (some x.c1 and ...) implies (some r: u | r.d1 = x.c1 and ...) }

In the temporal shape every rule is wrapped in always, so a step that would break one is not a step of the model.

4.5 Views and named queries

A view or named query v becomes fun v: set (K1 -> K2 ...), the set of tuples its SELECT gives in a state, under set semantics (UNION ALL is UNION). Supported are a projection of expressions or *, FROM with ,, JOIN, INNER JOIN, and CROSS JOIN with ON, WHERE, DISTINCT, UNION, INTERSECT, EXCEPT, and LIMIT 1 on a constant projection. A projected column takes its name from an alias or, in a union, from the first arm. A named query’s parameters become the function’s arguments: -- name: shares_of before SELECT s.id FROM shares s WHERE s.account_id = :acct becomes fun shares_of[acct: accounts_row]: set shares_row.

A promise in a sidecar can use a view by name. Views are also what diff --of compares (DESIGN.md section 9.3).

4.6 Steps

In the temporal shape each table t has these predicates, on a row atom r:

PredicateMeaning
insert_t[r]r is in neither t nor t_retired; t' = t + r; the new row’s columns are any values the rules allow; every other row and table stays the same
update_t[r]r is in t; any column of r may change; every other row and table stays the same
delete_t[r]r moves from t to t_retired, with the effect of each foreign key into t
same_tt, t_retired, and every column of t stay the same
nothingevery table stays the same

The effect of a foreign key from s into t on delete_t[r]: RESTRICT, NO ACTION, or no action add the guard no x: s | x.fk = r; CASCADE deletes the rows of s that reference r in the same step; SET NULL clears their reference. A CASCADE reaches every depth, as SQLite’s and Postgres’s do: the rows of s it deletes are a set D_s, and a foreign key from u into s acts on D_s as one into t acts on r (x.fk in D_s in place of x.fk = r). The sets are built parents first. When the CASCADE keys reached from t form a cycle, or a table’s CASCADE key refers to itself, only the rows that reference r directly are reached, and a delete the cycle would carry further is refused.

fact trace { always (nothing or (some r: t_row | insert_t[r]) or ...) } makes every step one of these. A trigger’s guard is a conjunct of its step (section 4.7).

4.7 Triggers

With --temporal, a trigger is read when it has this form:

CREATE TRIGGER name {BEFORE | AFTER} {INSERT | UPDATE [OF c1, ...] | DELETE}
  ON t [FOR EACH ROW] [WHEN cond]
BEGIN
  SELECT RAISE({ABORT | ROLLBACK | FAIL}, 'message') [FROM ...] [WHERE cond];
END;

or with a body of one INSERT INTO u [(cols)] VALUES (...). In conditions NEW.c is the column after the step, (r.c)', and OLD.c the column before, r.c. A subquery reads the state before the step in a BEFORE trigger and the state after it in an AFTER trigger.

A RAISE trigger becomes a predicate name[r] that holds when the trigger does not fire: not (WHEN and WHERE). It is a conjunct of the step for its event. An UPDATE OF trigger fires when a listed column changes value. A condition that is an OR at the top is split into predicates name_branch_N, one per disjunct, so a refusal names the branch.

An INSERT trigger makes its step, when the trigger fires, also insert a fresh row of u: some w: u_row - u - u_retired | ..., with the listed columns given the listed values, columns left out NULL when nullable and unconstrained otherwise. When it does not fire, u stays the same. A trigger whose target table the step already changes is skipped with the reason table X is already modified in this step. A row a trigger inserts does not fire further triggers.

Not read, each with a reason: INSTEAD OF triggers, RAISE(IGNORE), bodies with more than one statement, EXECUTE FUNCTION and other bodies, and triggers on tables not in the schema.

4.8 Initial states

Static models have no initial state. A temporal import starts from any state the rules allow (--from-any, the default for import). --from-empty adds

fact StartEmpty { no t and no t_retired and ... }

so every state is reached by steps from empty tables.

4.9 Names

SQL names become Alloy names by these rules, in order:

  1. Every character that is not an ASCII letter, digit, or _ becomes _; a name that starts with a digit gets a leading _. Case is kept.
  2. A name that is an Alloy keyword gets the suffix _sql. The keywords are abstract after all always and as assert before but check disj else enum eventually exactly expect extends fact for fun historically iden iff implies in int Int let lone module no none not once one open or pred releases run seq set sig since some steps String sum this triggered univ until var.
  3. A column named like a variable the generated formulas bind (a, b, d, r, w, x, and q, v, or p followed by digits), or like a table, gets _sql.
  4. A name already taken gets _2, _3, and so on.

Enumeration values are prefixed with table and column (orders_status_open becomes orders_status_open_sql, as open is a keyword). The import keeps the map from SQL names to Alloy names, and accepts, fuzz, and audit use it, so their scripts and reports use SQL names.

4.10 Slicing

--tables A,B imports only some tables, like the slicing of DESIGN.md section 7.9. The slice is the named tables, or for a named view the tables it reads, closed under foreign keys to their targets; in the temporal shape it also takes in the tables the kept tables’ triggers read or write. A name that is neither a table nor a view is als.unknown_name.

--with-referencing also adds, until nothing changes, every table with a foreign key into the slice. Without it, those tables are listed in outside_referencing_tables and in a model comment, since their foreign keys could refuse a delete the slice allows. A trigger on a kept table that writes outside the slice, or a trigger on a left-out table, is dropped and listed in dropped_triggers as NAME (on T, writes outside slice) or NAME (on dropped table T).

5. SQL in the other verbs

check, run, tests, eval, and diff take a .sql file or a migrations directory wherever they take a model, and import it first. The import is temporal when the schema creates a trigger (CREATE, then TRIGGER within the next four words), or when an Alloy sidecar has a temporal operator (always, after, until, …), steps, induction, a prime, or a call insert_t[...], update_...[...], or delete_...[...] of a step predicate; and static otherwise. Words inside comments and quoted strings do not count. For check and run, a temporal import starts from empty tables unless --from-any is given. The model’s bitwidth is the one of section 4.1, unless the command sets one.

6. import

elinvar import FILE|DIR [--with FILE] [--json] [--strict]
  [--temporal [--from-empty | --from-any]] [--tables A,B [--with-referencing]]
  [--only-ruled]

Prints the generated model (section 4) on standard output. When anything was skipped, ignored, left out by the slice, or dropped, a one-line note on standard error says how many: elinvar import: skipped N rule(s), M non-rule statement(s) ignored; slice left out referencing table(s): ...; slice dropped K trigger(s) (see comments or --json).

--from-empty and --from-any need --temporal, and only one may be given. --with-referencing needs --tables. --strict, --temporal, and --only-ruled are flags of import only. A flag misused is cli.usage.

With --strict, any skipped item makes the import fail: one error sql.skipped per item, with its place, the message not read: SQL (reason), and exit status 3. Ignored statements do not fail it.

--json prints, per elinvar explain schema:import:

KeyHolds
elinvar1
tablesthe SQL names of the imported tables
viewsthe names of views and named queries, when there are any
skipped, ignoredeach item’s place, sql, and reason
outside_referencing_tablestables outside the slice with a foreign key into it
dropped_triggerstriggers the slice dropped
sample_valuesa real value for each text-shape subset (section 4.3)
modelthe model text

Errors give { elinvar, command: "import", errors, story }.

Exit status: 0 imported, 3 errors (including --strict with skipped items).

7. accepts

elinvar accepts FILE TRACE [--with FILE] [--tables A,B [--with-referencing]] [--json]

Says whether the schema allows a script of changes, and whether every check promise in a sidecar holds along it. FILE may also be an Alloy model, which is the general form of this verb (DESIGN.md section 9.3); this section is about a .sql FILE, imported temporal and from any state.

TRACE is a result JSON when its first non-blank character is { (unreadable JSON is eval.result), and a SQL script otherwise.

7.1 Scripts

The script is split at ; outside strings, with -- comments removed. Each statement is one of:

  • INSERT INTO t [(cols)] VALUES (v, ...) with one row; without a column list the values follow the table’s column order;
  • UPDATE t SET c = e [, ...] [WHERE w], where e is a literal, a column, or +, -, * of those, with parentheses;
  • DELETE FROM t [WHERE w].

w is an AND of c op literal, with op one of =, !=, <>, <, <=, >, >=, and c IS [NOT] NULL. Values are NULL, TRUE, FALSE, 'text', x'hex', and integers. Anything else, among it INSERT OR ..., INSERT ... SELECT, several rows in one VALUES, WHERE c IN (...), a SELECT, a text value for an integer column, or an empty script, is sql.script, exit status 3, with the message naming the line.

7.2 Judging

The script runs from empty tables. Each statement is judged against the last state the model accepted:

  • An INSERT fills columns it leaves out from their DEFAULT literal, and is one insert step.
  • An UPDATE or DELETE that matches several rows is one step per row, and is refused as a whole when any of its steps is refused. One that matches no row changes nothing and is allowed.
  • AFTER triggers that insert rows, and ON DELETE actions, are applied to the state. BEFORE UPDATE RAISE triggers fire on an UPDATE that sets a column to the value it has, as in SQLite.
  • A refused statement leaves the state as it was, and the script goes on.

The resulting states are refereed by the evaluator against the model (DESIGN.md section 7.6). A refusal names the rules that refuse it: a fact (fact users_unique_id), a field whose multiplicity fails (field email), a foreign key (foreign key orders.user_id -> users.id), or a trigger guard (update_jobs: no_reopen).

7.3 Output

Text: accepts: ALLOWED (N state(s)) or accepts: REFUSED (N state(s)); then for each refused statement line L: STATEMENT: refused by RULES; the line failed rules: ...; when some rules of the schema were not read, warning: N rule(s) of the schema are not read; a statement they refuse is allowed here; then check NAME: holds or check NAME: BROKEN for each promise.

--json, per elinvar explain schema:accepts: elinvar, command, allowed, failed_rules, checks (each name, holds), all_checks_hold, unread_rules (when at least 1), and refused_statements (each line, statement, rules).

Exit status: 0 every statement allowed and every check holds; 1 a statement refused or a check broken; 3 errors.

8. fuzz

elinvar fuzz FILE [--against CMD] [--seed N] [--scripts N] [--length N]
  [--require-coverage] [--with FILE] [--tables A,B [--with-referencing]]
  [--timeout DUR] [--json]

Runs random scripts of changes against a real database and against the model, statement by statement, and reports the first statement on which they disagree.

8.1 The database

--against names the database command line, sqlite3 by default. It is split into words without a shell, with quotes honored; an unclosed quote or an empty command is sql.database. Three kinds are known:

CommandHow a statement is run
sqlite3 ...a template database is made once from PRAGMA foreign_keys = ON; and the schema, with -bail; each script runs on a copy, each statement with the pragma
psql ...with -v ON_ERROR_STOP=1, each statement runs as BEGIN; schema; earlier statements; statement; ROLLBACK;
anything elsethe schema, the earlier statements, and the statement are sent each time

A statement is allowed by the database when the command exits with status 0. A database that rejects the schema, or a command that cannot be run, is sql.database, exit status 3. Files go in a temporary directory under the system’s temporary directory.

8.2 Scripts

The model is imported temporal, from any state, as for accepts. A schema with no table is als.syntax. A seeded generator (SplitMix64, --seed, default 1) writes --scripts scripts (default 100) of about --length statements (default 8). A script first inserts rows into a table and its foreign-key ancestors in dependency order, then inserts, updates, and deletes rows of populated tables: updates pick rows by primary key and try col + 1, NULL, and the values of closed sets. Up to min(scripts / 3, 24) scripts aim at the guards found by tests, and tables with checks or insert triggers get rows solved to pass them. The scripts depend only on the schema, the seed, and the counts: solves are bounded by conflicts, and --timeout can stop the planning but not shape it. When it runs out while planning, no script runs and the verdict is unknown.

8.3 Comparing

For each statement, the database’s answer is compared with accepts on the earlier allowed statements followed by this one (section 7). Both allowed: the statement joins the prefix. Both refused: the script goes on. They differ: when the database refused, the model allowed, and the database’s error message matches a rule that was not read, the case is counted under explained_by_unread and the run goes on. Otherwise the prefix is shrunk, by removing statements while the disagreement remains, and the run stops with verdict disagreed and the shortest script found. When --timeout runs out or the database fails while shrinking, the script is reported as found, unshrunk, with shrunk: false and the reason in note.

A statement the generator writes that accepts cannot read is sql.script with the message fuzzer generated an unsupported statement; it is a bug in the generator.

8.4 Output

Verdicts: agreed, every script run without disagreement; disagreed; unknown, when --timeout ran out, or --require-coverage was given and some table got no row or some read rule never refused a statement.

--json, per elinvar explain schema:fuzz: verdict, against, seed, scripts_run, statements_run, database_allowed, database_refused, model_allowed, model_refused, rows_inserted per table, rule_refusals per rule, rules_never_fired, unread_rules, explained_by_unread, disagreement (script, line, statement, database_allowed, database_error, model_allowed, model_rules, shrunk, or null), note, and story.

Exit status: 0 agreed; 1 disagreed; 2 unknown; 3 errors.

9. audit

elinvar audit SCHEMA --data DUMP [--with FILE] [--tables A,B [--with-referencing]] [--json]

Checks the rows of a data dump, as one state, against the schema’s rules and the single-state promises of a sidecar, with the evaluator and without the solver. --data - reads the dump from standard input.

9.1 Reading the dump

The schema is imported temporal, from any state. The dump is split into statements, passing over -- and /* */ comments and lines that start with \. Read are INSERT [INTO] t [(cols)] VALUES (...), (...) [ON CONFLICT ...], with several rows, values NULL, TRUE, FALSE, 'text', x'hex', and integers, and Postgres casts and parentheses around values removed. Columns an INSERT leaves out take their DEFAULT literal.

StatementEffect
INSERT into a table of the schema or slicerows read
INSERT into another tablewarning audit.dropped_rows, with the row count and first line
ALTER, ANALYZE, BEGIN, COMMENT, COMMIT, CREATE, DROP, END, GRANT, LOCK, PRAGMA, RELEASE, REVOKE, ROLLBACK, SAVEPOINT, SELECT, SET, START, UNLOCK, USE, VACUUMpassed over
any other statement, such as COPY or UPDATEwarning audit.ignored_statement
no INSERT at allwarning audit.no_rows; when the file also holds other statements, it is not a dump and is error audit.parse
an INSERT that cannot be read, or whose value count differs from its column counterror audit.parse

9.2 Rules

These rules are checked directly on the rows, each named in the report as shown: NOT NULL t.c, UNIQUE t.c, CHECK enum t.c, PRIMARY KEY t(cols), UNIQUE t(cols), UNIQUE INDEX name (partial ones included), and FOREIGN KEY t.c -> u.id. The model’s other facts that do not involve steps, among them checks and composite foreign keys, are evaluated on the one state; a broken one is reported with the detail schema rule does not hold on the dumped rows.

A promise (check command) of an Alloy sidecar is evaluated on the state when it does not use steps, after an outer always is removed. One that does is listed under skipped_promises with the reason requires multiple states (uses temporal step operators).

9.3 Output

Verdicts: clean, every rule and promise holds; violations.

Text starts audit (DATA against SCHEMA): VERDICT (...) and lists each broken rule, each promise as holds or BROKEN, skipped promises, warnings as warning[CODE]: line N: MESSAGE, and, when rules were not read, warning: N rule(s) of the schema were not read and could not be checked.

--json, per elinvar explain schema:audit: verdict, rows_audited, tables (rows per table), rule_violations (each rule, table, detail, line), promises, skipped_promises, unread_rules, warnings (each code, message, fix, place), and story.

Exit status: 0 clean; 1 violations; 3 errors.

10. discover

elinvar discover FILE [--with FILE] [--tables A,B [--with-referencing]]
  [--show-rejected] [--scope N] [--budget N] [--timeout DUR] [--json]

Tries common invariants on each table and keeps those proved for any number of steps within the scope.

10.1 Candidates

The schema is imported temporal and from empty tables. For each table in the slice (every table without --tables) the candidates are:

KindInvariant
never_populatedthe table is always empty
never_deletedno row is ever deleted
protected_by_referencea row is not deleted while a row of a given table references it, one candidate per single-column foreign key into the table
always_presenta nullable column always has a value
immutablea column never changes after insert
immutable_once_seta nullable column never changes once it has a value
never_cleareda nullable column never goes from a value to NULL
non_decreasingan integer column, not a key or foreign key, never decreases
uniquea column is unique across live rows, except a table’s sole primary key
at_most_one_openat most one row per key has its marker column NULL: for each partial unique index WHERE c IS NULL, and for nullable columns that look like markers (the table has at most 6 columns, or the name contains ended, closed, revoked, deleted, archived, completed, cancelled, canceled, expired, removed, finished, or stopped), keyed by the other columns that are not unique

A table proved never_populated gets no other candidate. A proved candidate leaves out the ones it implies: never_deleted leaves out protected_by_reference; immutable leaves out immutable_once_set, never_cleared, and non_decreasing; immutable_once_set leaves out never_cleared and non_decreasing; unique leaves out at_most_one_open on the same single key.

10.2 Proof

Each candidate is an assert checked by k-induction with k = 1 (DESIGN.md section 7.6) at --scope (default 3), with at most --budget conflicts (default 200000) per candidate; --timeout limits the whole run. Only proved candidates are kept as invariants. Each is given the rules it rests on, from a minimal unsatisfiable core taken without StartEmpty at a scope of at most 2. With --show-rejected, a candidate that is not proved is listed with the reason counterexample and the counterexample, or not_inductive.

Candidates may be checked in parallel; the output is in candidate order and does not depend on the number of threads.

10.3 Output

Text: discover: proved N invariant(s) across T table(s) (scope S; checked C candidate(s)), then per table a sentence for each invariant and rests on: ..., then, with --show-rejected, a not proved: section.

--json, per elinvar explain schema:discover: tables, scope, candidates_checked, candidates_unfinished, unread_rules, invariants (each table, column, kind, sentence, formula, rules), rejected (with --show-rejected; each also reason and counterexample), and story.

Exit status: 0 every candidate finished; 2 some did not finish within the budget or time; 3 errors.

11. ci

elinvar ci [MANIFEST] [--timeout DUR] [--junit | --sarif | --json]

Runs the entries of a manifest, elinvar.toml by default, under one shared time limit, and compares each entry’s verdict with the one it expects.

11.1 The manifest

The manifest is a small subset of TOML: key = value lines, # comments, and array-of-table headers. Values are strings in " or ', lists of strings, true, false, and integers. Top-level keys, before the first entry, set defaults: timeout (a duration such as 60s), and scope, steps, and budget (integers of at least 1).

EntryKeysDefault expectVerdicts
[[check]]name file command with tables with_referencing expect induction scope steps budget explainholdsthe check’s verdict; holds also matches proved
[[run]]name file command with tables with_referencing expect scope steps budgetfoundthe run’s verdict
[[accepts]]name file trace with tables with_referencing expectallowedallowed, refused
[[diff]]name old new migration of with tables with_referencing ignore_unread expect scope steps budgetequivalentthe diff’s verdict
[[discover]]name file with tables with_referencing scope budget expectcompletedcompleted, unknown
[[tests]]name file with tables with_referencing allow_dead scope steps budget expectpassedpassed, failed, unknown

file, old, new, trace, migration, and with are paths relative to the manifest’s directory; a directory is read as migrations (section 1.1). A [[diff]] with migration compares old with old followed by the migration. An entry without name is named KIND#N, N its position from 1. A check or run on a file with several commands takes the worst verdict among them.

An unknown section or key, a value of the wrong type, or a manifest with no entry is ci.manifest, exit status 3. A missing manifest file is cli.input. An entry that cannot run (a missing file, a missing required key, a model with errors) is not a manifest error: the entry has actual verdict error and fails.

11.2 Running

Entries run in order. Each gets the time left of the shared limit (--timeout, else the manifest’s timeout, else none); when none is left, the remaining entries are unknown with the message shared CI timeout exhausted. An entry passes when its actual verdict matches expect, is unknown when its verdict is unknown and expect is not, and fails otherwise.

11.3 Output

Markdown by default: a table of entry, kind, expected, actual, result, and time, a line verdict: VERDICT (P passed, F failed, U unknown, T ms), and the message of each entry that did not pass. --junit writes JUnit XML, --sarif SARIF 2.1.0; only one may be given, and neither with --json. --json, per elinvar explain schema:ci: manifest, verdict (passed, failed, unknown), passed, failed, unknown, elapsed_ms, entries (each name, kind, file, expected, actual, outcome, elapsed_ms, message), and markdown.

Exit status: 0 every entry passed; 1 an entry failed; 2 none failed and one is unknown; 3 manifest or argument errors.

12. Codes

The codes of this file, all explained by elinvar explain CODE and listed in CODES.md. Errors end a verb with exit status 3; warnings do not change the verdict.

CodeKindWhen
sql.skippederrorimport --strict met a statement or clause it does not read; diff of two SQL schemas whose unread rules differ, unless --ignore-unread
sql.scripterroraccepts was given a SQL script with a statement or value it cannot read; fuzz generated such a statement
sql.databaseerrorfuzz could not run the --against command, the command was malformed, or the database rejected the schema
audit.parseerroraudit met an unreadable INSERT or value, or a file that is not a dump
audit.dropped_rowswarningthe dump inserts rows into a table not in the schema or slice
audit.ignored_statementwarningthe dump has a statement that is neither an INSERT nor one passed over
audit.no_rowswarningthe dump has no INSERT
ci.manifesterrorthe manifest cannot be parsed, has an unknown section or key or a value of the wrong type, or has no entry

Other codes these verbs give: als.syntax (a schema that cannot be lexed or has no table), als.unknown_name (--tables names an unknown table), eval.result (an unreadable result JSON given to accepts), cli.usage (a flag misused), and cli.input (a file that cannot be read).