Skip to main content

schema_model/model/
relation.rs

1use crate::model::types::RelationType;
2
3#[derive(Debug, Clone)]
4pub struct Relation {
5    to_table_name: String,
6    from_table_name: String,
7    column_pairs: Vec<(String, String)>,
8    relation_type: RelationType,
9    disable_usage_checking: bool,
10}
11impl Relation {
12    #[allow(clippy::too_many_arguments)]
13    pub fn new<SS: Into<String>>(
14        to_table_name: SS,
15        to_column_name: SS,
16        from_table_name: SS,
17        from_column_name: SS,
18        relation_type: RelationType,
19        disable_usage_checking: bool,
20    ) -> Self {
21        Self {
22            to_table_name: to_table_name.into(),
23            from_table_name: from_table_name.into(),
24            column_pairs: vec![(from_column_name.into(), to_column_name.into())],
25            relation_type,
26            disable_usage_checking,
27        }
28    }
29
30    /// Constructs a composite (multi-column) foreign key relation from a list of
31    /// `(from_column_name, to_column_name)` pairs, one per column position.
32    ///
33    /// Errors (rather than silently coercing) when fewer than two pairs are given -
34    /// a single-pair "composite" relation should be constructed via [`Relation::new`] instead.
35    pub fn new_composite<SS: Into<String>>(
36        to_table_name: SS,
37        from_table_name: SS,
38        column_pairs: Vec<(SS, SS)>,
39        relation_type: RelationType,
40        disable_usage_checking: bool,
41    ) -> Result<Self, String> {
42        if column_pairs.len() < 2 {
43            return Err(format!(
44                "composite relation must have at least 2 column pairs, got {}",
45                column_pairs.len()
46            ));
47        }
48        Ok(Self {
49            to_table_name: to_table_name.into(),
50            from_table_name: from_table_name.into(),
51            column_pairs: column_pairs
52                .into_iter()
53                .map(|(from, to)| (from.into(), to.into()))
54                .collect(),
55            relation_type,
56            disable_usage_checking,
57        })
58    }
59
60    pub fn to_table_name(&self) -> &str {
61        &self.to_table_name
62    }
63
64    /// First column pair's target-table column. For a composite relation, prefer
65    /// [`Relation::column_pairs`] to see every mapped column.
66    pub fn to_column_name(&self) -> &str {
67        &self.column_pairs[0].1
68    }
69
70    pub fn from_table_name(&self) -> &str {
71        &self.from_table_name
72    }
73
74    /// First column pair's local column. For a composite relation, prefer
75    /// [`Relation::column_pairs`] to see every mapped column.
76    pub fn from_column_name(&self) -> &str {
77        &self.column_pairs[0].0
78    }
79
80    /// All `(from_column_name, to_column_name)` pairs, in declared order.
81    pub fn column_pairs(&self) -> &[(String, String)] {
82        &self.column_pairs
83    }
84
85    pub fn is_composite(&self) -> bool {
86        self.column_pairs.len() > 1
87    }
88
89    pub fn relation_type(&self) -> RelationType {
90        self.relation_type
91    }
92
93    pub fn disable_usage_checking(&self) -> bool {
94        self.disable_usage_checking
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::model::types::RelationType;
102
103    #[test]
104    fn constructor_and_getters() {
105        let r = Relation::new(
106            "parent",
107            "id",
108            "child",
109            "parent_id",
110            RelationType::Cascade,
111            true,
112        );
113        assert_eq!(r.to_table_name(), "parent");
114        assert_eq!(r.to_column_name(), "id");
115        assert_eq!(r.from_table_name(), "child");
116        assert_eq!(r.from_column_name(), "parent_id");
117        assert_eq!(r.relation_type(), RelationType::Cascade);
118        assert!(r.disable_usage_checking());
119        assert!(!r.is_composite());
120        assert_eq!(
121            r.column_pairs(),
122            &[("parent_id".to_string(), "id".to_string())]
123        );
124    }
125
126    #[test]
127    fn composite_constructor_and_getters() {
128        let r = Relation::new_composite(
129            "Assignment",
130            "Child",
131            vec![("ParentAssignmentID", "ID"), ("PropertyID", "PropertyID")],
132            RelationType::Cascade,
133            false,
134        )
135        .unwrap();
136        assert_eq!(r.to_table_name(), "Assignment");
137        assert_eq!(r.from_table_name(), "Child");
138        assert!(r.is_composite());
139        assert_eq!(r.from_column_name(), "ParentAssignmentID");
140        assert_eq!(r.to_column_name(), "ID");
141        assert_eq!(
142            r.column_pairs(),
143            &[
144                ("ParentAssignmentID".to_string(), "ID".to_string()),
145                ("PropertyID".to_string(), "PropertyID".to_string()),
146            ]
147        );
148        assert_eq!(r.relation_type(), RelationType::Cascade);
149        assert!(!r.disable_usage_checking());
150    }
151
152    #[test]
153    fn composite_constructor_rejects_empty_pairs() {
154        let err = Relation::new_composite::<&str>(
155            "Assignment",
156            "Child",
157            vec![],
158            RelationType::Cascade,
159            false,
160        )
161        .unwrap_err();
162        assert!(err.contains("at least 2"));
163    }
164
165    #[test]
166    fn composite_constructor_rejects_single_pair() {
167        let err = Relation::new_composite(
168            "Assignment",
169            "Child",
170            vec![("PropertyID", "PropertyID")],
171            RelationType::Cascade,
172            false,
173        )
174        .unwrap_err();
175        assert!(err.contains("at least 2"));
176    }
177}