1use crate::model::enum_type::EnumType;
2use crate::model::function::Function;
3use crate::model::other_sql::OtherSql;
4use crate::model::procedure::Procedure;
5use crate::model::table::Table;
6use crate::model::types::{DatabaseType, RelationType};
7use crate::model::view::View;
8use std::collections::HashMap;
9
10#[derive(Debug)]
11pub struct Schema {
12 schema_name: Option<String>,
13 case_sensitive_text: bool,
14 tables: Vec<Table>,
15 views: Vec<View>,
16 functions: Vec<Function>,
17 procedures: Vec<Procedure>,
18 other_sql: Vec<OtherSql>,
19 table_map: HashMap<String, usize>,
21 enum_types: HashMap<String, EnumType>,
22}
23
24impl Default for Schema {
25 fn default() -> Self {
26 Self {
27 schema_name: None,
28 case_sensitive_text: true,
29 tables: Vec::new(),
30 views: Vec::new(),
31 functions: Vec::new(),
32 procedures: Vec::new(),
33 other_sql: Vec::new(),
34 table_map: HashMap::new(),
35 enum_types: HashMap::new(),
36 }
37 }
38}
39
40impl Schema {
41 pub fn new<S: Into<String>>(schema_name: Option<S>) -> Self {
42 Self {
43 schema_name: schema_name.map(|s| s.into()),
44 ..Default::default()
45 }
46 }
47
48 pub fn schema_name(&self) -> Option<&str> {
49 self.schema_name.as_deref()
50 }
51
52 pub fn case_sensitive_text(&self) -> bool {
53 self.case_sensitive_text
54 }
55
56 pub fn set_case_sensitive_text(&mut self, value: bool) {
57 self.case_sensitive_text = value;
58 }
59
60 pub fn tables(&self) -> &[Table] {
61 &self.tables
62 }
63
64 pub fn get_table(&self, name: &str) -> &Table {
65 let idx = self.table_index(name);
66 &self.tables[idx]
67 }
68
69 pub(crate) fn get_table_mut(&mut self, name: &str) -> &mut Table {
70 let idx = self.table_index(name);
71 &mut self.tables[idx]
72 }
73
74 fn table_index(&self, name: &str) -> usize {
75 let name_lower = name.to_lowercase();
76 *self.table_map.get(&name_lower)
77 .unwrap_or_else(|| panic!("Unable to locate a table with the name '{}'", name))
78 }
79
80 pub fn get_optional_table(&self, name: &str) -> Option<&Table> {
81 let name_lower = name.to_lowercase();
82 self.table_map.get(&name_lower).map(|&idx| &self.tables[idx])
83 }
84
85 pub fn all_views(&self) -> &[View] {
86 &self.views
87 }
88
89 pub fn views(&self, database_type: DatabaseType) -> Vec<View> {
90 self.views
91 .iter()
92 .filter(|view| view.database_type().is_none() || view.database_type().unwrap() == database_type)
93 .cloned()
94 .collect()
95 }
96
97 pub fn enum_types(&self) -> impl Iterator<Item = &EnumType> {
98 let mut enum_types: Vec<&EnumType> = self.enum_types.values().collect();
99 enum_types.sort_by(|a, b| a.name().cmp(b.name()));
100 enum_types.into_iter()
101 }
102
103 pub fn get_enum_type(&self, type_name: &str) -> &EnumType {
104 self.enum_types
105 .get(type_name)
106 .unwrap_or_else(|| panic!("Unable to locate an enum type with the name '{}'", type_name))
107 }
108
109 pub fn functions(&self) -> &[Function] {
110 &self.functions
111 }
112
113 pub fn procedures(&self) -> &[Procedure] {
114 &self.procedures
115 }
116
117 pub fn other_sql(&self) -> &[OtherSql] {
118 &self.other_sql
119 }
120
121 pub fn validate(&self) -> Vec<String> {
122 let mut errors: Vec<String> = Vec::new();
123 for table in &self.tables {
124 for relation in table.relations() {
125 if relation.relation_type() == RelationType::SetNull {
126 let from_table_name = relation.from_table_name().to_string();
127 let from_column_name = relation.from_column_name().to_string();
128 let from_table = self.get_table(&from_table_name);
129 if from_table.column(&from_column_name).is_required() {
130 errors.push(format!(
131 "ERROR: {}.{} is required. The {}.{} relation specifies setnull, which is not allowed",
132 from_table_name,
133 from_column_name,
134 relation.to_table_name(),
135 relation.to_column_name()
136 ));
137 }
138 }
139 }
140 }
141 errors
142 }
143
144 pub(crate) fn add_table(&mut self, table: Table) {
177 let idx = self.tables.len();
178 self.table_map.insert(table.name().to_lowercase(), idx);
179 self.tables.push(table);
180 }
181
182 pub fn sort_tables_by_name(&mut self) {
185 self.tables.sort_by(|a, b| a.name().cmp(b.name()));
186
187 self.table_map.clear();
188 for (idx, table) in self.tables.iter().enumerate() {
189 self.table_map.insert(table.name().to_lowercase(), idx);
190 }
191 }
192
193 pub(crate) fn add_view(&mut self, view: View) {
194 self.views.push(view);
195 }
196
197 pub(crate) fn add_enum_type(&mut self, enum_type: EnumType) {
198 self.enum_types
199 .insert(enum_type.name().to_string(), enum_type);
200 }
201
202 pub(crate) fn add_functions(&mut self, functions: Vec<Function>) {
203 self.functions.extend(functions);
204 }
205
206 pub(crate) fn add_procedures(&mut self, procedures: Vec<Procedure>) {
207 self.procedures.extend(procedures);
208 }
209
210 pub(crate) fn add_other_sql(&mut self, other_sql: OtherSql) {
211 self.other_sql.push(other_sql);
212 }
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218 use crate::model::column::Column;
219 use crate::model::column_type::ColumnType;
220 use crate::model::relation::Relation;
221
222 fn make_schema() -> Schema {
223 Schema::new(Some("schema"))
224 }
225
226 #[test]
227 fn add_and_get_table_and_sort() {
228 let mut schema = make_schema();
229 let table1 = Table::new(
230 Some("schema"),
231 "Table1",
232 Option::<&str>::None,
233 crate::model::types::LockEscalation::Auto,
234 false,
235 vec![Column::new(Some("s"), "id", ColumnType::Int, 0, 0, true)],
236 Vec::new(),
237 Vec::new(),
238 Vec::new(),
239 Vec::new(),
240 Vec::new(),
241 Vec::new(),
242 Vec::new(),
243 Vec::new(),
244 );
245 let table2 = Table::new(
246 Some("schema"),
247 "Table2",
248 Option::<&str>::None,
249 crate::model::types::LockEscalation::Auto,
250 false,
251 Vec::new(),
252 Vec::new(),
253 Vec::new(),
254 Vec::new(),
255 Vec::new(),
256 Vec::new(),
257 Vec::new(),
258 Vec::new(),
259 Vec::new(),
260 );
261 schema.add_table(table1);
262 schema.add_table(table2);
263 assert_eq!(schema.get_table("Table2").name(), "Table2"); let names: Vec<_> = schema.tables().iter().map(|t| t.name()).collect();
265 assert_eq!(names, vec!["Table1", "Table2"]);
266 assert_eq!(schema.get_table("Table1").name(), "Table1");
268 }
269
270 #[test]
271 fn views_filtered_by_database_type() {
272 let mut s = make_schema();
273 s.add_view(View::new(Some("s"), "v1", "sql1", Some(DatabaseType::Postgresql)));
274 s.add_view(View::new(Some("s"), "v2", "sql2", Some(DatabaseType::SqlServer)));
275 let pg = s.views(DatabaseType::Postgresql);
276 assert_eq!(pg.len(), 1);
277 assert_eq!(pg[0].name(), "v1");
278 }
279
280 #[test]
281 fn validate_setnull_error_when_required() {
282 let mut s = make_schema();
283 let parent = Table::new(
284 Some("s"),
285 "parent",
286 Option::<&str>::None,
287 crate::model::types::LockEscalation::Auto,
288 false,
289 vec![Column::new(Some("s"), "id", ColumnType::Int, 0, 0, true)],
290 Vec::new(),
291 Vec::new(),
292 Vec::new(),
293 Vec::new(),
294 Vec::new(),
295 Vec::new(),
296 Vec::new(),
297 Vec::new(),
298 );
299 s.add_table(parent);
300
301 let child = Table::new(
302 Some("s"),
303 "child",
304 Option::<&str>::None,
305 crate::model::types::LockEscalation::Auto,
306 false,
307 vec![Column::new(Some("s"), "pid", ColumnType::Int, 0, 0, true)],
308 Vec::new(),
309 Vec::new(),
310 vec![Relation::new(
311 "parent",
312 "id",
313 "child",
314 "pid",
315 RelationType::SetNull,
316 false,
317 )],
318 Vec::new(),
319 Vec::new(),
320 Vec::new(),
321 Vec::new(),
322 Vec::new(),
323 );
324 s.add_table(child);
325
326 let errors = s.validate();
327 assert_eq!(errors.len(), 1);
328 assert!(errors[0].contains("setnull"));
329 }
330
331 }