Skip to main content

oxilite_core/
reason.rs

1//! RDFS / OWL reasoning: the schema closure, query rewriting and OWL 2 RL materialization.
2//!
3//! Query-time reasoning rewrites each triple pattern into a derived table of *entailed*
4//! triples, computed from the asserted quads and `tbox_closure` (a small table recomputed by
5//! `optimize()` and by writes that touch schema predicates). Queries therefore stay single SQL
6//! statements. Materialization is explicit: OWL 2 RL rules run as `INSERT … SELECT`
7//! statements into `quads_inf` until nothing changes.
8//!
9// @lat: [[architecture#Reasoning]]
10
11use crate::encoding::{named_node_id, DEFAULT_GRAPH_ID, PAYLOAD_BITS};
12use crate::sql::{union_all, Statement};
13use oxrdf::vocab::{rdf, rdfs};
14use oxrdf::{QuadRef, Term, TermRef};
15use spargebra::term::{NamedNodePattern, TermPattern};
16use spargebra::{GraphUpdateOperation, Update};
17use std::collections::BTreeSet;
18
19/// Entailment regime of a query.
20#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
21#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
22#[cfg_attr(feature = "serde", serde(rename_all = "kebab-case"))]
23pub enum Reasoning {
24    /// Asserted triples only (Oxigraph's behaviour).
25    #[default]
26    None,
27    /// RDFS: subclass, subproperty, domain and range (plus equivalent classes and properties).
28    Rdfs,
29    /// RDFS plus the OWL QL property axioms: inverse and symmetric properties, and transitive
30    /// properties.
31    OwlQl,
32}
33
34const OWL: &str = "http://www.w3.org/2002/07/owl#";
35
36fn owl(local: &str) -> i64 {
37    named_node_id(&format!("{OWL}{local}"))
38}
39
40/// Ids of the vocabulary used by the closure and the rules.
41#[derive(Debug, Clone, Copy)]
42struct Vocab {
43    ty: i64,
44    sco: i64,
45    spo: i64,
46    dom: i64,
47    rng: i64,
48    eqc: i64,
49    eqp: i64,
50    inv: i64,
51    sym: i64,
52    trans: i64,
53    same: i64,
54    func: i64,
55    ifunc: i64,
56    has_value: i64,
57    on_property: i64,
58    some_values: i64,
59    all_values: i64,
60    intersection: i64,
61    union: i64,
62    chain: i64,
63    first: i64,
64    rest: i64,
65    nil: i64,
66    thing: i64,
67}
68
69fn vocab() -> Vocab {
70    Vocab {
71        ty: named_node_id(rdf::TYPE.as_str()),
72        sco: named_node_id(rdfs::SUB_CLASS_OF.as_str()),
73        spo: named_node_id(rdfs::SUB_PROPERTY_OF.as_str()),
74        dom: named_node_id(rdfs::DOMAIN.as_str()),
75        rng: named_node_id(rdfs::RANGE.as_str()),
76        eqc: owl("equivalentClass"),
77        eqp: owl("equivalentProperty"),
78        inv: owl("inverseOf"),
79        sym: owl("SymmetricProperty"),
80        trans: owl("TransitiveProperty"),
81        same: owl("sameAs"),
82        func: owl("FunctionalProperty"),
83        ifunc: owl("InverseFunctionalProperty"),
84        has_value: owl("hasValue"),
85        on_property: owl("onProperty"),
86        some_values: owl("someValuesFrom"),
87        all_values: owl("allValuesFrom"),
88        intersection: owl("intersectionOf"),
89        union: owl("unionOf"),
90        chain: owl("propertyChainAxiom"),
91        first: named_node_id(rdf::FIRST.as_str()),
92        rest: named_node_id(rdf::REST.as_str()),
93        nil: named_node_id(rdf::NIL.as_str()),
94        thing: owl("Thing"),
95    }
96}
97
98/// `tbox_closure.kind` values.
99pub mod kind {
100    /// `sub ⊑ sup` for classes (subClassOf and equivalentClass, transitive, irreflexive rows).
101    pub const CLASS: i64 = 1;
102    /// RDFS sub-property closure (subPropertyOf and equivalentProperty).
103    pub const PROPERTY: i64 = 2;
104    /// OWL: `(x sub y)` entails `(x sup y)` (sub-properties, inverses of inverses).
105    pub const OWL_SAME: i64 = 3;
106    /// OWL: `(x sub y)` entails `(y sup x)` (inverse and symmetric properties).
107    pub const OWL_INVERSE: i64 = 4;
108    /// Transitive properties (`sub = sup`).
109    pub const TRANSITIVE: i64 = 5;
110    /// RDFS: the subject of `sub` has type `sup` (domains through sub-properties/classes).
111    pub const SUBJECT_TYPE: i64 = 6;
112    /// RDFS: the object of `sub` has type `sup`.
113    pub const OBJECT_TYPE: i64 = 7;
114    /// OWL: the subject of `sub` has type `sup` (also through inverse ranges).
115    pub const OWL_SUBJECT_TYPE: i64 = 8;
116    /// OWL: the object of `sub` has type `sup`.
117    pub const OWL_OBJECT_TYPE: i64 = 9;
118}
119
120/// Predicates whose triples change the schema closure.
121pub fn schema_predicates() -> [i64; 6] {
122    let v = vocab();
123    [v.sco, v.spo, v.dom, v.rng, v.eqc, v.eqp]
124}
125
126/// Does a triple with this predicate and object change the closure?
127pub fn is_schema_triple(p: i64, o: i64) -> bool {
128    let v = vocab();
129    schema_predicates().contains(&p) || p == v.inv || (p == v.ty && (o == v.sym || o == v.trans))
130}
131
132fn is_schema_iri(p: &str) -> bool {
133    p == rdfs::SUB_CLASS_OF.as_str()
134        || p == rdfs::SUB_PROPERTY_OF.as_str()
135        || p == rdfs::DOMAIN.as_str()
136        || p == rdfs::RANGE.as_str()
137        || p.strip_prefix(OWL)
138            .is_some_and(|l| matches!(l, "equivalentClass" | "equivalentProperty" | "inverseOf"))
139}
140
141fn is_axiom_class(o: &str) -> bool {
142    o.strip_prefix(OWL)
143        .is_some_and(|l| matches!(l, "SymmetricProperty" | "TransitiveProperty"))
144}
145
146/// Does writing this quad change the schema closure?
147pub fn is_schema_quad(q: QuadRef<'_>) -> bool {
148    is_schema_iri(q.predicate.as_str())
149        || (q.predicate == rdf::TYPE
150            && matches!(q.object, TermRef::NamedNode(n) if is_axiom_class(n.as_str())))
151}
152
153/// Can this update change the schema closure? (Conservative: variables count as schema.)
154pub fn update_touches_schema(update: &Update) -> bool {
155    let pattern = |p: &NamedNodePattern, o: &TermPattern| match p {
156        NamedNodePattern::Variable(_) => true,
157        NamedNodePattern::NamedNode(n) if is_schema_iri(n.as_str()) => true,
158        NamedNodePattern::NamedNode(n) if *n == rdf::TYPE => match o {
159            TermPattern::NamedNode(c) => is_axiom_class(c.as_str()),
160            TermPattern::Variable(_) => true,
161            _ => false,
162        },
163        NamedNodePattern::NamedNode(_) => false,
164    };
165    update.operations.iter().any(|op| match op {
166        GraphUpdateOperation::InsertData { data } => data.iter().any(|q| {
167            is_schema_iri(q.predicate.as_str())
168                || (q.predicate == rdf::TYPE && matches!(&q.object, Term::NamedNode(n) if is_axiom_class(n.as_str())))
169        }),
170        GraphUpdateOperation::DeleteData { data } => data.iter().any(|q| {
171            is_schema_iri(q.predicate.as_str())
172                || (q.predicate == rdf::TYPE
173                    && matches!(&q.object, spargebra::term::GroundTerm::NamedNode(n) if is_axiom_class(n.as_str())))
174        }),
175        GraphUpdateOperation::DeleteInsert { delete, insert, .. } => {
176            delete.iter().any(|q| {
177                let o: TermPattern = q.object.clone().into();
178                pattern(&q.predicate, &o)
179            }) || insert.iter().any(|q| pattern(&q.predicate, &q.object))
180        }
181        GraphUpdateOperation::Create { .. } => false,
182        GraphUpdateOperation::Load { .. }
183        | GraphUpdateOperation::Clear { .. }
184        | GraphUpdateOperation::Drop { .. } => true,
185    })
186}
187
188/// SQL: the id is an IRI, a blank node or a triple term (a valid subject).
189pub(crate) fn non_literal(x: &str) -> String {
190    format!("(({x}) >> {PAYLOAD_BITS}) IN (1, 2, 9)")
191}
192
193/// Statements recomputing `tbox_closure` from the asserted quads (every graph).
194pub fn closure_statements() -> Vec<Statement> {
195    let v = vocab();
196    let (c, p, s_, t) = (
197        kind::CLASS,
198        kind::PROPERTY,
199        kind::OWL_SAME,
200        kind::TRANSITIVE,
201    );
202    let class_edges = format!(
203        "SELECT s AS a, o AS b FROM quads WHERE p = {sco} UNION SELECT s, o FROM quads WHERE p = {eqc} UNION SELECT o, s FROM quads WHERE p = {eqc}",
204        sco = v.sco,
205        eqc = v.eqc
206    );
207    let prop_edges = format!(
208        "SELECT s AS a, o AS b FROM quads WHERE p = {spo} UNION SELECT s, o FROM quads WHERE p = {eqp} UNION SELECT o, s FROM quads WHERE p = {eqp}",
209        spo = v.spo,
210        eqp = v.eqp
211    );
212    let closure = |k: i64, edges: &str| {
213        Statement::new(format!(
214            "WITH RECURSIVE e(a, b) AS ({edges}), c(a, b) AS (SELECT a, b FROM e UNION SELECT c.a, e.b FROM c JOIN e ON e.a = c.b) \
215             INSERT OR IGNORE INTO tbox_closure(kind, sub, sup) SELECT {k}, a, b FROM c WHERE a <> b"
216        ))
217    };
218    // OWL: property edges with a direction bit (1 = inverse), composed modulo 2.
219    let owl = Statement::new(format!(
220        "WITH RECURSIVE e(a, b, d) AS (SELECT a, b, 0 FROM ({prop_edges}) \
221           UNION SELECT s, o, 1 FROM quads WHERE p = {inv} UNION SELECT o, s, 1 FROM quads WHERE p = {inv} \
222           UNION SELECT s, s, 1 FROM quads WHERE p = {ty} AND o = {sym}), \
223         c(a, b, d) AS (SELECT a, b, d FROM e UNION SELECT c.a, e.b, (c.d + e.d) % 2 FROM c JOIN e ON e.a = c.b) \
224         INSERT OR IGNORE INTO tbox_closure(kind, sub, sup) SELECT {s_} + d, a, b FROM c WHERE d = 1 OR a <> b",
225        inv = v.inv,
226        ty = v.ty,
227        sym = v.sym,
228    ));
229    // Classes a domain/range class is a subclass of (reflexive).
230    let classes = format!(
231        "SELECT o AS a, o AS b FROM quads WHERE p IN ({dom}, {rng}) UNION SELECT sub, sup FROM tbox_closure WHERE kind = {c}",
232        dom = v.dom,
233        rng = v.rng
234    );
235    // Properties with (sub, sup) where sup is reflexive over properties having a domain/range.
236    let subs = |k: i64| {
237        format!(
238            "SELECT s AS a, s AS b FROM quads WHERE p IN ({dom}, {rng}) UNION SELECT sub, sup FROM tbox_closure WHERE kind = {k}",
239            dom = v.dom,
240            rng = v.rng
241        )
242    };
243    let typed = |k: i64, props: &str, axiom: i64| {
244        format!(
245            "SELECT {k}, pq.a, cd.b FROM ({props}) pq JOIN quads ax ON ax.p = {axiom} AND ax.s = pq.b JOIN ({classes}) cd ON cd.a = ax.o"
246        )
247    };
248    let inverse_typed = |k: i64, axiom: i64| {
249        format!(
250            "SELECT {k}, pq.sub, cd.b FROM tbox_closure pq JOIN quads ax ON ax.p = {axiom} AND ax.s = pq.sup JOIN ({classes}) cd ON cd.a = ax.o WHERE pq.kind = {inv}",
251            inv = kind::OWL_INVERSE
252        )
253    };
254    let insert = |sql: String| {
255        Statement::new(format!(
256            "INSERT OR IGNORE INTO tbox_closure(kind, sub, sup) {sql}"
257        ))
258    };
259    vec![
260        Statement::new("DELETE FROM tbox_closure"),
261        closure(c, &class_edges),
262        closure(p, &prop_edges),
263        owl,
264        Statement::new(format!(
265            "INSERT OR IGNORE INTO tbox_closure(kind, sub, sup) SELECT {t}, s, s FROM quads WHERE p = {ty} AND o = {trans}",
266            ty = v.ty,
267            trans = v.trans
268        )),
269        insert(typed(kind::SUBJECT_TYPE, &subs(p), v.dom)),
270        insert(typed(kind::OBJECT_TYPE, &subs(p), v.rng)),
271        insert(format!(
272            "{} UNION {}",
273            typed(kind::OWL_SUBJECT_TYPE, &subs(s_), v.dom),
274            inverse_typed(kind::OWL_SUBJECT_TYPE, v.rng)
275        )),
276        insert(format!(
277            "{} UNION {}",
278            typed(kind::OWL_OBJECT_TYPE, &subs(s_), v.rng),
279            inverse_typed(kind::OWL_OBJECT_TYPE, v.dom)
280        )),
281    ]
282}
283
284/// Loads the transitive properties (kept in memory with the planner statistics).
285pub fn transitive_statement(id_col: impl Fn(&str) -> String) -> Statement {
286    Statement::new(format!(
287        "SELECT {} FROM tbox_closure WHERE kind = {}",
288        id_col("sub"),
289        kind::TRANSITIVE
290    ))
291}
292
293/// Which graphs a reasoned pattern reads.
294#[derive(Debug, Clone)]
295pub enum GraphFilter {
296    /// Keep each quad's graph (the caller constrains `g`).
297    Keep,
298    /// The RDF merge of these graphs (`None`: every graph), exposed as graph 0.
299    Merge(Option<Vec<i64>>),
300}
301
302/// Builds derived tables of entailed triples.
303#[derive(Debug, Clone)]
304pub struct Entailment<'a> {
305    pub reasoning: Reasoning,
306    /// Also read materialized inferences (`quads_inf`).
307    pub inferred: bool,
308    pub transitive: &'a BTreeSet<i64>,
309    /// Maximum terms of a compound SELECT.
310    pub max_compound: usize,
311}
312
313impl Entailment<'_> {
314    /// Is any rewriting needed?
315    pub fn active(&self) -> bool {
316        self.reasoning != Reasoning::None || self.inferred
317    }
318
319    /// The table of stored triples: asserted, plus materialized inferences on request.
320    pub fn base(&self) -> &'static str {
321        if self.inferred {
322            "(SELECT s, p, o, g FROM quads UNION ALL SELECT s, p, o, g FROM quads_inf)"
323        } else {
324            "quads"
325        }
326    }
327
328    fn kinds(&self) -> (i64, Option<i64>, i64, i64) {
329        match self.reasoning {
330            Reasoning::OwlQl => (
331                kind::OWL_SAME,
332                Some(kind::OWL_INVERSE),
333                kind::OWL_SUBJECT_TYPE,
334                kind::OWL_OBJECT_TYPE,
335            ),
336            _ => (kind::PROPERTY, None, kind::SUBJECT_TYPE, kind::OBJECT_TYPE),
337        }
338    }
339
340    /// A `(s, p, o, g)` derived table of the entailed triples matching the constants.
341    pub fn source(
342        &self,
343        s: Option<i64>,
344        p: Option<i64>,
345        o: Option<i64>,
346        graphs: &GraphFilter,
347    ) -> String {
348        let base = self.base();
349        let g = |x: &str| match graphs {
350            GraphFilter::Keep => format!("{x}.g"),
351            GraphFilter::Merge(_) => DEFAULT_GRAPH_ID.to_string(),
352        };
353        let gw = |x: &str| match graphs {
354            GraphFilter::Merge(Some(l)) => format!(
355                " AND {x}.g IN ({})",
356                l.iter().map(i64::to_string).collect::<Vec<_>>().join(", ")
357            ),
358            _ => String::new(),
359        };
360        let eq =
361            |col: &str, v: Option<i64>| v.map(|v| format!(" AND {col} = {v}")).unwrap_or_default();
362        if self.reasoning == Reasoning::None {
363            let mut w = String::from("1");
364            w.push_str(&eq("x.s", s));
365            w.push_str(&eq("x.p", p));
366            w.push_str(&eq("x.o", o));
367            w.push_str(&gw("x"));
368            let d = if matches!(graphs, GraphFilter::Merge(_)) {
369                "DISTINCT "
370            } else {
371                ""
372            };
373            return format!(
374                "(SELECT {d}x.s AS s, x.p AS p, x.o AS o, {} AS g FROM {base} x WHERE {w})",
375                g("x")
376            );
377        }
378        let v = vocab();
379        let (same, inv, subj, obj) = self.kinds();
380        // One arm: `SELECT s AS s, p AS p, o AS o, g AS g FROM …` (compound SELECTs take their
381        // column names from the first arm, and derived tables cannot rename columns).
382        let row = |s: &str, p: &str, o: &str, gx: &str, rest: String| {
383            format!(
384                "SELECT {s} AS s, {p} AS p, {o} AS o, {} AS g FROM {rest}",
385                g(gx)
386            )
387        };
388        let ty = v.ty.to_string();
389        let type_arms = |s: Option<i64>, o: Option<i64>, asserted: bool| -> Vec<String> {
390            let mut a = Vec::new();
391            if asserted {
392                a.push(row(
393                    "x.s",
394                    &ty,
395                    "x.o",
396                    "x",
397                    format!(
398                        "{base} x WHERE x.p = {ty}{}{}{}",
399                        eq("x.s", s),
400                        eq("x.o", o),
401                        gw("x")
402                    ),
403                ));
404            }
405            // Superclasses of asserted types, then domains and ranges.
406            a.push(row("x.s", &ty, "c.sup", "x", format!(
407                "{base} x JOIN tbox_closure c ON c.kind = {} AND c.sub = x.o WHERE x.p = {ty}{}{}{}",
408                kind::CLASS, eq("x.s", s), eq("c.sup", o), gw("x")
409            )));
410            a.push(row(
411                "x.s",
412                &ty,
413                "c.sup",
414                "x",
415                format!(
416                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {subj}{}{}{}",
417                    eq("x.s", s),
418                    eq("c.sup", o),
419                    gw("x")
420                ),
421            ));
422            a.push(row(
423                "x.o",
424                &ty,
425                "c.sup",
426                "x",
427                format!(
428                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {obj} AND {}{}{}{}",
429                    non_literal("x.o"),
430                    eq("x.o", s),
431                    eq("c.sup", o),
432                    gw("x")
433                ),
434            ));
435            a
436        };
437        // Triples of property `pid` entailed without transitivity.
438        let prop_arms = |pid: i64, s: Option<i64>, o: Option<i64>| -> Vec<String> {
439            let pid_s = pid.to_string();
440            let mut a = vec![
441                row("x.s", &pid_s, "x.o", "x", format!("{base} x WHERE x.p = {pid}{}{}{}", eq("x.s", s), eq("x.o", o), gw("x"))),
442                row("x.s", &pid_s, "x.o", "x", format!(
443                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {same} AND c.sup = {pid}{}{}{}",
444                    eq("x.s", s), eq("x.o", o), gw("x")
445                )),
446            ];
447            if let Some(inv) = inv {
448                a.push(row("x.o", &pid_s, "x.s", "x", format!(
449                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {inv} AND c.sup = {pid} AND {}{}{}{}",
450                    non_literal("x.o"), eq("x.o", s), eq("x.s", o), gw("x")
451                )));
452            }
453            // The schema closure itself answers subClassOf / subPropertyOf patterns.
454            let schema_kind = if pid == v.sco {
455                Some(kind::CLASS)
456            } else if pid == v.spo {
457                Some(kind::PROPERTY)
458            } else {
459                None
460            };
461            if let Some(k) = schema_kind {
462                a.push(format!(
463                    "SELECT sub AS s, {pid} AS p, sup AS o, {DEFAULT_GRAPH_ID} AS g FROM tbox_closure WHERE kind = {k}{}{}",
464                    eq("sub", s),
465                    eq("sup", o)
466                ));
467            }
468            a
469        };
470        // A transitive property: the closure of its (otherwise) entailed triples, walked from a
471        // constant endpoint when there is one.
472        let transitive = |pid: i64, s: Option<i64>, o: Option<i64>| -> String {
473            let u = union_all(prop_arms(pid, None, None), self.max_compound);
474            let rec = match (s, o) {
475                (Some(s), _) => format!(
476                    "r(n, g) AS (SELECT o, g FROM u WHERE s = {s} UNION SELECT u.o, u.g FROM r JOIN u ON u.s = r.n AND u.g = r.g) \
477                     SELECT {s} AS s, {pid} AS p, n AS o, g FROM r{}",
478                    o.map(|o| format!(" WHERE n = {o}")).unwrap_or_default()
479                ),
480                (None, Some(o)) => format!(
481                    "r(n, g) AS (SELECT s, g FROM u WHERE o = {o} UNION SELECT u.s, u.g FROM r JOIN u ON u.o = r.n AND u.g = r.g) \
482                     SELECT n AS s, {pid} AS p, {o} AS o, g FROM r"
483                ),
484                (None, None) => format!(
485                    "r(s, o, g) AS (SELECT s, o, g FROM u UNION SELECT r.s, u.o, r.g FROM r JOIN u ON u.s = r.o AND u.g = r.g) \
486                     SELECT s, {pid} AS p, o, g FROM r"
487                ),
488            };
489            format!("SELECT * FROM (WITH RECURSIVE u(s, p, o, g) AS ({u}), {rec})")
490        };
491        let mut arms = Vec::new();
492        match p {
493            Some(pid) if pid == v.ty => arms.extend(type_arms(s, o, true)),
494            Some(pid) if self.reasoning == Reasoning::OwlQl && self.transitive.contains(&pid) => {
495                arms.push(transitive(pid, s, o));
496            }
497            Some(pid) => arms.extend(prop_arms(pid, s, o)),
498            None => {
499                // Every entailed triple: asserted, through property axioms, the schema closure,
500                // types, and transitive properties.
501                arms.push(row(
502                    "x.s",
503                    "x.p",
504                    "x.o",
505                    "x",
506                    format!(
507                        "{base} x WHERE 1{}{}{}",
508                        eq("x.s", s),
509                        eq("x.o", o),
510                        gw("x")
511                    ),
512                ));
513                arms.push(row(
514                    "x.s",
515                    "c.sup",
516                    "x.o",
517                    "x",
518                    format!(
519                        "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {same}{}{}{}",
520                        eq("x.s", s),
521                        eq("x.o", o),
522                        gw("x")
523                    ),
524                ));
525                if let Some(inv) = inv {
526                    arms.push(row("x.o", "c.sup", "x.s", "x", format!(
527                        "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {inv} AND {}{}{}{}",
528                        non_literal("x.o"), eq("x.o", s), eq("x.s", o), gw("x")
529                    )));
530                }
531                for (k, pid) in [(kind::CLASS, v.sco), (kind::PROPERTY, v.spo)] {
532                    arms.push(format!(
533                        "SELECT sub AS s, {pid} AS p, sup AS o, {DEFAULT_GRAPH_ID} AS g FROM tbox_closure WHERE kind = {k}{}{}",
534                        eq("sub", s),
535                        eq("sup", o)
536                    ));
537                }
538                arms.extend(type_arms(s, o, false));
539                if self.reasoning == Reasoning::OwlQl {
540                    for &pid in self.transitive {
541                        arms.push(transitive(pid, s, o));
542                    }
543                }
544            }
545        }
546        format!(
547            "(SELECT DISTINCT s, p, o, g FROM ({}))",
548            union_all(arms, self.max_compound)
549        )
550    }
551}
552
553/// Statements of one OWL 2 RL round: every rule inserts its new conclusions into
554/// `quads_inf` (graph 0), reading asserted and inferred triples of every graph.
555pub fn materialize_round() -> Vec<Statement> {
556    let v = vocab();
557    let a = "(SELECT s, p, o FROM quads UNION ALL SELECT s, p, o FROM quads_inf)";
558    let nl = |x: &str| non_literal(x);
559    let lists = format!(
560        "RECURSIVE l(head, node, item) AS (SELECT s, s, o FROM {a} WHERE p = {first} \
561           UNION SELECT l.head, r.o, f.o FROM l JOIN {a} r ON r.s = l.node AND r.p = {rest} JOIN {a} f ON f.s = r.o AND f.p = {first})",
562        first = v.first,
563        rest = v.rest
564    );
565    let rules: Vec<String> = vec![
566        // eq-sym, eq-trans
567        format!("SELECT o, {same}, s FROM {a} WHERE p = {same}", same = v.same),
568        format!("SELECT x.s, {same}, y.o FROM {a} x JOIN {a} y ON y.s = x.o AND y.p = {same} WHERE x.p = {same}", same = v.same),
569        // eq-rep-s, eq-rep-p, eq-rep-o
570        format!("SELECT e.o, t.p, t.o FROM {a} e JOIN {a} t ON t.s = e.s WHERE e.p = {same} AND {}", nl("e.o"), same = v.same),
571        format!("SELECT t.s, e.o, t.o FROM {a} e JOIN {a} t ON t.p = e.s WHERE e.p = {same} AND ((e.o) >> {PAYLOAD_BITS}) = 1", same = v.same),
572        format!("SELECT t.s, t.p, e.o FROM {a} e JOIN {a} t ON t.o = e.s WHERE e.p = {same}", same = v.same),
573        // prp-dom, prp-rng
574        format!("SELECT t.s, {ty}, d.o FROM {a} d JOIN {a} t ON t.p = d.s WHERE d.p = {dom}", ty = v.ty, dom = v.dom),
575        format!("SELECT t.o, {ty}, d.o FROM {a} d JOIN {a} t ON t.p = d.s WHERE d.p = {rng} AND {}", nl("t.o"), ty = v.ty, rng = v.rng),
576        // prp-fp, prp-ifp
577        format!(
578            "SELECT t1.o, {same}, t2.o FROM {a} f JOIN {a} t1 ON t1.p = f.s JOIN {a} t2 ON t2.p = f.s AND t2.s = t1.s \
579             WHERE f.p = {ty} AND f.o = {func} AND t1.o <> t2.o AND {} AND {}",
580            nl("t1.o"), nl("t2.o"), same = v.same, ty = v.ty, func = v.func
581        ),
582        format!(
583            "SELECT t1.s, {same}, t2.s FROM {a} f JOIN {a} t1 ON t1.p = f.s JOIN {a} t2 ON t2.p = f.s AND t2.o = t1.o \
584             WHERE f.p = {ty} AND f.o = {ifunc} AND t1.s <> t2.s",
585            same = v.same, ty = v.ty, ifunc = v.ifunc
586        ),
587        // prp-symp, prp-trp
588        format!("SELECT t.o, t.p, t.s FROM {a} f JOIN {a} t ON t.p = f.s WHERE f.p = {ty} AND f.o = {sym} AND {}", nl("t.o"), ty = v.ty, sym = v.sym),
589        format!(
590            "SELECT t1.s, t1.p, t2.o FROM {a} f JOIN {a} t1 ON t1.p = f.s JOIN {a} t2 ON t2.p = f.s AND t2.s = t1.o WHERE f.p = {ty} AND f.o = {trans}",
591            ty = v.ty, trans = v.trans
592        ),
593        // prp-spo1, prp-eqp1, prp-eqp2
594        format!("SELECT t.s, x.o, t.o FROM {a} x JOIN {a} t ON t.p = x.s WHERE x.p = {spo}", spo = v.spo),
595        format!("SELECT t.s, x.o, t.o FROM {a} x JOIN {a} t ON t.p = x.s WHERE x.p = {eqp}", eqp = v.eqp),
596        format!("SELECT t.s, x.s, t.o FROM {a} x JOIN {a} t ON t.p = x.o WHERE x.p = {eqp}", eqp = v.eqp),
597        // prp-inv1, prp-inv2
598        format!("SELECT t.o, x.o, t.s FROM {a} x JOIN {a} t ON t.p = x.s WHERE x.p = {inv} AND {}", nl("t.o"), inv = v.inv),
599        format!("SELECT t.o, x.s, t.s FROM {a} x JOIN {a} t ON t.p = x.o WHERE x.p = {inv} AND {}", nl("t.o"), inv = v.inv),
600        // cax-sco, cax-eqc1, cax-eqc2
601        format!("SELECT t.s, {ty}, x.o FROM {a} x JOIN {a} t ON t.p = {ty} AND t.o = x.s WHERE x.p = {sco}", ty = v.ty, sco = v.sco),
602        format!("SELECT t.s, {ty}, x.o FROM {a} x JOIN {a} t ON t.p = {ty} AND t.o = x.s WHERE x.p = {eqc}", ty = v.ty, eqc = v.eqc),
603        format!("SELECT t.s, {ty}, x.s FROM {a} x JOIN {a} t ON t.p = {ty} AND t.o = x.o WHERE x.p = {eqc}", ty = v.ty, eqc = v.eqc),
604        // scm-sco (transitive subclasses)
605        format!("SELECT x.s, {sco}, y.o FROM {a} x JOIN {a} y ON y.s = x.o AND y.p = {sco} WHERE x.p = {sco}", sco = v.sco),
606        // scm-eqc1 (the other scm-* rules only restate schema triples whose instance-level
607        // consequences the rules above already derive; `reasonable` omits them too)
608        format!("SELECT s, {sco}, o FROM {a} WHERE p = {eqc} UNION ALL SELECT o, {sco}, s FROM {a} WHERE p = {eqc}", sco = v.sco, eqc = v.eqc),
609        // Every subject is an owl:Thing; owl:Thing and owl:Nothing are classes (cls-thing, cls-nothing1)
610        format!("SELECT s, {ty}, {thing} FROM {a} WHERE {} UNION SELECT {thing}, {ty}, {class} UNION SELECT {nothing}, {ty}, {class}", nl("s"), ty = v.ty, thing = v.thing, class = owl("Class"), nothing = owl("Nothing")),
611        // cls-hv1, cls-hv2
612        format!(
613            "SELECT t.s, op.o, hv.o FROM {a} hv JOIN {a} op ON op.s = hv.s AND op.p = {onp} JOIN {a} t ON t.p = {ty} AND t.o = hv.s WHERE hv.p = {hv}",
614            onp = v.on_property, ty = v.ty, hv = v.has_value
615        ),
616        format!(
617            "SELECT t.s, {ty}, hv.s FROM {a} hv JOIN {a} op ON op.s = hv.s AND op.p = {onp} JOIN {a} t ON t.p = op.o AND t.o = hv.o WHERE hv.p = {hv}",
618            onp = v.on_property, ty = v.ty, hv = v.has_value
619        ),
620        // cls-svf1, cls-svf2
621        format!(
622            "SELECT t.s, {ty}, sv.s FROM {a} sv JOIN {a} op ON op.s = sv.s AND op.p = {onp} JOIN {a} t ON t.p = op.o \
623             JOIN {a} vt ON vt.s = t.o AND vt.p = {ty} AND vt.o = sv.o WHERE sv.p = {svf}",
624            onp = v.on_property, ty = v.ty, svf = v.some_values
625        ),
626        format!(
627            "SELECT t.s, {ty}, sv.s FROM {a} sv JOIN {a} op ON op.s = sv.s AND op.p = {onp} JOIN {a} t ON t.p = op.o WHERE sv.p = {svf} AND sv.o = {thing}",
628            onp = v.on_property, ty = v.ty, svf = v.some_values, thing = v.thing
629        ),
630        // cls-avf
631        format!(
632            "SELECT t.o, {ty}, av.o FROM {a} av JOIN {a} op ON op.s = av.s AND op.p = {onp} JOIN {a} xt ON xt.p = {ty} AND xt.o = av.s \
633             JOIN {a} t ON t.s = xt.s AND t.p = op.o WHERE av.p = {avf} AND {}",
634            nl("t.o"), onp = v.on_property, ty = v.ty, avf = v.all_values
635        ),
636        // cls-int1, cls-int2, cls-uni (list members through rdf:first / rdf:rest)
637        format!(
638            "WITH {lists}, m(c, item) AS (SELECT x.s, l.item FROM {a} x JOIN l ON l.head = x.o WHERE x.p = {int}) \
639             SELECT t.s, {ty}, m.c FROM m JOIN {a} t ON t.p = {ty} AND t.o = m.item GROUP BY m.c, t.s \
640             HAVING COUNT(DISTINCT m.item) = (SELECT COUNT(DISTINCT m2.item) FROM m m2 WHERE m2.c = m.c)",
641            ty = v.ty, int = v.intersection
642        ),
643        format!(
644            "WITH {lists} SELECT t.s, {ty}, l.item FROM {a} x JOIN l ON l.head = x.o JOIN {a} t ON t.p = {ty} AND t.o = x.s WHERE x.p = {int}",
645            ty = v.ty, int = v.intersection
646        ),
647        format!(
648            "WITH {lists} SELECT t.s, {ty}, x.s FROM {a} x JOIN l ON l.head = x.o JOIN {a} t ON t.p = {ty} AND t.o = l.item WHERE x.p = {uni}",
649            ty = v.ty, uni = v.union
650        ),
651        // prp-spo2 (property chains)
652        format!(
653            "WITH {lists}, \
654               ix(head, node, i) AS (SELECT s, s, 1 FROM {a} WHERE p = {first} UNION SELECT ix.head, r.o, ix.i + 1 FROM ix JOIN {a} r ON r.s = ix.node AND r.p = {rest} WHERE r.o <> {nil}), \
655               steps(chain, i, prop) AS (SELECT x.s, ix.i, f.o FROM {a} x JOIN ix ON ix.head = x.o JOIN {a} f ON f.s = ix.node AND f.p = {first} WHERE x.p = {chain}), \
656               w(chain, start, i, cur) AS (SELECT st.chain, t.s, 1, t.o FROM steps st JOIN {a} t ON t.p = st.prop WHERE st.i = 1 \
657                 UNION SELECT w.chain, w.start, w.i + 1, t.o FROM w JOIN steps st ON st.chain = w.chain AND st.i = w.i + 1 JOIN {a} t ON t.s = w.cur AND t.p = st.prop) \
658             SELECT w.start, w.chain, w.cur FROM w WHERE w.i = (SELECT MAX(i) FROM steps s2 WHERE s2.chain = w.chain)",
659            first = v.first, rest = v.rest, nil = v.nil, chain = v.chain
660        ),
661    ];
662    rules
663        .into_iter()
664        .map(|r| {
665            let (with, body) = match r.strip_prefix("WITH ") {
666                Some(rest) => split_with(rest),
667                None => (String::new(), r),
668            };
669            let body = name_columns(&body);
670            Statement::new(format!(
671                "{with}INSERT OR IGNORE INTO quads_inf(s, p, o, g) SELECT DISTINCT r.s, r.p, r.o, {DEFAULT_GRAPH_ID} FROM ({body}) AS r \
672                 WHERE {} AND NOT EXISTS (SELECT 1 FROM quads a WHERE a.s = r.s AND a.p = r.p AND a.o = r.o AND a.g = {DEFAULT_GRAPH_ID})",
673                non_literal("r.s")
674            ))
675        })
676        .collect()
677}
678
679/// Renames the three result columns of a rule's first SELECT to `s, p, o`.
680fn name_columns(select: &str) -> String {
681    let rest = select.strip_prefix("SELECT ").unwrap_or(select);
682    let from = top_level(rest, " FROM ").unwrap_or(rest.len());
683    let cols: Vec<&str> = split_top(&rest[..from], ',');
684    if cols.len() != 3 {
685        return select.to_string();
686    }
687    format!(
688        "SELECT {} AS s, {} AS p, {} AS o{}",
689        cols[0].trim(),
690        cols[1].trim(),
691        cols[2].trim(),
692        &rest[from..]
693    )
694}
695
696/// Byte offset of the first top-level (outside parentheses) occurrence of `pat`.
697fn top_level(s: &str, pat: &str) -> Option<usize> {
698    let mut depth = 0i32;
699    for (i, c) in s.char_indices() {
700        match c {
701            '(' => depth += 1,
702            ')' => depth -= 1,
703            _ if depth == 0 && s[i..].starts_with(pat) => return Some(i),
704            _ => {}
705        }
706    }
707    None
708}
709
710fn split_top(s: &str, sep: char) -> Vec<&str> {
711    let (mut depth, mut start, mut out) = (0i32, 0usize, Vec::new());
712    for (i, c) in s.char_indices() {
713        match c {
714            '(' => depth += 1,
715            ')' => depth -= 1,
716            c if c == sep && depth == 0 => {
717                out.push(&s[start..i]);
718                start = i + 1;
719            }
720            _ => {}
721        }
722    }
723    out.push(&s[start..]);
724    out
725}
726
727/// Splits `ctes SELECT …` (after `WITH `) into the `WITH … ` prefix and the final SELECT.
728fn split_with(rest: &str) -> (String, String) {
729    // The final SELECT is the last top-level "SELECT" (outside parentheses).
730    let bytes = rest.as_bytes();
731    let (mut depth, mut last) = (0i32, 0usize);
732    for (i, &c) in bytes.iter().enumerate() {
733        match c {
734            b'(' => depth += 1,
735            b')' => depth -= 1,
736            b'S' if depth == 0 && rest[i..].starts_with("SELECT ") => last = i,
737            _ => {}
738        }
739    }
740    (
741        format!("WITH {} ", rest[..last].trim_end()),
742        rest[last..].to_string(),
743    )
744}
745
746/// Statements run before materialization: previous inferences are discarded, and the
747/// vocabulary that rule conclusions use (`owl:sameAs`, `rdfs:subClassOf`, …) gets its term
748/// rows, since it may not appear in the data.
749pub fn materialize_reset(caps: &crate::sql::Capabilities) -> Vec<Statement> {
750    let mut rows = crate::encoding::EncodedRows::default();
751    for iri in [
752        rdf::TYPE.as_str(),
753        rdfs::SUB_CLASS_OF.as_str(),
754        rdfs::SUB_PROPERTY_OF.as_str(),
755        rdfs::DOMAIN.as_str(),
756        rdfs::RANGE.as_str(),
757    ] {
758        rows.iri(iri);
759    }
760    for local in [
761        "sameAs",
762        "equivalentClass",
763        "equivalentProperty",
764        "Thing",
765        "Nothing",
766        "Class",
767    ] {
768        rows.iri(&format!("{OWL}{local}"));
769    }
770    rows.dedup();
771    let mut out = vec![Statement::new("DELETE FROM quads_inf")];
772    out.extend(crate::writer::term_statements(&rows, caps));
773    out
774}