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? (A schema axiom, or anything in the
147/// registry graph, which scopes the closure.)
148pub fn is_schema_quad(q: QuadRef<'_>) -> bool {
149    crate::registry::is_registry_quad(q)
150        || is_schema_iri(q.predicate.as_str())
151        || (q.predicate == rdf::TYPE
152            && matches!(q.object, TermRef::NamedNode(n) if is_axiom_class(n.as_str())))
153}
154
155/// Can this update change the schema closure? (Conservative: variables count as schema.)
156pub fn update_touches_schema(update: &Update) -> bool {
157    crate::registry::update_touches_registry(update) || touches_axioms(update)
158}
159
160fn touches_axioms(update: &Update) -> bool {
161    let pattern = |p: &NamedNodePattern, o: &TermPattern| match p {
162        NamedNodePattern::Variable(_) => true,
163        NamedNodePattern::NamedNode(n) if is_schema_iri(n.as_str()) => true,
164        NamedNodePattern::NamedNode(n) if *n == rdf::TYPE => match o {
165            TermPattern::NamedNode(c) => is_axiom_class(c.as_str()),
166            TermPattern::Variable(_) => true,
167            _ => false,
168        },
169        NamedNodePattern::NamedNode(_) => false,
170    };
171    update.operations.iter().any(|op| match op {
172        GraphUpdateOperation::InsertData { data } => data.iter().any(|q| {
173            is_schema_iri(q.predicate.as_str())
174                || (q.predicate == rdf::TYPE && matches!(&q.object, Term::NamedNode(n) if is_axiom_class(n.as_str())))
175        }),
176        GraphUpdateOperation::DeleteData { data } => data.iter().any(|q| {
177            is_schema_iri(q.predicate.as_str())
178                || (q.predicate == rdf::TYPE
179                    && matches!(&q.object, spargebra::term::GroundTerm::NamedNode(n) if is_axiom_class(n.as_str())))
180        }),
181        GraphUpdateOperation::DeleteInsert { delete, insert, .. } => {
182            delete.iter().any(|q| {
183                let o: TermPattern = q.object.clone().into();
184                pattern(&q.predicate, &o)
185            }) || insert.iter().any(|q| pattern(&q.predicate, &q.object))
186        }
187        GraphUpdateOperation::Create { .. } => false,
188        GraphUpdateOperation::Load { .. }
189        | GraphUpdateOperation::Clear { .. }
190        | GraphUpdateOperation::Drop { .. } => true,
191    })
192}
193
194/// SQL: the id is an IRI, a blank node or a triple term (a valid subject).
195pub(crate) fn non_literal(x: &str) -> String {
196    format!("(({x}) >> {PAYLOAD_BITS}) IN (1, 2, 9)")
197}
198
199/// Statements recomputing `tbox_closure`, one closure per scope (see
200/// [`crate::registry::ontology_axioms`]): the scope of every graph, and one per graph that an
201/// active ontology is mapped to. Each statement reads the ontology axioms tagged with their
202/// scope; recursion only joins rows of the same scope.
203pub fn closure_statements() -> Vec<Statement> {
204    let v = vocab();
205    let ax = |cond: String| crate::registry::ontology_axioms(&cond);
206    let (c, p, s_, t) = (
207        kind::CLASS,
208        kind::PROPERTY,
209        kind::OWL_SAME,
210        kind::TRANSITIVE,
211    );
212    let class_edges = format!(
213        "SELECT scope AS k, s AS a, o AS b FROM {} UNION SELECT scope, o, s FROM {}",
214        ax(format!("q.p IN ({}, {})", v.sco, v.eqc)),
215        ax(format!("q.p = {}", v.eqc))
216    );
217    let prop_edges = format!(
218        "SELECT scope AS k, s AS a, o AS b FROM {} UNION SELECT scope, o, s FROM {}",
219        ax(format!("q.p IN ({}, {})", v.spo, v.eqp)),
220        ax(format!("q.p = {}", v.eqp))
221    );
222    let closure = |k: i64, edges: &str| {
223        Statement::new(format!(
224            "WITH RECURSIVE e(k, a, b) AS ({edges}), \
225             c(k, a, b) AS (SELECT k, a, b FROM e UNION SELECT c.k, c.a, e.b FROM c JOIN e ON e.k = c.k AND e.a = c.b) \
226             INSERT OR IGNORE INTO tbox_closure(kind, scope, sub, sup) SELECT {k}, k, a, b FROM c WHERE a <> b"
227        ))
228    };
229    // OWL: property edges with a direction bit (1 = inverse), composed modulo 2.
230    let owl = Statement::new(format!(
231        "WITH RECURSIVE e(k, a, b, d) AS (SELECT k, a, b, 0 FROM ({prop_edges}) \
232           UNION SELECT scope, s, o, 1 FROM {inv} UNION SELECT scope, o, s, 1 FROM {inv} \
233           UNION SELECT scope, s, s, 1 FROM {sym}), \
234         c(k, a, b, d) AS (SELECT k, a, b, d FROM e UNION SELECT c.k, c.a, e.b, (c.d + e.d) % 2 FROM c JOIN e ON e.k = c.k AND e.a = c.b) \
235         INSERT OR IGNORE INTO tbox_closure(kind, scope, sub, sup) SELECT {s_} + d, k, a, b FROM c WHERE d = 1 OR a <> b",
236        inv = ax(format!("q.p = {}", v.inv)),
237        sym = ax(format!("q.p = {} AND q.o = {}", v.ty, v.sym)),
238    ));
239    let dom_rng = || ax(format!("q.p IN ({}, {})", v.dom, v.rng));
240    // Classes a domain/range class is a subclass of (reflexive), per scope.
241    let classes = format!(
242        "SELECT scope AS k, o AS a, o AS b FROM {} UNION SELECT scope, sub, sup FROM tbox_closure WHERE kind = {c}",
243        dom_rng()
244    );
245    // Properties with (sub, sup) where sup is reflexive over properties having a domain/range.
246    let subs = |k: i64| {
247        format!(
248            "SELECT scope AS k, s AS a, s AS b FROM {} UNION SELECT scope, sub, sup FROM tbox_closure WHERE kind = {k}",
249            dom_rng()
250        )
251    };
252    let typed = |k: i64, props: &str, axiom: i64| {
253        format!(
254            "SELECT {k}, pq.k, pq.a, cd.b FROM ({props}) pq JOIN {} x ON x.s = pq.b AND x.scope = pq.k \
255             JOIN ({classes}) cd ON cd.a = x.o AND cd.k = pq.k",
256            ax(format!("q.p = {axiom}"))
257        )
258    };
259    let inverse_typed = |k: i64, axiom: i64| {
260        format!(
261            "SELECT {k}, pq.scope, pq.sub, cd.b FROM tbox_closure pq JOIN {} x ON x.s = pq.sup AND x.scope = pq.scope \
262             JOIN ({classes}) cd ON cd.a = x.o AND cd.k = pq.scope WHERE pq.kind = {inv}",
263            ax(format!("q.p = {axiom}")),
264            inv = kind::OWL_INVERSE
265        )
266    };
267    let insert = |sql: String| {
268        Statement::new(format!(
269            "INSERT OR IGNORE INTO tbox_closure(kind, scope, sub, sup) {sql}"
270        ))
271    };
272    vec![
273        Statement::new("DELETE FROM tbox_closure"),
274        closure(c, &class_edges),
275        closure(p, &prop_edges),
276        owl,
277        Statement::new(format!(
278            "INSERT OR IGNORE INTO tbox_closure(kind, scope, sub, sup) SELECT {t}, scope, s, s FROM {}",
279            ax(format!("q.p = {} AND q.o = {}", v.ty, v.trans))
280        )),
281        insert(typed(kind::SUBJECT_TYPE, &subs(p), v.dom)),
282        insert(typed(kind::OBJECT_TYPE, &subs(p), v.rng)),
283        insert(format!(
284            "{} UNION {}",
285            typed(kind::OWL_SUBJECT_TYPE, &subs(s_), v.dom),
286            inverse_typed(kind::OWL_SUBJECT_TYPE, v.rng)
287        )),
288        insert(format!(
289            "{} UNION {}",
290            typed(kind::OWL_OBJECT_TYPE, &subs(s_), v.rng),
291            inverse_typed(kind::OWL_OBJECT_TYPE, v.dom)
292        )),
293    ]
294}
295
296/// Loads the transitive properties (kept in memory with the planner statistics).
297pub fn transitive_statement(id_col: impl Fn(&str) -> String) -> Statement {
298    Statement::new(format!(
299        "SELECT DISTINCT {} FROM tbox_closure WHERE kind = {}",
300        id_col("sub"),
301        kind::TRANSITIVE
302    ))
303}
304
305/// Which graphs a reasoned pattern reads.
306#[derive(Debug, Clone)]
307pub enum GraphFilter {
308    /// Keep each quad's graph (the caller constrains `g`).
309    Keep,
310    /// The RDF merge of these graphs (`None`: every graph), exposed as graph 0.
311    Merge(Option<Vec<i64>>),
312}
313
314/// Builds derived tables of entailed triples.
315#[derive(Debug, Clone)]
316pub struct Entailment<'a> {
317    pub reasoning: Reasoning,
318    /// Also read materialized inferences (`quads_inf`).
319    pub inferred: bool,
320    /// Exclude every registered schema graph from the stored triples
321    /// (`QueryOptions::include_schema_graphs`).
322    pub hide_schema: bool,
323    pub transitive: &'a BTreeSet<i64>,
324    /// Graphs with a closure of their own (see `tbox_closure.scope`); every other graph uses
325    /// the closure of [`crate::registry::all_scope`].
326    pub scopes: &'a BTreeSet<i64>,
327    /// Maximum terms of a compound SELECT.
328    pub max_compound: usize,
329    /// Read the store as it was at this tick (see `version`), from the change log.
330    pub as_of: Option<i64>,
331}
332
333impl Entailment<'_> {
334    /// SQL: the closure scope of the quads whose graph column is `g`.
335    fn scope_of(&self, g: &str) -> String {
336        let all = crate::registry::all_scope();
337        if self.scopes.is_empty() {
338            return all.to_string();
339        }
340        let list = self
341            .scopes
342            .iter()
343            .map(i64::to_string)
344            .collect::<Vec<_>>()
345            .join(", ");
346        format!("(CASE WHEN {g} IN ({list}) THEN {g} ELSE {all} END)")
347    }
348
349    /// Is any rewriting needed?
350    pub fn active(&self) -> bool {
351        self.reasoning != Reasoning::None || self.inferred
352    }
353
354    /// The table of stored triples: asserted, plus materialized inferences on request, minus
355    /// the registered schema graphs when they are hidden.
356    ///
357    /// Every quad source of the compiler goes through this or [`Self::source`], so hiding is
358    /// applied once and covers patterns, paths, `OPTIONAL` and `GRAPH ?g` alike. Inferences
359    /// are conclusions rather than schema, so they are never hidden.
360    pub fn base(&self) -> String {
361        let asserted = match (self.as_of, self.hide_schema) {
362            (Some(t), true) => {
363                crate::registry::without_schema_graphs(&crate::version::as_of_sql(&t.to_string()))
364            }
365            (Some(t), false) => crate::version::as_of_sql(&t.to_string()),
366            (None, true) => crate::registry::quads_without_schema_graphs().to_owned(),
367            (None, false) => "quads".to_owned(),
368        };
369        if self.inferred {
370            format!(
371                "(SELECT s, p, o, g FROM {asserted} UNION ALL SELECT s, p, o, g FROM quads_inf)"
372            )
373        } else {
374            asserted.to_string()
375        }
376    }
377
378    fn kinds(&self) -> (i64, Option<i64>, i64, i64) {
379        match self.reasoning {
380            Reasoning::OwlQl => (
381                kind::OWL_SAME,
382                Some(kind::OWL_INVERSE),
383                kind::OWL_SUBJECT_TYPE,
384                kind::OWL_OBJECT_TYPE,
385            ),
386            _ => (kind::PROPERTY, None, kind::SUBJECT_TYPE, kind::OBJECT_TYPE),
387        }
388    }
389
390    /// A `(s, p, o, g)` derived table of the entailed triples matching the constants.
391    pub fn source(
392        &self,
393        s: Option<i64>,
394        p: Option<i64>,
395        o: Option<i64>,
396        graphs: &GraphFilter,
397    ) -> String {
398        let base = self.base();
399        let g = |x: &str| match graphs {
400            GraphFilter::Keep => format!("{x}.g"),
401            GraphFilter::Merge(_) => DEFAULT_GRAPH_ID.to_string(),
402        };
403        let gw = |x: &str| match graphs {
404            GraphFilter::Merge(Some(l)) => format!(
405                " AND {x}.g IN ({})",
406                l.iter().map(i64::to_string).collect::<Vec<_>>().join(", ")
407            ),
408            _ => String::new(),
409        };
410        let eq =
411            |col: &str, v: Option<i64>| v.map(|v| format!(" AND {col} = {v}")).unwrap_or_default();
412        if self.reasoning == Reasoning::None {
413            let mut w = String::from("1");
414            w.push_str(&eq("x.s", s));
415            w.push_str(&eq("x.p", p));
416            w.push_str(&eq("x.o", o));
417            w.push_str(&gw("x"));
418            let d = if matches!(graphs, GraphFilter::Merge(_)) {
419                "DISTINCT "
420            } else {
421                ""
422            };
423            return format!(
424                "(SELECT {d}x.s AS s, x.p AS p, x.o AS o, {} AS g FROM {base} x WHERE {w})",
425                g("x")
426            );
427        }
428        let v = vocab();
429        let (same, inv, subj, obj) = self.kinds();
430        // Each quad is entailed with the closure of its graph's scope.
431        let cs = format!(" AND c.scope = {}", self.scope_of("x.g"));
432        let cs = cs.as_str();
433        // One arm: `SELECT s AS s, p AS p, o AS o, g AS g FROM …` (compound SELECTs take their
434        // column names from the first arm, and derived tables cannot rename columns).
435        let row = |s: &str, p: &str, o: &str, gx: &str, rest: String| {
436            format!(
437                "SELECT {s} AS s, {p} AS p, {o} AS o, {} AS g FROM {rest}",
438                g(gx)
439            )
440        };
441        let ty = v.ty.to_string();
442        let type_arms = |s: Option<i64>, o: Option<i64>, asserted: bool| -> Vec<String> {
443            let mut a = Vec::new();
444            if asserted {
445                a.push(row(
446                    "x.s",
447                    &ty,
448                    "x.o",
449                    "x",
450                    format!(
451                        "{base} x WHERE x.p = {ty}{}{}{}",
452                        eq("x.s", s),
453                        eq("x.o", o),
454                        gw("x")
455                    ),
456                ));
457            }
458            // Superclasses of asserted types, then domains and ranges.
459            a.push(row("x.s", &ty, "c.sup", "x", format!(
460                "{base} x JOIN tbox_closure c ON c.kind = {} AND c.sub = x.o WHERE x.p = {ty}{cs}{}{}{}",
461                kind::CLASS, eq("x.s", s), eq("c.sup", o), gw("x")
462            )));
463            a.push(row(
464                "x.s",
465                &ty,
466                "c.sup",
467                "x",
468                format!(
469                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {subj}{cs}{}{}{}",
470                    eq("x.s", s),
471                    eq("c.sup", o),
472                    gw("x")
473                ),
474            ));
475            a.push(row(
476                "x.o",
477                &ty,
478                "c.sup",
479                "x",
480                format!(
481                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {obj}{cs} AND {}{}{}{}",
482                    non_literal("x.o"),
483                    eq("x.o", s),
484                    eq("c.sup", o),
485                    gw("x")
486                ),
487            ));
488            a
489        };
490        // Triples of property `pid` entailed without transitivity.
491        let prop_arms = |pid: i64, s: Option<i64>, o: Option<i64>| -> Vec<String> {
492            let pid_s = pid.to_string();
493            let mut a = vec![
494                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"))),
495                row("x.s", &pid_s, "x.o", "x", format!(
496                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {same} AND c.sup = {pid}{cs}{}{}{}",
497                    eq("x.s", s), eq("x.o", o), gw("x")
498                )),
499            ];
500            if let Some(inv) = inv {
501                a.push(row("x.o", &pid_s, "x.s", "x", format!(
502                    "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {inv} AND c.sup = {pid}{cs} AND {}{}{}{}",
503                    non_literal("x.o"), eq("x.o", s), eq("x.s", o), gw("x")
504                )));
505            }
506            // The schema closure itself answers subClassOf / subPropertyOf patterns.
507            let schema_kind = if pid == v.sco {
508                Some(kind::CLASS)
509            } else if pid == v.spo {
510                Some(kind::PROPERTY)
511            } else {
512                None
513            };
514            if let Some(k) = schema_kind {
515                a.push(format!(
516                    "SELECT sub AS s, {pid} AS p, sup AS o, {DEFAULT_GRAPH_ID} AS g FROM tbox_closure WHERE kind = {k}{}{}",
517                    eq("sub", s),
518                    eq("sup", o)
519                ));
520            }
521            a
522        };
523        // A transitive property: the closure of its (otherwise) entailed triples, walked from a
524        // constant endpoint when there is one.
525        // With graphs of their own scope, a property is transitive only in the graphs whose
526        // scope declares it so; elsewhere its triples are entailed as for any property.
527        let declared = |pid: i64, g: &str| {
528            format!(
529                "EXISTS (SELECT 1 FROM tbox_closure t WHERE t.kind = {} AND t.sub = {pid} AND t.scope = {})",
530                kind::TRANSITIVE,
531                self.scope_of(g)
532            )
533        };
534        let transitive = |pid: i64, s: Option<i64>, o: Option<i64>| -> Vec<String> {
535            let mut u = union_all(prop_arms(pid, None, None), self.max_compound);
536            let mut arms = Vec::new();
537            if !self.scopes.is_empty() {
538                u = format!(
539                    "SELECT z.s, z.p, z.o, z.g FROM ({u}) z WHERE {}",
540                    declared(pid, "z.g")
541                );
542                arms.push(format!(
543                    "SELECT z.s, z.p, z.o, z.g FROM ({}) z WHERE NOT {}",
544                    union_all(prop_arms(pid, s, o), self.max_compound),
545                    declared(pid, "z.g")
546                ));
547            }
548            let rec = match (s, o) {
549                (Some(s), _) => format!(
550                    "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) \
551                     SELECT {s} AS s, {pid} AS p, n AS o, g FROM r{}",
552                    o.map(|o| format!(" WHERE n = {o}")).unwrap_or_default()
553                ),
554                (None, Some(o)) => format!(
555                    "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) \
556                     SELECT n AS s, {pid} AS p, {o} AS o, g FROM r"
557                ),
558                (None, None) => format!(
559                    "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) \
560                     SELECT s, {pid} AS p, o, g FROM r"
561                ),
562            };
563            arms.push(format!(
564                "SELECT * FROM (WITH RECURSIVE u(s, p, o, g) AS ({u}), {rec})"
565            ));
566            arms
567        };
568        let mut arms = Vec::new();
569        match p {
570            Some(pid) if pid == v.ty => arms.extend(type_arms(s, o, true)),
571            Some(pid) if self.reasoning == Reasoning::OwlQl && self.transitive.contains(&pid) => {
572                arms.extend(transitive(pid, s, o));
573            }
574            Some(pid) => arms.extend(prop_arms(pid, s, o)),
575            None => {
576                // Every entailed triple: asserted, through property axioms, the schema closure,
577                // types, and transitive properties.
578                arms.push(row(
579                    "x.s",
580                    "x.p",
581                    "x.o",
582                    "x",
583                    format!(
584                        "{base} x WHERE 1{}{}{}",
585                        eq("x.s", s),
586                        eq("x.o", o),
587                        gw("x")
588                    ),
589                ));
590                arms.push(row(
591                    "x.s",
592                    "c.sup",
593                    "x.o",
594                    "x",
595                    format!(
596                        "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {same}{cs}{}{}{}",
597                        eq("x.s", s),
598                        eq("x.o", o),
599                        gw("x")
600                    ),
601                ));
602                if let Some(inv) = inv {
603                    arms.push(row("x.o", "c.sup", "x.s", "x", format!(
604                        "tbox_closure c JOIN {base} x ON x.p = c.sub WHERE c.kind = {inv}{cs} AND {}{}{}{}",
605                        non_literal("x.o"), eq("x.o", s), eq("x.s", o), gw("x")
606                    )));
607                }
608                for (k, pid) in [(kind::CLASS, v.sco), (kind::PROPERTY, v.spo)] {
609                    arms.push(format!(
610                        "SELECT sub AS s, {pid} AS p, sup AS o, {DEFAULT_GRAPH_ID} AS g FROM tbox_closure WHERE kind = {k}{}{}",
611                        eq("sub", s),
612                        eq("sup", o)
613                    ));
614                }
615                arms.extend(type_arms(s, o, false));
616                if self.reasoning == Reasoning::OwlQl {
617                    for &pid in self.transitive {
618                        arms.extend(transitive(pid, s, o));
619                    }
620                }
621            }
622        }
623        format!(
624            "(SELECT DISTINCT s, p, o, g FROM ({}))",
625            union_all(arms, self.max_compound)
626        )
627    }
628}
629
630/// Statements of one OWL 2 RL round: every rule inserts its new conclusions into
631/// `quads_inf` (graph 0), reading asserted and inferred triples of every graph.
632pub fn materialize_round() -> Vec<Statement> {
633    let v = vocab();
634    let a = "(SELECT s, p, o FROM quads UNION ALL SELECT s, p, o FROM quads_inf)";
635    let nl = |x: &str| non_literal(x);
636    let lists = format!(
637        "RECURSIVE l(head, node, item) AS (SELECT s, s, o FROM {a} WHERE p = {first} \
638           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})",
639        first = v.first,
640        rest = v.rest
641    );
642    let rules: Vec<String> = vec![
643        // eq-sym, eq-trans
644        format!("SELECT o, {same}, s FROM {a} WHERE p = {same}", same = v.same),
645        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),
646        // eq-rep-s, eq-rep-p, eq-rep-o
647        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),
648        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),
649        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),
650        // prp-dom, prp-rng
651        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),
652        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),
653        // prp-fp, prp-ifp
654        format!(
655            "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 \
656             WHERE f.p = {ty} AND f.o = {func} AND t1.o <> t2.o AND {} AND {}",
657            nl("t1.o"), nl("t2.o"), same = v.same, ty = v.ty, func = v.func
658        ),
659        format!(
660            "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 \
661             WHERE f.p = {ty} AND f.o = {ifunc} AND t1.s <> t2.s",
662            same = v.same, ty = v.ty, ifunc = v.ifunc
663        ),
664        // prp-symp, prp-trp
665        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),
666        format!(
667            "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}",
668            ty = v.ty, trans = v.trans
669        ),
670        // prp-spo1, prp-eqp1, prp-eqp2
671        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),
672        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),
673        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),
674        // prp-inv1, prp-inv2
675        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),
676        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),
677        // cax-sco, cax-eqc1, cax-eqc2
678        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),
679        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),
680        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),
681        // scm-sco (transitive subclasses)
682        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),
683        // scm-eqc1 (the other scm-* rules only restate schema triples whose instance-level
684        // consequences the rules above already derive; `reasonable` omits them too)
685        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),
686        // Every subject is an owl:Thing; owl:Thing and owl:Nothing are classes (cls-thing, cls-nothing1)
687        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")),
688        // cls-hv1, cls-hv2
689        format!(
690            "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}",
691            onp = v.on_property, ty = v.ty, hv = v.has_value
692        ),
693        format!(
694            "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}",
695            onp = v.on_property, ty = v.ty, hv = v.has_value
696        ),
697        // cls-svf1, cls-svf2
698        format!(
699            "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 \
700             JOIN {a} vt ON vt.s = t.o AND vt.p = {ty} AND vt.o = sv.o WHERE sv.p = {svf}",
701            onp = v.on_property, ty = v.ty, svf = v.some_values
702        ),
703        format!(
704            "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}",
705            onp = v.on_property, ty = v.ty, svf = v.some_values, thing = v.thing
706        ),
707        // cls-avf
708        format!(
709            "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 \
710             JOIN {a} t ON t.s = xt.s AND t.p = op.o WHERE av.p = {avf} AND {}",
711            nl("t.o"), onp = v.on_property, ty = v.ty, avf = v.all_values
712        ),
713        // cls-int1, cls-int2, cls-uni (list members through rdf:first / rdf:rest)
714        format!(
715            "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}) \
716             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 \
717             HAVING COUNT(DISTINCT m.item) = (SELECT COUNT(DISTINCT m2.item) FROM m m2 WHERE m2.c = m.c)",
718            ty = v.ty, int = v.intersection
719        ),
720        format!(
721            "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}",
722            ty = v.ty, int = v.intersection
723        ),
724        format!(
725            "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}",
726            ty = v.ty, uni = v.union
727        ),
728        // prp-spo2 (property chains)
729        format!(
730            "WITH {lists}, \
731               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}), \
732               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}), \
733               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 \
734                 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) \
735             SELECT w.start, w.chain, w.cur FROM w WHERE w.i = (SELECT MAX(i) FROM steps s2 WHERE s2.chain = w.chain)",
736            first = v.first, rest = v.rest, nil = v.nil, chain = v.chain
737        ),
738    ];
739    let mut statements: Vec<Statement> = rules
740        .into_iter()
741        .map(|r| {
742            let (with, body) = match r.strip_prefix("WITH ") {
743                Some(rest) => split_with(rest),
744                None => (String::new(), r),
745            };
746            let body = name_columns(&body);
747            Statement::new(format!(
748                "{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 \
749                 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})",
750                non_literal("r.s")
751            ))
752        })
753        .collect();
754    statements.push(inference_attribute(OWL_PRODUCER));
755    statements
756}
757
758/// Renames the three result columns of a rule's first SELECT to `s, p, o`.
759fn name_columns(select: &str) -> String {
760    let rest = select.strip_prefix("SELECT ").unwrap_or(select);
761    let from = top_level(rest, " FROM ").unwrap_or(rest.len());
762    let cols: Vec<&str> = split_top(&rest[..from], ',');
763    if cols.len() != 3 {
764        return select.to_string();
765    }
766    format!(
767        "SELECT {} AS s, {} AS p, {} AS o{}",
768        cols[0].trim(),
769        cols[1].trim(),
770        cols[2].trim(),
771        &rest[from..]
772    )
773}
774
775/// Byte offset of the first top-level (outside parentheses) occurrence of `pat`.
776fn top_level(s: &str, pat: &str) -> Option<usize> {
777    let mut depth = 0i32;
778    for (i, c) in s.char_indices() {
779        match c {
780            '(' => depth += 1,
781            ')' => depth -= 1,
782            _ if depth == 0 && s[i..].starts_with(pat) => return Some(i),
783            _ => {}
784        }
785    }
786    None
787}
788
789fn split_top(s: &str, sep: char) -> Vec<&str> {
790    let (mut depth, mut start, mut out) = (0i32, 0usize, Vec::new());
791    for (i, c) in s.char_indices() {
792        match c {
793            '(' => depth += 1,
794            ')' => depth -= 1,
795            c if c == sep && depth == 0 => {
796                out.push(&s[start..i]);
797                start = i + 1;
798            }
799            _ => {}
800        }
801    }
802    out.push(&s[start..]);
803    out
804}
805
806/// Splits `ctes SELECT …` (after `WITH `) into the `WITH … ` prefix and the final SELECT.
807fn split_with(rest: &str) -> (String, String) {
808    // The final SELECT is the last top-level "SELECT" (outside parentheses).
809    let bytes = rest.as_bytes();
810    let (mut depth, mut last) = (0i32, 0usize);
811    for (i, &c) in bytes.iter().enumerate() {
812        match c {
813            b'(' => depth += 1,
814            b')' => depth -= 1,
815            b'S' if depth == 0 && rest[i..].starts_with("SELECT ") => last = i,
816            _ => {}
817        }
818    }
819    (
820        format!("WITH {} ", rest[..last].trim_end()),
821        rest[last..].to_string(),
822    )
823}
824
825/// The producer id of OWL 2 RL materialization (SQL rules and `reasonable` alike).
826pub const OWL_PRODUCER: &str = "owl2rl";
827
828/// The id a producer name is stored under in `quads_inf_src` and `inf_producers`.
829pub fn producer_id(name: &str) -> i64 {
830    // A positive 62-bit hash: stable across runs and backends, computed without a lookup.
831    (xxhash_rust::xxh3::xxh3_64(name.as_bytes()) >> 2) as i64
832}
833
834/// Discards one producer's inferences: its attributions go, and so does every inferred quad no
835/// other producer derived. The producer is (re)registered under its name.
836pub fn inference_reset(name: &str) -> Vec<Statement> {
837    let id = producer_id(name);
838    vec![
839        Statement::new(format!(
840            "INSERT OR REPLACE INTO inf_producers(id, name) VALUES ({id}, '{}')",
841            name.replace('\'', "''")
842        )),
843        Statement::new(format!("DELETE FROM quads_inf_src WHERE src = {id}")),
844        Statement::new(
845            "DELETE FROM quads_inf WHERE NOT EXISTS (SELECT 1 FROM quads_inf_src q \
846             WHERE q.s = quads_inf.s AND q.p = quads_inf.p AND q.o = quads_inf.o AND q.g = quads_inf.g)",
847        ),
848    ]
849}
850
851/// Attributes every inferred quad no producer claims yet to `name`. Run after a producer
852/// writes, so what it derived (and nobody had derived before) is recorded as its own.
853pub fn inference_attribute(name: &str) -> Statement {
854    Statement::new(format!(
855        "INSERT OR IGNORE INTO quads_inf_src(src, s, p, o, g) SELECT {}, i.s, i.p, i.o, i.g FROM quads_inf i \
856         WHERE NOT EXISTS (SELECT 1 FROM quads_inf_src q WHERE q.s = i.s AND q.p = i.p AND q.o = i.o AND q.g = i.g)",
857        producer_id(name)
858    ))
859}
860
861/// Statements run before OWL 2 RL materialization (see [`materialize_reset_for`]).
862pub fn materialize_reset(caps: &crate::sql::Capabilities) -> Vec<Statement> {
863    materialize_reset_for(caps, OWL_PRODUCER)
864}
865
866/// Statements run before a producer materializes: its previous inferences are discarded, and
867/// the vocabulary that rule conclusions use (`owl:sameAs`, `rdfs:subClassOf`, …) gets its term
868/// rows, since it may not appear in the data.
869pub fn materialize_reset_for(caps: &crate::sql::Capabilities, producer: &str) -> Vec<Statement> {
870    let mut rows = crate::encoding::EncodedRows::default();
871    for iri in [
872        rdf::TYPE.as_str(),
873        rdfs::SUB_CLASS_OF.as_str(),
874        rdfs::SUB_PROPERTY_OF.as_str(),
875        rdfs::DOMAIN.as_str(),
876        rdfs::RANGE.as_str(),
877    ] {
878        rows.iri(iri);
879    }
880    for local in [
881        "sameAs",
882        "equivalentClass",
883        "equivalentProperty",
884        "Thing",
885        "Nothing",
886        "Class",
887    ] {
888        rows.iri(&format!("{OWL}{local}"));
889    }
890    rows.dedup();
891    let mut out = inference_reset(producer);
892    out.extend(crate::writer::term_statements(&rows, caps));
893    out
894}