Documentation

CslibFrontier.Languages.SQL.Query

SQL queries with bag semantics #

Query S n is a query over the database schema S whose result rows have n columns: a table, WHERE (Query.select), a SELECT list (Query.project), an inner join ON θ (Query.join; a cross join is ON TRUE), UNION ALL (Query.unionAll) and DISTINCT (Query.distinct). The output arity is the type index, so a projection list or a join predicate cannot refer to a column its input lacks.

Query.eval D q evaluates q on the instance D and returns a list of rows or an error. The list is a bag: projection, join and UNION ALL keep duplicates, and only DISTINCT removes them, treating rows with NULL in the same places as duplicates, as SQL's DISTINCT does (Mathlib's List.dedup, which keeps the last copy). The list order is a property of this representation, not of SQL, which promises no order without ORDER BY: here a table keeps its list order, WHERE keeps the order of its input, a join enumerates pairs with the left row outermost, and UNION ALL lists its left input first. The equivalences in Cslib.SQL.Query.Equiv decide how much of the order a law may rely on.

Evaluation is strict. A WHERE or ON predicate is evaluated on every input row or pair, and a projection on every input row, from left to right; the first error fails the whole query, even when an engine might never have reached the failing row. On an empty input nothing is evaluated, so the same query succeeds (Expr.filterRows, Expr.evalRow).

Query.typeOf q is the typing context of the result, if q is well-typed: predicates are boolean in the context of their input, projections are well-typed, and UNION ALL combines two inputs of the same types. Type soundness (Query.eval_ok_or_divisionByZero): on a conforming instance, a well-typed query returns rows conforming to its type, or fails with divisionByZero, which requires a division that is not divSafe; it never raises typeMismatch. The decidable check Query.IsSafe (well-typed, every division by a nonzero literal) guarantees that evaluation succeeds on every conforming instance.

It adapts and redesigns the queries of sql_equiv (revision 38030a6b) by Evelyn Mitchell. There, queries were untyped syntax whose column names were looked up in the rows at run time, and the evaluator for the richer fragment (aggregates, subqueries, set operations) was partial. Here the fragment is the select–project–join–union core with DISTINCT, columns are positions checked by the type index, evaluation is structural and total, and errors are results rather than rows silently dropped.

Main definitions #

Main results #

def Cslib.SQL.Row.product {n m : ℕ} (rs : List (Row n)) (ss : List (Row m)) :
List (Row (n + m))

The rows of the cross join of rs and ss: every row r of rs followed by every row s of ss gives the joined row Fin.append r s, with the left row outermost.

