6.4. Equivalence
Cslib.SQL.Query.Equiv ℓ q₁ q₂ says that on every conforming instance both queries fail,
or both succeed with results related at level ℓ: the same list, the same bag, or the same set.
Laws about expressions lift into queries by congruence. Here AND commutes inside a WHERE
clause; the input's typing context is needed because expression equivalence speaks about
conforming rows.
abbrev isOne : Expr 2 := .binary (.cmp .eq) (.col 1) (.lit (.int 1))
abbrev isAnn : Expr 2 := .binary (.cmp .eq) (.col 0) (.lit (.text "ann"))
example : Equiv .ordered (.select (.binary .and isOne isAnn) emp)
(.select (.binary .and isAnn isOne) emp) :=
Equiv.select_expr (Γ := S.ctx Tbl.emp) rfl
(Expr.Equiv.binary_comm (fun a b => a:Datumb:Datum⊢ (evalBinOp BinOp.and a b).toOption = (evalBinOp BinOp.and b a).toOption All goals completed! 🐙) _ _)
A law that moves or drops an evaluation needs a side condition. Because evaluation is strict,
moving a WHERE clause below a SELECT list that may fail can turn a failing query into a
succeeding one; the decidable check Cslib.SQL.Expr.IsSafe (well-typed, dividing only by
nonzero literals) rules this out. The join-size tests prove such a rewrite for a concrete
query with the check discharged by decide, and show a failing instance when the check fails.
The fragment has no subqueries, outer joins, aggregates or ORDER BY yet; the
manual page lists the limitations and the known differences from SQLite.