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(
153 data: &mut TheaterData,
154 spec: &crate::graph_type::GraphTypeSpec,
155) -> Result<()> {
156 let derived = crate::graph_type::derived_constraints_map(&spec.to_body())
157 .map_err(crate::graph_type::persisted_derive_error)?;
158 data.current_graph_type = spec.clone();
159 data.derived_constraints = derived;
160 Ok(())
161}
162
163impl Graph {
164 #[doc(hidden)]
166 pub fn checkpoint_theater(&self) -> CheckpointTheater {
167 CheckpointTheater {
168 databases: self
171 .databases()
172 .snapshot()
173 .into_iter()
174 .map(|(ns, entry)| (ns.as_str().to_string(), entry))
175 .collect(),
176 data: self.theater.lock().unwrap().clone(),
177 legacy_unknown_constraints: self
178 .legacy_unenforced
179 .lock()
180 .unwrap()
181 .clone()
182 .into_iter()
183 .collect(),
184 }
185 }
186
187 #[doc(hidden)]
199 pub fn restore_checkpoint_theater(&self, image: CheckpointTheater) -> Result<()> {
200 let mut image = image;
201 {
202 let mut catalog = self.catalog.lock().unwrap();
203 let mut migrated = catalog.clone();
204 super::derived_migration::rederive_derived_constraints(&mut image.data, &mut migrated)?;
205 Self::validate_checkpoint_theater_image_in(&image, &migrated)?;
206 *catalog = migrated;
207 }
208 self.install_checkpoint_theater_image(image)
209 }
210
211 pub fn graph_type_spec(&self) -> Result<Option<String>> {
216 let model = self.theater.lock().unwrap().current_graph_type.clone();
217 if model == Default::default() {
218 return Ok(None);
219 }
220 crate::graph_type::canonicalize_graph_type_body(&model.to_body())
221 .map_err(crate::graph_type::persisted_derive_error)
222 .map(Some)
223 }
224
225 pub fn restore_graph_type_spec(&self, spec: Option<&str>) -> Result<()> {
227 let Some(raw) = spec.map(str::trim).filter(|s| !s.is_empty()) else {
228 return Ok(());
229 };
230 let inner = raw
231 .strip_prefix('{')
232 .and_then(|s| s.strip_suffix('}'))
233 .unwrap_or(raw);
234 let body = relate_parser::parse_graph_type_body(inner)
235 .map_err(|e| Error::storage(format!("invalid graph_type spec: {e}")))?;
236 let spec = crate::graph_type::GraphTypeSpec::from_body(&body)
244 .map_err(crate::graph_type::persisted_validation_error)?;
245 let mut theater = self.theater.lock().unwrap();
246 set_current_graph_type(&mut theater, &spec)?;
247 Ok(())
248 }
249
250 #[doc(hidden)]
253 pub fn checkpoint_theater_for_write(&self) -> Result<CheckpointTheater> {
254 let image = self.checkpoint_theater();
255 self.validate_checkpoint_theater_image(&image)?;
256 Ok(image)
257 }
258
259 #[doc(hidden)]
261 pub fn mark_legacy_unenforced(&self) {
262 let image = self.checkpoint_theater();
263 let catalog = self.catalog.lock().unwrap();
264 let mut legacy = self.legacy_unenforced.lock().unwrap();
265 for def in catalog
266 .constraints
267 .values()
268 .filter(|d| requires_enforced_label(d))
269 {
270 if !image
271 .data
272 .derived_constraints
273 .get(&def.name)
274 .is_some_and(|c| matching_enforced_label(def, c))
275 {
276 legacy.insert(def.name.clone(), def.clone());
277 }
278 }
279 }
280
281 fn install_checkpoint_theater_image(&self, image: CheckpointTheater) -> Result<()> {
284 *self.legacy_unenforced.lock().unwrap() = image
285 .legacy_unknown_constraints
286 .iter()
287 .map(|(name, def)| (name.clone(), def.clone()))
288 .collect();
289 let databases = DatabasesCatalog::sanitize(&image.databases);
294 self.databases().install(databases);
297 for detail in image.data.index_details.values() {
302 self.record_schema_names(detail.relationship, detail.labels.iter().cloned());
303 }
304 for constraint in image.data.derived_constraints.values() {
305 if let Some(enforced) = &constraint.enforced_label {
306 self.record_schema_names(false, std::iter::once(enforced.clone()));
307 }
308 }
309 *self.theater.lock().unwrap() = image.data;
310 self.refresh_index_charge();
311 Ok(())
312 }
313
314 fn validate_checkpoint_theater_image(&self, image: &CheckpointTheater) -> Result<()> {
315 Self::validate_checkpoint_theater_image_in(image, &self.catalog.lock().unwrap())
316 }
317
318 fn validate_checkpoint_theater_image_in(
322 image: &CheckpointTheater,
323 catalog: &Catalog,
324 ) -> Result<()> {
325 Self::validate_legacy_unknown(image, catalog)?;
326 Self::validate_enforced_label_completeness(image, catalog)?;
327 Self::validate_graph_type_derivation(image)?;
328 Self::validate_derived_identity(image, catalog)?;
329 Self::validate_index_details(image, catalog)
330 }
331
332 fn validate_legacy_unknown(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
335 for (name, def) in &image.legacy_unknown_constraints {
336 if name != &def.name
337 || !requires_enforced_label(def)
338 || catalog.constraints.get(name) != Some(def)
339 || image.data.derived_constraints.contains_key(name)
340 {
341 return Err(Error::storage(
342 "checkpoint legacy-unknown constraint does not match its named definition",
343 ));
344 }
345 }
346 Ok(())
347 }
348
349 fn validate_enforced_label_completeness(
352 image: &CheckpointTheater,
353 catalog: &Catalog,
354 ) -> Result<()> {
355 for def in catalog
356 .constraints
357 .values()
358 .filter(|d| requires_enforced_label(d))
359 {
360 match image.data.derived_constraints.get(&def.name) {
364 Some(constraint) if matching_enforced_label(def, constraint) => {}
365 None if image.legacy_unknown_constraints.get(&def.name) == Some(def) => {}
366 _ => {
367 return Err(Error::storage(
368 "checkpoint named label constraint is missing matching enforced label",
369 ))
370 }
371 }
372 }
373 Ok(())
374 }
375
376 fn validate_graph_type_derivation(image: &CheckpointTheater) -> Result<()> {
379 for expected in
380 crate::graph_type::derive_constraints(&image.data.current_graph_type.to_body())
381 .map_err(crate::graph_type::persisted_derive_error)?
382 {
383 if image.data.derived_constraints.get(&expected.name) != Some(&expected) {
384 return Err(Error::storage(
385 "checkpoint graph type is missing a derived constraint",
386 ));
387 }
388 }
389 Ok(())
390 }
391
392 fn validate_derived_identity(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
395 for (name, constraint) in &image.data.derived_constraints {
396 let kind = match constraint.entity_kind() {
401 Ok(kind) if name == &constraint.name => kind,
402 _ => {
403 return Err(Error::storage(
404 "invalid checkpoint derived constraint identity",
405 ))
406 }
407 };
408 let label_kind = constraint.constraint_type.is_enforced_label_kind();
409 let has_label = super::has_enforced_label(constraint);
410 let relationship = kind.is_relationship();
411 let wrong_entity = constraint
412 .constraint_type
413 .enforced_label_site()
414 .is_some_and(|site| site.is_relationship() != relationship);
415 if wrong_entity {
416 return Err(Error::storage(
417 "checkpoint enforced-label entity type mismatch",
418 ));
419 }
420 if label_kind && !has_label {
421 return Err(Error::storage(
422 "checkpoint constraint is missing its enforced label",
423 ));
424 }
425 if constraint.enforced_label.is_some() {
426 let matches = catalog.constraints.values().any(|def| {
427 (def.name == *name || !catalog.constraints.contains_key(name))
428 && matching_enforced_label(def, constraint)
429 });
430 if !matches || !has_label {
431 return Err(Error::storage(
432 "invalid checkpoint enforced-label constraint",
433 ));
434 }
435 }
436 }
437 Ok(())
438 }
439
440 fn validate_index_details(image: &CheckpointTheater, catalog: &Catalog) -> Result<()> {
443 for name in image
444 .data
445 .index_details
446 .keys()
447 .chain(image.data.index_options.keys())
448 {
449 if !catalog.indexes.contains_key(name) {
450 return Err(Error::storage("checkpoint index detail has no named index"));
451 }
452 }
453 Ok(())
454 }
455
456 #[doc(hidden)]
459 pub fn restore_legacy_enforced_constraints(
460 &self,
461 constraints: Vec<relate_model::Constraint>,
462 ) -> Result<()> {
463 let mut image = self.checkpoint_theater();
464 for constraint in constraints {
465 self.validate_legacy_enforced_entry(&constraint)?;
470 image
471 .data
472 .derived_constraints
473 .insert(constraint.name.clone(), constraint);
474 }
475 self.install_checkpoint_theater_image(image)
476 }
477
478 fn validate_legacy_enforced_entry(&self, constraint: &relate_model::Constraint) -> Result<()> {
481 constraint.entity_kind().map_err(Error::storage)?;
482 let catalog = self.catalog.lock().unwrap();
483 let matches = catalog
484 .constraints
485 .values()
486 .any(|def| matching_enforced_label(def, constraint));
487 if !super::has_enforced_label(constraint) || !matches {
488 return Err(Error::storage(
489 "invalid checkpoint enforced-label constraint",
490 ));
491 }
492 Ok(())
493 }
494}
495
496#[cfg(test)]
497mod tests {
498 use super::*;
499 use crate::redo::{IndexDetailSpec, IndexKindSpec};
500
501 fn range_index_detail() -> IndexDetailSpec {
502 IndexDetailSpec {
503 kind: IndexKindSpec::Range,
504 relationship: false,
505 labels: vec!["N".into()],
506 properties: vec!["p".into()],
507 with_properties: Vec::new(),
508 }
509 }
510
511 fn admitted_show() -> ShowSchema {
512 ShowSchema::capture(
513 DatabasesCatalog::default().snapshot(),
514 &TheaterData::default(),
515 )
516 }
517
518 #[test]
519 fn apply_overlay_propagates_corrupt_index_options() {
520 let mut show = admitted_show();
521 let ops = vec![RedoOp::CatalogIndexDetail {
522 name: "idx".into(),
523 detail: range_index_detail(),
524 options: serde_json::json!("corrupted"),
525 }];
526 assert!(apply_show_overlay(&mut show, &ops).is_err());
529 assert!(show.data.index_details.is_empty());
530 assert!(show.data.index_options.is_empty());
531 }
532
533 #[test]
534 fn apply_overlay_installs_valid_index_options() {
535 let mut show = admitted_show();
536 let ops = vec![RedoOp::CatalogIndexDetail {
537 name: "idx".into(),
538 detail: range_index_detail(),
539 options: serde_json::json!({}),
540 }];
541 apply_show_overlay(&mut show, &ops).unwrap();
542 assert!(show.data.index_details.contains_key("idx"));
543 assert!(show.data.index_options.contains_key("idx"));
544 }
545
546 #[test]
549 fn default_catalog_has_exactly_the_fixed_namespaces() {
550 let catalog = DatabasesCatalog::default();
551 let snapshot = catalog.snapshot();
552 let names: Vec<Namespace> = snapshot.keys().copied().collect();
553 assert_eq!(names, Namespace::ALL);
554 }
555
556 #[test]
563 fn database_ops_keep_only_the_fixed_namespaces() {
564 let ops = [
565 RedoOp::PutDatabase {
566 name: "analytics".into(),
567 language: 5,
568 composite: false,
569 },
570 RedoOp::PutDatabase {
571 name: "Neo4j".into(),
572 language: 5,
573 composite: false,
574 },
575 RedoOp::DropDatabase {
576 name: "system".into(),
577 },
578 ];
579 let mut show = admitted_show();
580 apply_show_overlay(&mut show, &ops).unwrap();
581 let names: Vec<Namespace> = show.databases.keys().copied().collect();
582 assert_eq!(names, Namespace::ALL);
583 assert_eq!(
584 show.databases[&Namespace::Neo4j],
585 DatabaseEntry {
586 default_language: 5,
587 composite: false,
588 }
589 );
590
591 let catalog = DatabasesCatalog::default();
592 for op in &ops {
593 match op {
594 RedoOp::PutDatabase {
595 name,
596 language,
597 composite,
598 } => catalog.put_database(name, *language, *composite),
599 RedoOp::DropDatabase { .. } => {}
600 _ => unreachable!(),
601 }
602 }
603 assert_eq!(catalog.snapshot(), show.databases);
604 }
605
606 #[test]
610 fn sanitize_databases_drops_non_fixed_and_fills_defaults() {
611 let mut map = BTreeMap::new();
612 map.insert(
613 "analytics".to_string(),
614 DatabaseEntry {
615 default_language: 5,
616 composite: false,
617 },
618 );
619 map.insert(
620 "NEO4J".to_string(),
621 DatabaseEntry {
622 default_language: 5,
623 composite: true,
624 },
625 );
626 let fixed = DatabasesCatalog::sanitize(&map);
627 let names: Vec<Namespace> = fixed.keys().copied().collect();
628 assert_eq!(names, Namespace::ALL);
629 assert_eq!(
630 fixed[&Namespace::Neo4j],
631 DatabaseEntry {
632 default_language: 5,
633 composite: true,
634 }
635 );
636 assert_eq!(
637 fixed[&Namespace::System],
638 DatabasesCatalog::DEFAULT_DATABASE_ENTRY
639 );
640 assert_eq!(
641 fixed[&Namespace::SystemOntologies],
642 DatabasesCatalog::DEFAULT_DATABASE_ENTRY
643 );
644 }
645
646 #[test]
652 fn restore_rederives_a_pre_generated_name_theater() {
653 use relate_model::{ConstraintType, EntityKind};
654
655 use crate::exec::test_support::exec_autocommit;
656
657 let source = Graph::default();
658 exec_autocommit(
659 &source,
660 "ALTER CURRENT GRAPH TYPE SET { (:Person => {name :: STRING NOT NULL}) }",
661 )
662 .unwrap();
663 let mut image = source.checkpoint_theater();
664 let legacy = relate_model::Constraint {
668 name: "constraint_propertyType_Person_name".into(),
669 label: "Person".into(),
670 properties: vec!["name".into()],
671 constraint_type: ConstraintType::PropertyType,
672 property_type: Some("STRING NOT NULL".into()),
673 entity_type: "NODE".into(),
674 enforced_label: None,
675 };
676 image.data.derived_constraints =
677 std::iter::once((legacy.name.clone(), legacy.clone())).collect::<BTreeMap<_, _>>();
678
679 let graph = Graph::default();
680 graph
681 .install_named_constraint(ConstraintDef::from_model(&legacy, EntityKind::Node))
682 .unwrap();
683 graph
684 .restore_checkpoint_theater(image)
685 .expect("a pre-generated-name image re-derives and restores");
686
687 let theater = graph.theater.lock().unwrap();
688 let expected =
689 crate::graph_type::derived_constraints_map(&theater.current_graph_type.to_body())
690 .unwrap();
691 assert_eq!(theater.derived_constraints, expected);
692 drop(theater);
693 let mut rows = graph.named_constraints();
694 rows.sort_by(|a, b| a.name.cmp(&b.name));
695 assert_eq!(rows.len(), 2, "{rows:?}");
696 assert!(
697 rows.iter().all(|def| def.name.starts_with("constraint_")),
698 "{rows:?}"
699 );
700 let property_type = rows
701 .iter()
702 .find(|def| def.kind == "propertyType")
703 .expect("the property-type row survives the re-derivation");
704 assert_eq!(property_type.property_type.as_deref(), Some("STRING"));
705 }
706
707 #[test]
713 fn replaying_a_pre_generated_name_record_keeps_the_catalog_current() {
714 use relate_model::{ConstraintType, EntityKind};
715
716 use crate::exec::test_support::exec_autocommit;
717
718 let graph = Graph::default();
719 exec_autocommit(
720 &graph,
721 "ALTER CURRENT GRAPH TYPE SET { (:Person => {name :: STRING NOT NULL}) }",
722 )
723 .unwrap();
724 let body = graph.checkpoint_theater().data.current_graph_type.clone();
725 let committed: Vec<String> = graph
726 .named_constraints()
727 .into_iter()
728 .map(|def| def.name)
729 .collect();
730 assert_eq!(committed.len(), 2, "{committed:?}");
731
732 let legacy = relate_model::Constraint {
735 name: "constraint_propertyType_Person_name".into(),
736 label: "Person".into(),
737 properties: vec!["name".into()],
738 constraint_type: ConstraintType::PropertyType,
739 property_type: Some("STRING NOT NULL".into()),
740 entity_type: "NODE".into(),
741 enforced_label: None,
742 };
743 let mut ops: Vec<RedoOp> = committed
744 .into_iter()
745 .map(|name| RedoOp::DropConstraint { name })
746 .collect();
747 ops.push(RedoOp::create_constraint(ConstraintDef::from_model(
748 &legacy,
749 EntityKind::Node,
750 )));
751 ops.push(RedoOp::CatalogDerivedConstraint { constraint: legacy });
752 ops.push(RedoOp::SetCurrentGraphType { body });
753 graph.apply_redo(ops, graph.commit_ts() + 1).unwrap();
754
755 let mut rows = graph.named_constraints();
756 rows.sort_by(|a, b| a.name.cmp(&b.name));
757 assert_eq!(rows.len(), 2, "{rows:?}");
758 assert!(
759 rows.iter().all(|def| def.name.starts_with("constraint_")),
760 "{rows:?}"
761 );
762 assert!(
763 rows.iter()
764 .any(|def| def.property_type.as_deref() == Some("STRING")),
765 "{rows:?}"
766 );
767
768 let alter = "ALTER CURRENT GRAPH TYPE ALTER { (:Person => {name :: STRING NOT NULL, nickname :: STRING}) }";
771 exec_autocommit(&graph, alter).expect("the upgraded store's ALTER re-syncs cleanly");
772 let after = graph.named_constraints().len();
773 exec_autocommit(&graph, alter).expect("a repeated ALTER stays idempotent");
774 assert_eq!(graph.named_constraints().len(), after);
775 }
776}