Instances For
    theorem Cslib.SQL.Row.mem_product {n m : ℕ} {rs : List (Row n)} {ss : List (Row m)} {t : Row (n + m)} :
    t ∈ product rs ss ↔ ∃ r ∈ rs, ∃ s ∈ ss, Fin.append r s = t

    A row of the cross join is a left row joined with a right row.

    theorem Cslib.SQL.Row.conforms_of_mem_product {n m : ℕ} {Γ : Fin n → SqlType} {Δ : Fin m → SqlType} {rs : List (Row n)} {ss : List (Row m)} (hrs : ∀ r ∈ rs, Conforms Γ r) (hss : ∀ s ∈ ss, Conforms Δ s) {t : Row (n + m)} (ht : t ∈ product rs ss) :

    The rows of a cross join of conforming rows conform to the joined typing context.

    SELECT lists and WHERE on rows #

    def Cslib.SQL.Expr.evalRow {n k : ℕ} :
    (Fin k → Expr n) → Row n → Except EvalError (Row k)

    Evaluate a SELECT list on a row, from left to right: the row of results, or the first error.

    Instances For
      def Cslib.SQL.Expr.filterRows {n : ℕ} (p : Expr n) (rs : List (Row n)) :

      Keep the rows on which the predicate is TRUE, in order, as WHERE and ON do. The predicate is evaluated on every row, and the first error fails the whole filter.

      Instances For
        theorem Cslib.SQL.Expr.evalRow_eq_ok_iff {n k : ℕ} {es : Fin k → Expr n} {r : Row n} {d : Row k} :
        evalRow es r = Except.ok d ↔ ∀ (i : Fin k), eval r (es i) = Except.ok (d i)

        A SELECT list succeeds with the row d exactly when each expression succeeds with its cell of d.

        theorem Cslib.SQL.Expr.exists_evalRow_eq_ok_iff {n k : ℕ} {es : Fin k → Expr n} {r : Row n} :
        (∃ (d : Row k), evalRow es r = Except.ok d) ↔ ∀ (i : Fin k), ∃ (d : Datum), eval r (es i) = Except.ok d

        A SELECT list succeeds exactly when each of its expressions does.

        theorem Cslib.SQL.Expr.exists_eval_eq_error_of_evalRow_eq_error {n k : ℕ} {es : Fin k → Expr n} {r : Row n} {e : EvalError} (h : evalRow es r = Except.error e) :
        ∃ (i : Fin k), eval r (es i) = Except.error e

        When a SELECT list fails, one of its expressions fails with that error.

        theorem Cslib.SQL.Expr.toOption_evalRow_congr {n k : ℕ} {es es' : Fin k → Expr n} {r : Row n} (h : ∀ (i : Fin k), (eval r (es i)).toOption = (eval r (es' i)).toOption) :

        SELECT lists whose expressions have the same observations on a row have the same observation on it.

        theorem Cslib.SQL.Expr.toOption_filterRows {n : ℕ} (p : Expr n) (rs : List (Row n)) :

        WHERE succeeds exactly when the predicate succeeds on every row, and then keeps the rows on which it is TRUE, in order.

        theorem Cslib.SQL.Expr.mem_of_filterRows_eq_ok {n : ℕ} {p : Expr n} {rs rs' : List (Row n)} (h : p.filterRows rs = Except.ok rs') {r : Row n} (hr : r ∈ rs') :
        r ∈ rs

        When WHERE succeeds, it keeps some of its input rows.

        theorem Cslib.SQL.Expr.evalTruth_spec {n : ℕ} {Γ : Fin n → SqlType} {r : Row n} (hr : Row.Conforms Γ r) {p : Expr n} (hp : typeOf Γ p = some SqlType.bool) :
        Except.Spec (fun (x : Truth) => True) (fun (err : EvalError) => err = EvalError.divisionByZero ∧ p.divSafe = false) (evalTruth r p)

        Type soundness for predicates: on a conforming row, a boolean predicate has a truth value, or divides by zero, which requires a division that is not divSafe.

        Equijoin predicates #

        def Cslib.SQL.Expr.eqCols {n m : ℕ} (i : Fin n) (j : Fin m) :
        Expr (n + m)

        The equijoin predicate q₁.i = q₂.j over the joined row of an n-column left input and an m-column right input: column i of the left input (Fin.castAdd m i) equals column j of the right input (Fin.natAdd n j).

        Instances For
          theorem Cslib.SQL.Expr.evalTruth_eqCols {n m : ℕ} (i : Fin n) (j : Fin m) (r : Row n) (s : Row m) :
          evalTruth (Fin.append r s) (eqCols i j) = CmpOp.eq.eval (r i) (s j)

          The equijoin predicate on a joined row is the three-valued comparison of the two keys.

          theorem Cslib.SQL.Expr.evalTruth_eqCols_eq_ok_true_iff {n m : ℕ} {i : Fin n} {j : Fin m} {r : Row n} {s : Row m} :
          evalTruth (Fin.append r s) (eqCols i j) = Except.ok Truth.true ↔ ∃ (v : Value), r i = some v ∧ s j = some v

          The equijoin predicate keeps a pair of rows exactly when both keys are the same non-null value.

          theorem Cslib.SQL.Expr.isSafePredicate_eqCols_iff {n m : ℕ} {Γ : Fin n → SqlType} {Δ : Fin m → SqlType} {i : Fin n} {j : Fin m} :
          IsSafePredicate (Fin.append Γ Δ) (eqCols i j) ↔ Γ i = Δ j

          The equijoin predicate is a safe predicate on the joined rows exactly when the two key columns have the same type.

          Queries #

          inductive Cslib.SQL.Query (S : DbSchema) :
          ℕ → Type

          A query over the schema S whose result rows have n columns.

          • table {S : DbSchema} (t : S.Table) : Query S (S.arity t)

            The rows of a table, in the instance's list order.

          • select {S : DbSchema} {n : ℕ} (p : Expr n) (q : Query S n) : Query S n

            SELECT * FROM q WHERE p: the rows of q on which p is TRUE.

          • project {S : DbSchema} {n k : ℕ} (es : Fin k → Expr n) (q : Query S n) : Query S k

            SELECT es₀, …, esₖ₋₁ FROM q: one row of results per row of q; duplicates are kept.

          • join {S : DbSchema} {n m : ℕ} (θ : Expr (n + m)) (q₁ : Query S n) (q₂ : Query S m) : Query S (n + m)

            q₁ JOIN q₂ ON θ: the joined rows Fin.append r s of the pairs on which θ is TRUE. The left columns come first; a cross join is ON TRUE.

          • unionAll {S : DbSchema} {n : ℕ} (q₁ q₂ : Query S n) : Query S n

            q₁ UNION ALL q₂: the rows of both, with duplicates.

          • distinct {S : DbSchema} {n : ℕ} (q : Query S n) : Query S n

            SELECT DISTINCT * FROM q: one copy of each row of q. Rows with NULL in the same places and equal values elsewhere are duplicates.

          Instances For
            def Cslib.SQL.Query.eval {S : DbSchema} (D : Database S) {n : ℕ} :
            Query S n → Except EvalError (List (Row n))

            Evaluate a query on a database instance: the bag of result rows as a list, or the first error. Every predicate and projection is evaluated on every row of its input.

            Instances For
              @[simp]
              theorem Cslib.SQL.Query.eval_table {S : DbSchema} (D : Database S) (t : S.Table) :
              eval D (table t) = Except.ok (D t)
              theorem Cslib.SQL.Query.eval_select {n : ℕ} {S : DbSchema} (D : Database S) (p : Expr n) (q : Query S n) :
              eval D (select p q) = do let __do_lift ← eval D q p.filterRows __do_lift
              theorem Cslib.SQL.Query.eval_project {n k : ℕ} {S : DbSchema} (D : Database S) (es : Fin k → Expr n) (q : Query S n) :
              eval D (project es q) = do let __do_lift ← eval D q List.mapM (Expr.evalRow es) __do_lift
              theorem Cslib.SQL.Query.eval_join {n m : ℕ} {S : DbSchema} (D : Database S) (θ : Expr (n + m)) (q₁ : Query S n) (q₂ : Query S m) :
              eval D (join θ q₁ q₂) = do let rs ← eval D q₁ let ss ← eval D q₂ θ.filterRows (Row.product rs ss)
              theorem Cslib.SQL.Query.eval_unionAll {n : ℕ} {S : DbSchema} (D : Database S) (q₁ q₂ : Query S n) :
              eval D (q₁.unionAll q₂) = do let rs ← eval D q₁ let ss ← eval D q₂ pure (rs ++ ss)
              theorem Cslib.SQL.Query.eval_distinct {n : ℕ} {S : DbSchema} (D : Database S) (q : Query S n) :
              eval D q.distinct = do let __do_lift ← eval D q pure __do_lift.dedup
              theorem Cslib.SQL.Query.eval_join_eq_ok_of_forall {n m : ℕ} {S : DbSchema} {D : Database S} {θ : Expr (n + m)} {q₁ : Query S n} {q₂ : Query S m} {rs : List (Row n)} {ss : List (Row m)} (h₁ : eval D q₁ = Except.ok rs) (h₂ : eval D q₂ = Except.ok ss) (hθ : ∀ r ∈ rs, ∀ s ∈ ss, ∃ (t : Truth), Expr.evalTruth (Fin.append r s) θ = Except.ok t) :
              eval D (join θ q₁ q₂) = Except.ok (List.map (fun (x : Row n × Row m) => match x with | (r, s) => Fin.append r s) (List.filter (fun (x : Row n × Row m) => match x with | (r, s) => decide ((Expr.evalTruth (Fin.append r s) θ).toOption = some Truth.true)) (rs ×ˢ ss)))

              When the join predicate θ succeeds on every pair of input rows, the join succeeds and returns the joined rows of the pairs on which θ is TRUE, in the order of rs ×ˢ ss.

              Typing and safety #

              def Cslib.SQL.Query.typeOf {S : DbSchema} {n : ℕ} :
              Query S n → Option (Fin n → SqlType)

              The typing context of the query's result rows, if the query is well-typed: WHERE and ON predicates are boolean over their input, the expressions of a SELECT list are well-typed, and the inputs of UNION ALL have the same types.

              Instances For
                @[simp]
                theorem Cslib.SQL.Query.typeOf_table {S : DbSchema} (t : S.Table) :
                (table t).typeOf = some (S.ctx t)
                theorem Cslib.SQL.Query.typeOf_select_eq_some {n : ℕ} {S : DbSchema} {p : Expr n} {q : Query S n} {Γ : Fin n → SqlType} :
                theorem Cslib.SQL.Query.typeOf_project_eq_some {n k : ℕ} {S : DbSchema} {es : Fin k → Expr n} {q : Query S n} {Δ : Fin k → SqlType} :
                (project es q).typeOf = some Δ ↔ ∃ (Γ : Fin n → SqlType), q.typeOf = some Γ ∧ ∀ (i : Fin k), Expr.typeOf Γ (es i) = some (Δ i)
                theorem Cslib.SQL.Query.typeOf_join_eq_some {n m : ℕ} {S : DbSchema} {θ : Expr (n + m)} {q₁ : Query S n} {q₂ : Query S m} {Γ' : Fin (n + m) → SqlType} :
                (join θ q₁ q₂).typeOf = some Γ' ↔ ∃ (Γ : Fin n → SqlType) (Δ : Fin m → SqlType), q₁.typeOf = some Γ ∧ q₂.typeOf = some Δ ∧ Expr.typeOf (Fin.append Γ Δ) θ = some SqlType.bool ∧ Fin.append Γ Δ = Γ'
                theorem Cslib.SQL.Query.typeOf_unionAll_eq_some {n : ℕ} {S : DbSchema} {q₁ q₂ : Query S n} {Γ : Fin n → SqlType} :
                (q₁.unionAll q₂).typeOf = some Γ ↔ q₁.typeOf = some Γ ∧ q₂.typeOf = some Γ
                def Cslib.SQL.Query.divSafe {S : DbSchema} {n : ℕ} :
                Query S n → Bool

                Every division in the query's predicates and projections is by a nonzero integer literal.

                Instances For
                  def Cslib.SQL.Query.IsSafe {n : ℕ} {S : DbSchema} (q : Query S n) :

                  The query is well-typed and every division in it is by a nonzero literal; then it succeeds on every conforming instance (Query.IsSafe.exists_eval_eq_ok).

                  Instances For
                    @[instance_reducible]
                    theorem Cslib.SQL.Query.eval_spec {n : ℕ} {S : DbSchema} {D : Database S} (hD : D.Conforms) {q : Query S n} {Γ : Fin n → SqlType} (hq : q.typeOf = some Γ) :
                    Except.Spec (fun (rs : List (Row n)) => ∀ r ∈ rs, Row.Conforms Γ r) (fun (err : EvalError) => err = EvalError.divisionByZero ∧ q.divSafe = false) (eval D q)

                    Type soundness as a postcondition: on a conforming instance, a well-typed query returns rows of its type, or divides by zero, which requires a division that is not divSafe.

                    theorem Cslib.SQL.Query.eval_ok_or_divisionByZero {n : ℕ} {S : DbSchema} {D : Database S} (hD : D.Conforms) {q : Query S n} {Γ : Fin n → SqlType} (hq : q.typeOf = some Γ) :
                    (∃ (rs : List (Row n)), eval D q = Except.ok rs ∧ ∀ r ∈ rs, Row.Conforms Γ r) ∨ eval D q = Except.error EvalError.divisionByZero ∧ q.divSafe = false

                    Type soundness: on a conforming instance, a well-typed query returns rows of its type, or divides by zero, which requires a division that is not divSafe.

                    theorem Cslib.SQL.Query.eval_ne_typeMismatch {n : ℕ} {S : DbSchema} {D : Database S} (hD : D.Conforms) {q : Query S n} {Γ : Fin n → SqlType} (hq : q.typeOf = some Γ) :

                    A well-typed query never raises a type error on a conforming instance.

                    theorem Cslib.SQL.Query.conforms_of_eval_eq_ok {n : ℕ} {S : DbSchema} {D : Database S} (hD : D.Conforms) {q : Query S n} {Γ : Fin n → SqlType} (hq : q.typeOf = some Γ) {rs : List (Row n)} (h : eval D q = Except.ok rs) (r : Row n) :
                    r ∈ rs → Row.Conforms Γ r

                    The rows of a well-typed query on a conforming instance conform to its type.

                    theorem Cslib.SQL.Query.IsSafe.exists_eval_eq_ok {n : ℕ} {S : DbSchema} {q : Query S n} (hs : q.IsSafe) {D : Database S} (hD : D.Conforms) :
                    ∃ (rs : List (Row n)), eval D q = Except.ok rs

                    A safe query succeeds on every conforming instance.