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