Skip to main content

mqdb_core/
relationship.rs

1// Copyright 2025-2026 LabOverWire. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::collections::HashMap;
5
6#[derive(Debug, Clone)]
7pub struct Relationship {
8    pub source_entity: String,
9    pub field: String,
10    pub target_entity: String,
11    pub field_suffix: String,
12}
13
14impl Relationship {
15    #[allow(clippy::must_use_candidate)]
16    pub fn new(source_entity: String, field: String, target_entity: String) -> Self {
17        let field_suffix = if field.ends_with("_id") {
18            field.clone()
19        } else {
20            format!("{field}_id")
21        };
22
23        Self {
24            source_entity,
25            field,
26            target_entity,
27            field_suffix,
28        }
29    }
30}
31
32#[derive(Default)]
33pub struct RelationshipRegistry {
34    relationships: HashMap<String, Vec<Relationship>>,
35}
36
37impl RelationshipRegistry {
38    #[allow(clippy::must_use_candidate)]
39    pub fn new() -> Self {
40        Self {
41            relationships: HashMap::new(),
42        }
43    }
44
45    pub fn add(&mut self, relationship: Relationship) {
46        let key = relationship.source_entity.clone();
47        self.relationships
48            .entry(key)
49            .or_default()
50            .push(relationship);
51    }
52
53    #[allow(clippy::must_use_candidate)]
54    pub fn get(&self, entity: &str, field: &str) -> Option<&Relationship> {
55        self.relationships
56            .get(entity)?
57            .iter()
58            .find(|r| r.field == field)
59    }
60
61    #[allow(clippy::must_use_candidate)]
62    pub fn get_all(&self, entity: &str) -> Option<&Vec<Relationship>> {
63        self.relationships.get(entity)
64    }
65}