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()
218            .into_iter()
219            .find(|d| crate::redo::holds_index_pair(d, label, property))
220    }
221
222    pub fn named_constraints(&self) -> Vec<ConstraintDef> {
223        let committed = self
224            .schema
225            .map(|s| s.constraints.clone())
226            .unwrap_or_else(|| self.base.named_constraints());
227        self.fold_named_constraints(committed)
228    }
229
230    /// The constraint fold of [`Self::named_constraints`], over an
231    /// already-captured committed set — the piece [`Self::index_facts`]
232    /// reuses so its one capture and the single reader agree.
233    fn fold_named_constraints(&self, committed: Vec<ConstraintDef>) -> Vec<ConstraintDef> {
234        self.named_defs(committed, |map, op| {
235            if let Some(def) = op.constraint_def() {
236                map.insert(def.name.clone(), def);
237            } else if let RedoOp::DropConstraint { name } = op {
238                map.remove(name);
239            }
240        })
241    }
242
243    /// The named constraints with each row's enforced label resolved (see
244    /// [`resolve_enforced_labels`]): the one effective-identity view every
245    /// schema comparison reads (ADR-0450's legacy policy). Enforcement is
246    /// separate: `validate_slice` resolves the label from the theater alone,
247    /// the legacy-unenforced signal.
248    pub(crate) fn effective_constraints(&self) -> Result<Vec<ConstraintDef>> {
249        Ok(self.effective_constraints_in(&self.show_schema()?))
250    }
251
252    /// The same effective-identity view over an already-taken snapshot, for
253    /// a gate that reads several views of one catalog state (the
254    /// `CREATE CONSTRAINT` conflict gate) and must not take a second
255    /// snapshot between them.
256    pub(crate) fn effective_constraints_in(&self, show: &ShowSchema) -> Vec<ConstraintDef> {
257        resolve_enforced_labels(self.named_constraints(), &show.data.derived_constraints)
258    }
259
260    /// Index DDL: create a standalone index, counted in
261    /// `QueryStats::indexes_added` (ADR-0309).
262    pub fn create_named_index(&self, name: String, label: String, property: String) -> Result<()> {
263        self.push_schema_redo(
264            RedoOp::CreateIndex {
265                name,
266                label,
267                property,
268            },
269            |stats| stats.indexes_added += 1,
270        )
271    }
272
273    /// Create the range index backing an index-backed constraint. It is
274    /// part of that constraint, so it is not counted as an index (ADR-0309).
275    pub(crate) fn create_backing_index(
276        &self,
277        name: String,
278        label: String,
279        property: String,
280    ) -> Result<()> {
281        self.push_schema_redo(
282            RedoOp::CreateIndex {
283                name,
284                label,
285                property,
286            },
287            |_| {},
288        )
289    }
290
291    pub(crate) fn push_catalog_redo(&self, op: RedoOp) {
292        self.scratch_mut().push_redo(op);
293    }
294
295    /// Index DDL: drop a standalone index, counted in
296    /// `QueryStats::indexes_removed` (ADR-0309).
297    pub fn drop_named_index(&self, name: String) -> Result<()> {
298        self.push_schema_redo(RedoOp::DropIndex { name }, |stats| {
299            stats.indexes_removed += 1
300        })
301    }
302
303    /// Drop the backing index of a constraint being dropped; not counted as
304    /// an index (ADR-0309).
305    pub(crate) fn drop_backing_index(&self, name: String) -> Result<()> {
306        self.push_schema_redo(RedoOp::DropIndex { name }, |_| {})
307    }
308
309    pub fn create_named_constraint(&self, def: ConstraintDef) -> Result<()> {
310        self.push_schema_redo(RedoOp::create_constraint(def), |stats| {
311            stats.constraints_added += 1
312        })
313    }
314
315    pub fn drop_named_constraint(&self, name: String) -> Result<()> {
316        self.push_schema_redo(RedoOp::DropConstraint { name }, |stats| {
317            stats.constraints_removed += 1
318        })
319    }
320
321    /// Append one schema op and count it where it is recorded, next to the
322    /// mutation (the `writes.rs` accounting rule, ADR-0309).
323    fn push_schema_redo(&self, op: RedoOp, count: impl FnOnce(&mut QueryStats)) -> Result<()> {
324        let mut scratch = self.scratch_mut();
325        count(&mut scratch.statement.stats);
326        scratch.push_redo(op);
327        Ok(())
328    }
329}
330
331/// Fill each row's missing enforced label from the theater's
332/// derived-constraint index — its historical source — through
333/// [`crate::graph::resolve_enforced_label`], ADR-0450's one
334/// legacy-resolution rule, mapped over the set.
335fn resolve_enforced_labels(
336    constraints: Vec<ConstraintDef>,
337    derived: &BTreeMap<String, relate_model::Constraint>,
338) -> Vec<ConstraintDef> {
339    constraints
340        .into_iter()
341        .map(|mut def| {
342            let twin_label = derived
343                .get(&def.name)
344                .and_then(|constraint| constraint.enforced_label.as_deref());
345            crate::graph::resolve_enforced_label(&mut def, twin_label);
346            def
347        })
348        .collect()
349}