Skip to main content

schema_model/model/
database_model.rs

1use crate::model::enum_type::EnumType;
2use crate::model::schema::Schema;
3use crate::model::table::Table;
4use crate::model::types::{BooleanMode, ForeignKeyMode};
5
6#[derive(Debug, Default, Clone)]
7pub struct DatabaseModel {
8    foreign_key_mode: ForeignKeyMode,
9    boolean_mode: BooleanMode,
10    schemas: Vec<Schema>,
11}
12
13impl DatabaseModel {
14    pub fn new(boolean_mode: BooleanMode,
15               foreign_key_mode: ForeignKeyMode,
16               schemas: Vec<Schema>) -> Self {
17        Self {
18            boolean_mode,
19            foreign_key_mode,
20            schemas,
21        }
22    }
23
24    pub fn foreign_key_mode(&self) -> ForeignKeyMode {
25        self.foreign_key_mode
26    }
27
28    pub fn boolean_mode(&self) -> BooleanMode {
29        self.boolean_mode
30    }
31
32    pub fn schemas(&self) -> &Vec<Schema> {
33        &self.schemas
34    }
35
36    pub fn default_schema(&self) -> &Schema {
37        self.schemas
38            .iter()
39            .find(|s| s.schema_name().is_none())
40            .expect("Default schema not found")
41    }
42
43    pub fn default_schema_mut(&mut self) -> &mut Schema {
44        self.schemas
45            .iter_mut()
46            .find(|s| s.schema_name().is_none())
47            .expect("Default schema not found")
48    }
49
50    pub fn find_schema(&self, schema_name: Option<&str>) -> &Schema {
51        if schema_name.is_none() {
52            return self.default_schema();
53        }
54
55        self.schemas
56            .iter()
57            .filter(|s| s.schema_name().is_some())
58            .find(|s| s.schema_name().unwrap() == schema_name.unwrap())
59            .expect("Schema not found")
60    }
61
62    pub(crate) fn find_schema_mut(&mut self, schema_name: Option<&str>) -> &mut Schema {
63        if schema_name.is_none() {
64            return self.default_schema_mut();
65        }
66
67        self.schemas
68            .iter_mut()
69            .filter(|s| s.schema_name().is_some())
70            .find(|s| s.schema_name().unwrap() == schema_name.unwrap())
71            .expect("Schema not found")
72    }
73
74    pub fn find_enum_type(&self, schema_name: Option<&str>, enum_type: &str) -> &EnumType {
75        let schema = self.find_schema(schema_name);
76        schema.get_enum_type(enum_type)
77    }
78
79    pub fn all_tables(&self) -> Vec<&Table> {
80        self.schemas
81            .iter()
82            .flat_map(|s| s.tables())
83            .collect()
84    }
85
86    pub fn find_table(&self, schema_name: Option<&str>, table_name: &str) -> &Table {
87        let schema = self.find_schema(schema_name);
88        schema.get_table(table_name)
89    }
90
91    pub fn find_table_by_qualified_name(&self, qualified_name: &str) -> &Table {
92        let parts: Vec<&str> = qualified_name.split('.').collect();
93        let (schema_name, table_name) = if parts.len() == 2 {
94            (Some(parts[0]), parts[1])
95        } else {
96            (None, qualified_name)
97        };
98
99        self.find_table(schema_name, table_name)
100    }
101
102    /// Same as `find_table_by_qualified_name`, but returns `None` instead of panicking
103    /// when the schema or table doesn't exist - used by `validate()` to check relation
104    /// targets without crashing on a dangling one.
105    pub fn find_table_by_qualified_name_checked(&self, qualified_name: &str) -> Option<&Table> {
106        let parts: Vec<&str> = qualified_name.split('.').collect();
107        let (schema_name, table_name) = if parts.len() == 2 {
108            (Some(parts[0]), parts[1])
109        } else {
110            (None, qualified_name)
111        };
112
113        self.schemas
114            .iter()
115            .find(|s| s.schema_name() == schema_name)
116            .and_then(|s| s.get_optional_table(table_name))
117    }
118
119    /// Checks model-wide invariants that individual `Schema::validate()` calls can't see
120    /// (a relation's target table may live in a different schema than the one declaring
121    /// it). Combined with each schema's own `validate()`, this is meant to be run once
122    /// after parsing/building a model and before handing it to SQL generation or
123    /// migration - several generator code paths (`find_enum_type`, `find_table_by_qualified_name`,
124    /// ...) panic on a reference that doesn't resolve, on the assumption the model was
125    /// already validated.
126    pub fn validate(&self) -> Vec<String> {
127        let mut errors: Vec<String> = Vec::new();
128
129        for schema in &self.schemas {
130            errors.extend(schema.validate());
131        }
132
133        for table in self.all_tables() {
134            for relation in table.relations() {
135                if self.find_table_by_qualified_name_checked(relation.to_table_name()).is_none() {
136                    errors.push(format!(
137                        "ERROR: {}.{} has a relation to '{}' which does not exist",
138                        table.name(),
139                        relation.from_column_name(),
140                        relation.to_table_name()
141                    ));
142                }
143            }
144        }
145
146        errors
147    }
148
149    pub fn find_table_mut(&mut self, schema_name: Option<&str>, table_name: &str) -> &mut Table {
150        let schema = self.find_schema_mut(schema_name);
151        schema.get_table_mut(table_name)
152    }
153
154    /// Same as `find_table_mut`, but returns `None` instead of panicking when the schema
155    /// or table doesn't exist - useful for callers (e.g. the XML parser) resolving
156    /// possibly-malformed input, where a dangling reference should surface as an error
157    /// rather than crash.
158    pub fn find_table_mut_checked(&mut self, schema_name: Option<&str>, table_name: &str) -> Option<&mut Table> {
159        let schema = self.schemas.iter_mut().find(|s| s.schema_name() == schema_name)?;
160        schema.get_table_mut_checked(table_name)
161    }
162
163    pub fn sort_tables_by_name(&mut self) {
164        for schema in self.schemas.iter_mut() {
165            schema.sort_tables_by_name();
166        }
167    }
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use crate::builder::{ColumnBuilder, SchemaBuilder, TableBuilder};
174    use crate::model::column_type::ColumnType;
175    use crate::model::relation::Relation;
176    use crate::model::types::RelationType;
177
178    #[test]
179    fn validate_reports_error_for_a_relation_whose_target_table_does_not_exist() {
180        // A relation whose target table doesn't exist anywhere in the model (typo'd
181        // name, or a schema that was never declared) must surface as a validation
182        // error - several generator code paths panic on this instead if it's not
183        // caught up front.
184        let child = TableBuilder::new(None::<&str>, "child")
185            .add_column(ColumnBuilder::new(None::<&str>, "parent_id", ColumnType::Int).build())
186            .add_relation(Relation::new("Regoin", "id", "child", "parent_id", RelationType::Cascade, false))
187            .build();
188        let schema = SchemaBuilder::new(None::<&str>).add_table(child).build();
189        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
190
191        let errors = model.validate();
192        assert_eq!(errors.len(), 1);
193        assert!(errors[0].contains("Regoin"));
194    }
195
196    #[test]
197    fn validate_accepts_a_relation_whose_target_table_exists_in_a_different_schema() {
198        let parent = TableBuilder::new(Some("app"), "parent")
199            .add_column(ColumnBuilder::new(None::<&str>, "id", ColumnType::Sequence).required(true).build())
200            .build();
201        let parent_schema = SchemaBuilder::new(Some("app")).add_table(parent).build();
202
203        let child = TableBuilder::new(None::<&str>, "child")
204            .add_column(ColumnBuilder::new(None::<&str>, "parent_id", ColumnType::Int).build())
205            .add_relation(Relation::new("app.parent", "id", "child", "parent_id", RelationType::Cascade, false))
206            .build();
207        let default_schema = SchemaBuilder::new(None::<&str>).add_table(child).build();
208
209        let model = DatabaseModel::new(
210            BooleanMode::Native,
211            ForeignKeyMode::Relations,
212            vec![default_schema, parent_schema],
213        );
214
215        assert!(model.validate().is_empty());
216    }
217}