Metakit / Write a rule once
2. Generate SQL CHECK and WHERE from the same rule
Because the invariant is data rather than a closure, @doeixd/metakit/sql compiles it to SQL without re-writing it.
import * as Sql from '@doeixd/metakit/sql'
const check = Result.getOrThrow(Sql.toCheck(Account, { dialect: 'postgres' }))
// check ->
// CHECK ((((("balance" >= 0) AND ("reserved" >= 0)) AND ("reserved" <= "balance"))) IS TRUE)
const openHigh = Expr.in({ row: Account }, ({ row }) =>
Expr.all(Eq.is(row.status, 'open'), Num.gte(row.balance, 20_000)),
)
const where = Result.getOrThrow(Sql.toWhere(openHigh, { dialect: 'postgres' }))
// where.text -> (("status" IS NOT DISTINCT FROM $1) AND ("balance" >= $2))
// where.params -> ['open', 20000]What happened: toCheck wrote the CHECK clause for your migration, and toWhere wrote a WHERE clause with its values as parameters. Expr.in({ row: Account }, …) builds an expression over a named input, here the row, and the default rowPrefix, the path row, says paths under it are columns, so row.status becomes "status".
The check ends in IS TRUE because SQL lets a CHECK pass when its result is null; here a null result fails, as it does when the Schema decodes the value. Eq.is compiles to IS NOT DISTINCT FROM in Postgres (IS in SQLite), so it answers of a null column as Expr.eval, metakit's in-memory evaluator, does. The same predicate selects the same rows on both databases and in Expr.eval.