Skip to main content

relate_executor/overlay/
catalog.rs

1//! Catalog views of the overlay: the committed (or admitted) catalog with
2//! the scratch's catalog ops replayed over it (ADR-0172 §8), and the named
3//! index / constraint DDL that appends those ops.
4
5use std::collections::BTreeMap;
6
7use relate_catalog::{ConstraintDef, IndexDef};
8use relate_core::Result;
9
10use crate::graph::{QueryStats, ShowSchema};
11use crate::redo::{CatalogName, IndexFacts, RedoOp};
12
13use super::{ExecGraph, WriteScratch};
14
15/// A catalog definition keyed by its name, for the overlay fold
16/// [`ExecGraph::named_defs`] shares.
17trait NamedDef {
18    fn def_name(&self) -> &str;
19}
20
21impl NamedDef for IndexDef {
22    fn def_name(&self) -> &str {
23        &self.name
24    }
25}
26
27impl NamedDef for ConstraintDef {
28    fn def_name(&self) -> &str {
29        &self.name
30    }
31}
32
33/// The catalog facts of a view (ADR-0363 decision 5): the committed catalog
34/// or interner plus the names the view's write overlay named. The overlay's
35/// redo log is its write record — no second name set — read through
36/// [`RedoOp::catalog_names`], so a label, type or key a transaction just
37/// wrote is known before the commit publishes it.
38impl ExecGraph<'_> {
39    /// Whether this view's catalog knows `label`: the committed catalog or a
40    /// label any scratch write named. The committed contract is monotone (a
41    /// label outlives its last node); the scratch side keeps it: a create or
42    /// label change counts even if a later write removed it.
43    pub fn has_label(&self, label: &str) -> bool {
44        self.base.has_label(label) || self.scratch_wrote(|scratch| scratch.has_written_label(label))
45    }
46
47    /// Whether this view's catalog knows relationship type `rel_type`; the
48    /// label contract applies unchanged.
49    pub fn has_rel_type(&self, rel_type: &str) -> bool {
50        self.base.has_rel_type(rel_type)
51            || self.scratch_wrote(|scratch| scratch.has_written_rel_type(rel_type))
52    }
53
54    /// Whether this view's interner knows property key `key`: the committed
55    /// interner or a property key any scratch write named. A hit still only
56    /// suppresses a warning; a miss is a true miss.
57    pub fn has_property_key(&self, key: &str) -> bool {
58        self.base.has_property_key(key)
59            || self.scratch_wrote(|scratch| scratch.has_written_property_key(key))
60    }
61
62    /// Run a catalog question against the write overlay when the view has
63    /// one; a read view answers from the committed facts alone.
64    fn scratch_wrote(&self, question: impl Fn(&WriteScratch) -> bool) -> bool {
65        self.scratch
66            .is_some_and(|scratch| question(&scratch.borrow()))
67    }
68}
69
70/// The write overlay's catalog facts, read through
71/// [`RedoOp::catalog_names`] — the one total derivation of the names an op
72/// mentions — over the redo log, the one record every scratch write funnels
73/// through. The redo keeps a name after a later op removes it, matching the
74/// committed catalog's monotone contract.
75impl WriteScratch {
76    fn mentions(&self, wanted: CatalogName<'_>) -> bool {
77        self.redo.mentions(wanted)
78    }
79
80    fn has_written_label(&self, label: &str) -> bool {
81        self.mentions(CatalogName::Label(label))
82    }
83
84    fn has_written_rel_type(&self, rel_type: &str) -> bool {
85        self.mentions(CatalogName::RelType(rel_type))
86    }
87
88    fn has_written_property_key(&self, key: &str) -> bool {
89        self.mentions(CatalogName::PropertyKey(key))
90    }
91}
92
93impl<'a> ExecGraph<'a> {
94    /// The typed facts of every named index, resolved through the one
95    /// [`IndexFacts`] precedence (detail, then backing constraint, then
96    /// the legacy encoding) in the catalog's name order — the snapshot a
97    /// statement-scoped index reader (the 03N95 dynamic-property
98    /// detector) reads instead of re-spelling the chain over raw
99    /// [`IndexDef`] rows.
100    pub fn index_facts(&self) -> Result<Vec<IndexFacts>> {
101        // One admission boundary for the three catalog views (the pinned
102        // snapshot the view carries, else the base's single capture): the
103        // per-kind scratch folds and the show overlay replay over this one
104        // capture, where three separate reader calls could tear.
105        let (indexes, constraints, mut show) = match self.schema {
106            Some(schema) => (
107                schema.indexes.clone(),
108                schema.constraints.clone(),
109                schema.show.clone(),
110            ),
111            None => {
112                let snapshot = self.base.schema_snapshot();
113                (snapshot.indexes, snapshot.constraints, snapshot.show)
114            }
115        };
116        let indexes = self.fold_named_indexes(indexes);
117        let constraints = self.fold_named_constraints(constraints);
118        if let Some(scratch) = self.scratch {
119            crate::graph::apply_show_overlay(&mut show, scratch.borrow().redo.catalog_ops())?;
120        }
121        let details = &show.data.index_details;
122        Ok(crate::redo::resolve_index_facts(
123            &indexes,
124            details,
125            &constraints,
126        ))
127    }
128
129    pub(crate) fn show_schema(&self) -> Result<ShowSchema> {
130        // A view carrying an admitted `SchemaSnapshot` reads that pinned
131        // theater. Schema-less views (`read`/`read_at`/`write`) fall back to
132        // the live committed theater under its lock; those constructors are
133        // documented as test/diagnostic or non-SHOW callers, and the
134        // autocommit write path reaches `validate_constraints` while holding
135        // the publication read guard, so the fallback cannot observe a torn
136        // theater. Statement execution that must be admitted uses the
137        // `_with_schema` constructors.
138        let mut show = self
139            .schema
140            .map(|schema| schema.show.clone())
141            .unwrap_or_else(|| self.base.capture_show_schema());
142        if let Some(scratch) = self.scratch {
143            crate::graph::apply_show_overlay(&mut show, scratch.borrow().redo.catalog_ops())?;
144        }
145        Ok(show)
146    }
147
148    /// The overlay fold [`Self::named_indexes`] and [`Self::named_constraints`]
149    /// share (ADR-0172 §8): the committed (or admitted) definitions keyed by
150    /// name, with the scratch's catalog ops replayed over them — `apply`
151    /// upserts on a create and removes on a drop.
152    fn named_defs<D: NamedDef>(
153        &self,
154        committed: Vec<D>,
155        apply: impl Fn(&mut BTreeMap<String, D>, &RedoOp),
156    ) -> Vec<D> {
157        let mut map: BTreeMap<String, D> = committed
158            .into_iter()
159            .map(|d| (d.def_name().to_string(), d))
160            .collect();
161        if let Some(cell) = self.scratch {
162            for op in cell.borrow().redo.catalog_ops() {
163                apply(&mut map, op);
164            }
165        }
166        map.into_values().collect()
167    }
168
169    pub fn named_indexes(&self) -> Vec<IndexDef> {
170        let committed = self
171            .schema
172            .map(|s| s.indexes.clone())
173            .unwrap_or_else(|| self.base.named_indexes());
174        self.fold_named_indexes(committed)
175    }
176
177    /// The index fold of [`Self::named_indexes`], over an already-captured
178    /// committed set — the piece [`Self::index_facts`] reuses so its one
179    /// capture and the single reader agree.
180    fn fold_named_indexes(&self, committed: Vec<IndexDef>) -> Vec<IndexDef> {
181        self.named_defs(committed, |map, op| match op {
182            RedoOp::CreateIndex {
183                name,
184                label,
185                property,
186            } => {
187                map.insert(
188                    name.clone(),
189                    IndexDef {
190                        name: name.clone(),
191                        label: label.clone(),
192                        property: property.clone(),
193                    },
194                );
195            }
196            RedoOp::DropIndex { name } => {
197                map.remove(name);
198            }
199            _ => {}
200        })
201    }
202
203    pub fn named_index(&self, name: &str) -> Option<IndexDef> {
204        self.named_indexes().into_iter().find(|d| d.name == name)
205    }
206
207    /// The named constraint of that name — the [`ExecGraph::named_index`]
208    /// twin, so a by-name existence probe reads one accessor instead of
209    /// materializing the whole list and scanning it at each site.
210    pub fn named_constraint(&self, name: &str) -> Option<ConstraintDef> {
211        self.named_constraints()
212            .into_iter()
213            .find(|def| def.name == name)
214    }
215
216    pub fn named_index_by_schema(&self, label: &str, property: &str) -> Option<IndexDef> {
217        self.named_indexes().into_iter().find(|d| {
218            d.label == label
219                && crate::redo::split_legacy_property_encoding(&d.property).0 == property
220        })
221    }
222
223    pub fn named_constraints(&self) -> Vec<ConstraintDef> {
224        let committed = self
225            .schema
226            .map(|s| s.constraints.clone())
227            .unwrap_or_else(|| self.base.named_constraints());
228        self.fold_named_constraints(committed)
229    }
230
231    /// The constraint fold of [`Self::named_constraints`], over an
232    /// already-captured committed set — the piece [`Self::index_facts`]
233    /// reuses so its one capture and the single reader agree.
234    fn fold_named_constraints(&self, committed: Vec<ConstraintDef>) -> Vec<ConstraintDef> {
235        self.named_defs(committed, |map, op| {
236            if let Some(def) = op.constraint_def() {
237                map.insert(def.name.clone(), def);
238            } else if let RedoOp::DropConstraint { name } = op {
239                map.remove(name);
240            }
241        })
242    }
243
244    /// The named constraints with each row's enforced label resolved (see
245    /// [`resolve_enforced_labels`]): the one effective-identity view every
246    /// schema comparison reads (ADR-0450's legacy policy). Enforcement is
247    /// separate: `validate_slice` resolves the label from the theater alone,
248    /// the legacy-unenforced signal.
249    pub(crate) fn effective_constraints(&self) -> Result<Vec<ConstraintDef>> {
250        Ok(self.effective_constraints_in(&self.show_schema()?))
251    }
252
253    /// The same effective-identity view over an already-taken snapshot, for
254    /// a gate that reads several views of one catalog state (the
255    /// `CREATE CONSTRAINT` conflict gate) and must not take a second
256    /// snapshot between them.
257    pub(crate) fn effective_constraints_in(&self, show: &ShowSchema) -> Vec<ConstraintDef> {
258        resolve_enforced_labels(self.named_constraints(), &show.data.derived_constraints)
259    }
260
261    /// Index DDL: create a standalone index, counted in
262    /// `QueryStats::indexes_added` (ADR-0309).
263    pub fn create_named_index(&self, name: String, label: String, property: String) -> Result<()> {
264        self.push_schema_redo(
265            RedoOp::CreateIndex {
266                name,
267                label,
268                property,
269            },
270            |stats| stats.indexes_added += 1,
271        )
272    }
273
274    /// Create the range index backing an index-backed constraint. It is
275    /// part of that constraint, so it is not counted as an index (ADR-0309).
276    pub(crate) fn create_backing_index(
277        &self,
278        name: String,
279        label: String,
280        property: String,
281    ) -> Result<()> {
282        self.push_schema_redo(
283            RedoOp::CreateIndex {
284                name,
285                label,
286                property,
287            },
288            |_| {},
289        )
290    }
291
292    pub(crate) fn push_catalog_redo(&self, op: RedoOp) {
293        self.scratch_mut().push_redo(op);
294    }
295
296    /// Index DDL: drop a standalone index, counted in
297    /// `QueryStats::indexes_removed` (ADR-0309).
298    pub fn drop_named_index(&self, name: String) -> Result<()> {
299        self.push_schema_redo(RedoOp::DropIndex { name }, |stats| {
300            stats.indexes_removed += 1
301        })
302    }
303
304    /// Drop the backing index of a constraint being dropped; not counted as
305    /// an index (ADR-0309).
306    pub(crate) fn drop_backing_index(&self, name: String) -> Result<()> {
307        self.push_schema_redo(RedoOp::DropIndex { name }, |_| {})
308    }
309
310    pub fn create_named_constraint(&self, def: ConstraintDef) -> Result<()> {
311        self.push_schema_redo(RedoOp::create_constraint(def), |stats| {
312            stats.constraints_added += 1
313        })
314    }
315
316    pub fn drop_named_constraint(&self, name: String) -> Result<()> {
317        self.push_schema_redo(RedoOp::DropConstraint { name }, |stats| {
318            stats.constraints_removed += 1
319        })
320    }
321
322    /// Append one schema op and count it where it is recorded, next to the
323    /// mutation (the `writes.rs` accounting rule, ADR-0309).
324    fn push_schema_redo(&self, op: RedoOp, count: impl FnOnce(&mut QueryStats)) -> Result<()> {
325        let mut scratch = self.scratch_mut();
326        count(&mut scratch.statement.stats);
327        scratch.push_redo(op);
328        Ok(())
329    }
330}
331
332/// Fill each row's missing enforced label from the theater's
333/// derived-constraint index — its historical source. ADR-0450's one
334/// legacy-resolution rule: a row that already carries the label keeps it,
335/// and a field-less legacy row resolves to the same identity its
336/// current-shape twin would have. New rows never change here.
337fn resolve_enforced_labels(
338    constraints: Vec<ConstraintDef>,
339    derived: &BTreeMap<String, relate_model::Constraint>,
340) -> Vec<ConstraintDef> {
341    constraints
342        .into_iter()
343        .map(|mut def| {
344            if def.enforced_label.is_none() {
345                def.enforced_label = derived
346                    .get(&def.name)
347                    .and_then(|constraint| constraint.enforced_label.clone());
348            }
349            def
350        })
351        .collect()
352}