1use std::collections::BTreeMap;
5use std::sync::Mutex;
6
7use relate_catalog::Catalog;
8#[cfg(test)]
9use relate_catalog::ConstraintDef;
10use relate_core::{Error, Namespace, Result};
11
12use crate::redo::{self, RedoOp};
13
14use super::{matching_enforced_label, requires_enforced_label, Graph};
15
16pub use relate_engine_api::{
17 map_put_database, CheckpointTheater, DatabaseEntry, SchemaSnapshot, ShowSchema, TheaterData,
18};
19
20#[derive(Debug)]
31pub(crate) struct DatabasesCatalog {
32 entries: Mutex<BTreeMap<Namespace, DatabaseEntry>>,
33}
34
35impl DatabasesCatalog {
36 pub(crate) const DEFAULT_DATABASE_ENTRY: DatabaseEntry = DatabaseEntry {
42 default_language: 25,
43 composite: false,
44 };
45
46 fn seeded() -> BTreeMap<Namespace, DatabaseEntry> {
49 Namespace::ALL
50 .iter()
51 .map(|ns| (*ns, Self::DEFAULT_DATABASE_ENTRY))
52 .collect()
53 }
54
55 pub(crate) fn snapshot(&self) -> BTreeMap<Namespace, DatabaseEntry> {
58 self.entries.lock().unwrap().clone()
59 }
60
61 pub(crate) fn put_database(&self, name: &str, language: u32, composite: bool) {
64 map_put_database(&mut self.entries.lock().unwrap(), name, language, composite);
65 }
66
67 pub(crate) fn sanitize(
74 map: &BTreeMap<String, DatabaseEntry>,
75 ) -> BTreeMap<Namespace, DatabaseEntry> {
76 let mut out = Self::seeded();
80 for (name, entry) in map {
81 if let Some(ns) = Namespace::parse(name) {
82 out.insert(ns, *entry);
83 }
84 }
85 out
86 }
87
88 pub(crate) fn install(&self, map: BTreeMap<Namespace, DatabaseEntry>) {
91 *self.entries.lock().unwrap() = map;
92 }
93}
94
95impl Default for DatabasesCatalog {
96 fn default() -> Self {
97 Self {
98 entries: Mutex::new(Self::seeded()),
99 }
100 }
101}
102
103pub(crate) fn apply_show_overlay<'o>(
105 show: &mut ShowSchema,
106 ops: impl IntoIterator<Item = &'o RedoOp>,
107) -> Result<()> {
108 for op in ops {
109 match op {
110 RedoOp::CatalogIndexDetail {
111 name,
112 detail,
113 options,
114 } => {
115 let options = redo::props_from_json(options)?;
116 show.data.index_details.insert(name.clone(), detail.clone());
117 show.data.index_options.insert(name.clone(), options);
118 }
119 RedoOp::DropIndex { name } => {
120 show.data.index_details.remove(name);
121 show.data.index_options.remove(name);
122 }
123 RedoOp::PutDatabase {
124 name,
125 language,
126 composite,
127 } => {
128 map_put_database(&mut show.databases, name, *language, *composite);
129 }
130 RedoOp::DropDatabase { .. } => {}
131 RedoOp::PutGraphType { name, body } => {
132 show.data.graph_types.insert(name.clone(), body.clone());
133 }
134 RedoOp::SetCurrentGraphType { body } => {
135 set_current_graph_type(&mut show.data, body)?;
136 }
137 RedoOp::CatalogDerivedConstraint { constraint } => {
138 show.data
139 .derived_constraints
140 .insert(constraint.name.clone(), constraint.clone());
141 }
142 RedoOp::DropConstraint { name } => {
143 show.data.derived_constraints.remove(name);
144 }
145 _ => {}
146 }
147 }
148 Ok(())
149}
150
151pub(crate) fn set_current_graph_type(
157 data: &mut TheaterData,
158 spec: &crate::graph_type::GraphTypeSpec,
159) -> Result<()> {
160 let derived = crate::graph_type::persisted_derived_map(spec)?;
161 data.current_graph_type = spec.clone();
162 data.derived_constraints = derived;
163 Ok(())
164}
165
166impl Graph {
167 #[doc(hidden)]
169 pub fn checkpoint_theater(&self) -> CheckpointTheater {
170 CheckpointTheater {
171 databases: self
174 .databases()
175 .snapshot()
176 .into_iter()
177 .map(|(ns, entry)| (ns.as_str().to_string(), entry))
178 .collect(),
179 data: self.theater.lock().unwrap().clone(),
180 legacy_unknown_constraints: self
181 .legacy_unenforced
182 .lock()
183 .unwrap()
184 .clone()
185 .into_iter()
186 .collect(),
187 }
188 }
189
190 #[doc(hidden)]
202 pub fn restore_checkpoint_theater(&self, image: CheckpointTheater) -> Result<()> {
203 let mut image = image;
204 {
205 let mut catalog = self.catalog.lock().unwrap();
206 let mut migrated = catalog.clone();
207 super::derived_migration::rederive_derived_constraints(&mut image.data, &mut migrated)?;
208 Self::validate_checkpoint_theater_image_in(&image, &migrated)?;
209 *catalog = migrated;
210 }
211 self.install_checkpoint_theater_image(image)
212 }
213
214 pub fn graph_type_spec(&self) -> Result<Option<String>> {
219 let model = self.theater.lock().unwrap().current_graph_type.clone();
220 if model == Default::default() {
221 return Ok(None);
222 }
223 crate::graph_type::canonicalize_graph_type_body(&model.to_body())
224 .map_err(crate::graph_type::persisted_derive_error)
225 .map(Some)
226 }
227
228 pub fn restore_graph_type_spec(&self, spec: Option<&str>) -> Result<()> {
230 let Some(raw) = spec.map(str::trim).filter(|s| !s.is_empty()) else {
231 return Ok(());
232 };
233 let inner = raw
234 .strip_prefix('{')
235 .and_then(|s| s.strip_suffix('}'))
236 .unwrap_or(raw);
237 let body = relate_parser::parse_graph_type_body(inner)
238 .map_err(|e| Error::storage(format!("invalid graph_type spec: {e}")))?;
239 let spec = crate::graph_type::GraphTypeSpec::from_body(&body)
247 .map_err(crate::graph_type::persisted_validation_error)?;
248 let mut theater = self.theater.lock().unwrap();
249 set_current_graph_type(&mut theater, &spec)?;
250 Ok(())
251 }
252
253 #[doc(hidden)]
256 pub fn checkpoint_theater_for_write(&self) -> Result<CheckpointTheater> {
257 let image = self.checkpoint_theater();
258 self.validate_checkpoint_theater_image(&image)?;
259 Ok(image)
260 }
261
262 #[doc(hidden)]
264 pub fn mark_legacy_unenforced(&self) {
265 let image = self.checkpoint_theater();
266 let catalog = self.catalog.lock().unwrap();
267 let mut legacy = self.legacy_unenforced.lock().unwrap();
268 for def in catalog
269 .constraints
270 .values()
271 .filter(|d| requires_enforced_label(d))
272 {
273 if !image
274 .data
275 .derived_constraints
276 .get(&def.name)
277 .is_some_and(|c| matching_enforced_label(def, c))
278 {
279 legacy.insert(def.name.clone(), def.clone());
280 }
281 }
282 }
283
284 fn install_checkpoint_theater_image(&self, image: CheckpointTheater) -> Result<()> {
287 *self.legacy_unenforced.lock().unwrap() = image
288 .legacy_unknown_constraints
289 .iter()
290 .map(|(name, def)| (name.clone(), def.clone()))
291 .collect();
292 let databases = DatabasesCatalog::sanitize(&image.databases);
297 self.databases().install(databases);
300 for detail in image.data.index_details.values() {
305 self.record_schema_names(detail.relationship, detail.labels.iter().cloned());
306 }
307 for constraint in image.data.derived_constraints.values() {
308 if let Some(enforced) = &constraint.enforced_label {
309 self.record_schema_names(false, std::iter::once(enforced.clone()));
310 }
311 }
312 *self.theater.lock().unwrap() = image.data;
313 self.refresh_index_charge();
314 Ok(())
315 }
316
317 fn validate_checkpoint_theater_image(&self, image: &CheckpointTheater) -> Result<()> {
318 Self::validate_checkpoint_theater_image_in(image, &self.catalog.lock().unwrap())
319 }
320
321 fn validate_checkpoint_theater_image_in(
325 image: &CheckpointTheater,
326 catalog: &Catalog,
327 ) -> Result<()> {
328 Self::validate_legacy_unknown(image, catalog)?;
329 Self::validate_enforced_label_completeness(image, catalog)?;
330 Self::validate_graph_type_derivation(image)?;
331 Self::validate_derived_identity(image, catalog)?;
332 Self::validate_index_details(image, catalog)
333 }
334
335 fn validate_legacy_unknown(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
338 for (name, def) in &image.legacy_unknown_constraints {
339 if name != &def.name
340 || !requires_enforced_label(def)
341 || catalog.constraints.get(name) != Some(def)
342 || image.data.derived_constraints.contains_key(name)
343 {
344 return Err(Error::storage(
345 "checkpoint legacy-unknown constraint does not match its named definition",
346 ));
347 }
348 }
349 Ok(())
350 }
351
352 fn validate_enforced_label_completeness(
355 image: &CheckpointTheater,
356 catalog: &Catalog,
357 ) -> Result<()> {
358 for def in catalog
359 .constraints
360 .values()
361 .filter(|d| requires_enforced_label(d))
362 {
363 match image.data.derived_constraints.get(&def.name) {
367 Some(constraint) if matching_enforced_label(def, constraint) => {}
368 None if image.legacy_unknown_constraints.get(&def.name) == Some(def) => {}
369 _ => {
370 return Err(Error::storage(
371 "checkpoint named label constraint is missing matching enforced label",
372 ))
373 }
374 }
375 }
376 Ok(())
377 }
378
379 fn validate_graph_type_derivation(image: &CheckpointTheater) -> Result<()> {
382 for expected in
383 crate::graph_type::derive_constraints(&image.data.current_graph_type.to_body())
384 .map_err(crate::graph_type::persisted_derive_error)?
385 {
386 if image.data.derived_constraints.get(&expected.name) != Some(&expected) {
387 return Err(Error::storage(
388 "checkpoint graph type is missing a derived constraint",
389 ));
390 }
391 }
392 Ok(())
393 }
394
395 fn validate_derived_identity(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
398 for (name, constraint) in &image.data.derived_constraints {
399 let kind = match constraint.entity_kind() {
404 Ok(kind) if name == &constraint.name => kind,
405 _ => {
406 return Err(Error::storage(
407 "invalid checkpoint derived constraint identity",
408 ))
409 }
410 };
411 let label_kind = constraint.constraint_type.is_enforced_label_kind();
412 let has_label = super::has_enforced_label(constraint);
413 let relationship = kind.is_relationship();
414 let wrong_entity = constraint
415 .constraint_type
416 .enforced_label_site()
417 .is_some_and(|site| site.is_relationship() != relationship);
418 if wrong_entity {
419 return Err(Error::storage(
420 "checkpoint enforced-label entity type mismatch",
421 ));
422 }
423 if label_kind && !has_label {
424 return Err(Error::storage(
425 "checkpoint constraint is missing its enforced label",
426 ));
427 }
428 if constraint.enforced_label.is_some() {
429 let matches = catalog.constraints.values().any(|def| {
430 (def.name == *name || !catalog.constraints.contains_key(name))
431 && matching_enforced_label(def, constraint)
432 });
433 if !matches || !has_label {
434 return Err(Error::storage(
435 "invalid checkpoint enforced-label constraint",
436 ));
437 }
438 }
439 }
440 Ok(())
441 }
442
443 fn validate_index_details(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
446 for name in image
447 .data
448 .index_details
449 .keys()
450 .chain(image.data.index_options.keys())
451 {
452 if !catalog.indexes.contains_key(name) {
453 return Err(Error::storage("checkpoint index detail has no named index"));
454 }
455 }
456 Ok(())
457 }
458
459 #[doc(hidden)]
462 pub fn restore_legacy_enforced_constraints(
463 &self,
464 constraints: Vec<relate_model::Constraint>,
465 ) -> Result<()> {
466 let mut image = self.checkpoint_theater();
467 for constraint in constraints {
468 self.validate_legacy_enforced_entry(&constraint)?;
473 image
474 .data
475 .derived_constraints
476 .insert(constraint.name.clone(), constraint);
477 }
478 self.install_checkpoint_theater_image(image)
479 }
480
481 fn validate_legacy_enforced_entry(&self, constraint: &relate_model::Constraint) -> Result<()> {
484 constraint.entity_kind().map_err(Error::storage)?;
485 let catalog = self.catalog.lock().unwrap();
486 let matches = catalog
487 .constraints
488 .values()
489 .any(|def| matching_enforced_label(def, constraint));
490 if !super::has_enforced_label(constraint) || !matches {
491 return Err(Error::storage(
492 "invalid checkpoint enforced-label constraint",
493 ));
494 }
495 Ok(())
496 }
497}
498
499#[cfg(test)]
500mod tests {
501 use super::*;
502 use crate::redo::{IndexDetailSpec, IndexKindSpec};
503
504 fn range_index_detail() -> IndexDetailSpec {
505 IndexDetailSpec {
506 kind: IndexKindSpec::Range,
507 relationship: false,
508 labels: vec!["N".into()],
509 properties: vec!["p".into()],
510 with_properties: Vec::new(),
511 }
512 }
513
514 fn admitted_show() -> ShowSchema {
515 ShowSchema::capture(
516 DatabasesCatalog::default().snapshot(),
517 &TheaterData::default(),
518 )
519 }
520
521 #[test]
522 fn apply_overlay_propagates_corrupt_index_options() {
523 let mut show = admitted_show();
524 let ops = vec![RedoOp::CatalogIndexDetail {
525 name: "idx".into(),
526 detail: range_index_detail(),
527 options: serde_json::json!("corrupted"),
528 }];
529 assert!(apply_show_overlay(&mut show, &ops).is_err());
532 assert!(show.data.index_details.is_empty());
533 assert!(show.data.index_options.is_empty());
534 }
535
536 #[test]
537 fn apply_overlay_installs_valid_index_options() {
538 let mut show = admitted_show();
539 let ops = vec![RedoOp::CatalogIndexDetail {
540 name: "idx".into(),
541 detail: range_index_detail(),
542 options: serde_json::json!({}),
543 }];
544 apply_show_overlay(&mut show, &ops).unwrap();
545 assert!(show.data.index_details.contains_key("idx"));
546 assert!(show.data.index_options.contains_key("idx"));
547 }
548
549 #[test]
552 fn default_catalog_has_exactly_the_fixed_namespaces() {
553 let catalog = DatabasesCatalog::default();
554 let snapshot = catalog.snapshot();
555 let names: Vec<Namespace> = snapshot.keys().copied().collect();
556 assert_eq!(names, Namespace::ALL);
557 }
558
559 #[test]
566 fn database_ops_keep_only_the_fixed_namespaces() {
567 let ops = [
568 RedoOp::PutDatabase {
569 name: "analytics".into(),
570 language: 5,
571 composite: false,
572 },
573 RedoOp::PutDatabase {
574 name: "Neo4j".into(),
575 language: 5,
576 composite: false,
577 },
578 RedoOp::DropDatabase {
579 name: "system".into(),
580 },
581 ];
582 let mut show = admitted_show();
583 apply_show_overlay(&mut show, &ops).unwrap();
584 let names: Vec<Namespace> = show.databases.keys().copied().collect();
585 assert_eq!(names, Namespace::ALL);
586 assert_eq!(
587 show.databases[&Namespace::Neo4j],
588 DatabaseEntry {
589 default_language: 5,
590 composite: false,
591 }
592 );
593
594 let catalog = DatabasesCatalog::default();
595 for op in &ops {
596 match op {
597 RedoOp::PutDatabase {
598 name,
599 language,
600 composite,
601 } => catalog.put_database(name, *language, *composite),
602 RedoOp::DropDatabase { .. } => {}
603 _ => unreachable!(),
604 }
605 }
606 assert_eq!(catalog.snapshot(), show.databases);
607 }
608
609 #[test]
613 fn sanitize_databases_drops_non_fixed_and_fills_defaults() {
614 let mut map = BTreeMap::new();
615 map.insert(
616 "analytics".to_string(),
617 DatabaseEntry {
618 default_language: 5,
619 composite: false,
620 },
621 );
622 map.insert(
623 "NEO4J".to_string(),
624 DatabaseEntry {
625 default_language: 5,
626 composite: true,
627 },
628 );
629 let fixed = DatabasesCatalog::sanitize(&map);
630 let names: Vec<Namespace> = fixed.keys().copied().collect();
631 assert_eq!(names, Namespace::ALL);
632 assert_eq!(
633 fixed[&Namespace::Neo4j],
634 DatabaseEntry {
635 default_language: 5,
636 composite: true,
637 }
638 );
639 assert_eq!(
640 fixed[&Namespace::System],
641 DatabasesCatalog::DEFAULT_DATABASE_ENTRY
642 );
643 assert_eq!(
644 fixed[&Namespace::SystemOntologies],
645 DatabasesCatalog::DEFAULT_DATABASE_ENTRY
646 );
647 }
648
649 #[test]
655 fn restore_rederives_a_pre_generated_name_theater() {
656 use relate_model::{ConstraintType, EntityKind};
657
658 use crate::exec::test_support::exec_autocommit;
659
660 let source = Graph::default();
661 exec_autocommit(
662 &source,
663 "ALTER CURRENT GRAPH TYPE SET { (:Person => {name :: STRING NOT NULL}) }",
664 )
665 .unwrap();
666 let mut image = source.checkpoint_theater();
667 let legacy = relate_model::Constraint {
671 name: "constraint_propertyType_Person_name".into(),
672 label: "Person".into(),
673 properties: vec!["name".into()],
674 constraint_type: ConstraintType::PropertyType,
675 property_type: Some("STRING NOT NULL".into()),
676 entity_type: "NODE".into(),
677 enforced_label: None,
678 };
679 image.data.derived_constraints =
680 std::iter::once((legacy.name.clone(), legacy.clone())).collect::<BTreeMap<_, _>>();
681
682 let graph = Graph::default();
683 graph
684 .install_named_constraint(ConstraintDef::from_model(&legacy, EntityKind::Node))
685 .unwrap();
686 graph
687 .restore_checkpoint_theater(image)
688 .expect("a pre-generated-name image re-derives and restores");
689
690 let theater = graph.theater.lock().unwrap();
691 let expected =
692 crate::graph_type::derived_constraints_map(&theater.current_graph_type.to_body())
693 .unwrap();
694 assert_eq!(theater.derived_constraints, expected);
695 drop(theater);
696 let mut rows = graph.named_constraints();
697 rows.sort_by(|a, b| a.name.cmp(&b.name));
698 assert_eq!(rows.len(), 2, "{rows:?}");
699 assert!(
700 rows.iter().all(|def| def.name.starts_with("constraint_")),
701 "{rows:?}"
702 );
703 let property_type = rows
704 .iter()
705 .find(|def| def.kind == "propertyType")
706 .expect("the property-type row survives the re-derivation");
707 assert_eq!(property_type.property_type.as_deref(), Some("STRING"));
708 }
709
710 #[test]
716 fn replaying_a_pre_generated_name_record_keeps_the_catalog_current() {
717 use relate_model::{ConstraintType, EntityKind};
718
719 use crate::exec::test_support::exec_autocommit;
720
721 let graph = Graph::default();
722 exec_autocommit(
723 &graph,
724 "ALTER CURRENT GRAPH TYPE SET { (:Person => {name :: STRING NOT NULL}) }",
725 )
726 .unwrap();
727 let body = graph.checkpoint_theater().data.current_graph_type.clone();
728 let committed: Vec<String> = graph
729 .named_constraints()
730 .into_iter()
731 .map(|def| def.name)
732 .collect();
733 assert_eq!(committed.len(), 2, "{committed:?}");
734
735 let legacy = relate_model::Constraint {
738 name: "constraint_propertyType_Person_name".into(),
739 label: "Person".into(),
740 properties: vec!["name".into()],
741 constraint_type: ConstraintType::PropertyType,
742 property_type: Some("STRING NOT NULL".into()),
743 entity_type: "NODE".into(),
744 enforced_label: None,
745 };
746 let mut ops: Vec<RedoOp> = committed
747 .into_iter()
748 .map(|name| RedoOp::DropConstraint { name })
749 .collect();
750 ops.push(RedoOp::create_constraint(ConstraintDef::from_model(
751 &legacy,
752 EntityKind::Node,
753 )));
754 ops.push(RedoOp::CatalogDerivedConstraint { constraint: legacy });
755 ops.push(RedoOp::SetCurrentGraphType { body });
756 graph.apply_redo(ops, graph.commit_ts() + 1).unwrap();
757
758 let mut rows = graph.named_constraints();
759 rows.sort_by(|a, b| a.name.cmp(&b.name));
760 assert_eq!(rows.len(), 2, "{rows:?}");
761 assert!(
762 rows.iter().all(|def| def.name.starts_with("constraint_")),
763 "{rows:?}"
764 );
765 assert!(
766 rows.iter()
767 .any(|def| def.property_type.as_deref() == Some("STRING")),
768 "{rows:?}"
769 );
770
771 let alter = "ALTER CURRENT GRAPH TYPE ALTER { (:Person => {name :: STRING NOT NULL, nickname :: STRING}) }";
774 exec_autocommit(&graph, alter).expect("the upgraded store's ALTER re-syncs cleanly");
775 let after = graph.named_constraints().len();
776 exec_autocommit(&graph, alter).expect("a repeated ALTER stays idempotent");
777 assert_eq!(graph.named_constraints().len(), after);
778 }
779}