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) {
145 let idx = self.tables.len();
146 self.table_map.insert(table.name().to_lowercase(), idx);
147 self.tables.push(table);
148 }
149
150 pub fn sort_tables_by_name(&mut self) {
153 self.tables.sort_by(|a, b| a.name().cmp(b.name()));
154
155 self.table_map.clear();
156 for (idx, table) in self.tables.iter().enumerate() {
157 self.table_map.insert(table.name().to_lowercase(), idx);
158 }
159 }
160
161 pub(crate) fn add_view(&mut self, view: View) {
162 self.views.push(view);
163 }
164
165 pub(crate) fn add_enum_type(&mut self, enum_type: EnumType) {
166 self.enum_types
167 .insert(enum_type.name().to_string(), enum_type);
168 }
169
170 pub(crate) fn add_functions(&mut self, functions: Vec<Function>) {
171 self.functions.extend(functions);
172 }
173
174 pub(crate) fn add_procedures(&mut self, procedures: Vec<Procedure>) {
175 self.procedures.extend(procedures);
176 }
177
178 pub(crate) fn add_other_sql(&mut self, other_sql: OtherSql) {
179 self.other_sql.push(other_sql);
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186 use crate::model::column::Column;
187 use crate::model::column_type::ColumnType;
188 use crate::model::relation::Relation;
189
190 fn make_schema() -> Schema {
191 Schema::new(Some("schema"))
192 }
193
194 #[test]
195 fn add_and_get_table_and_sort() {
196 let mut schema = make_schema();
197 let table1 = Table::new(
198 Some("schema"),
199 "Table1",
200 Option::<&str>::None,
201 crate::model::types::LockEscalation::Auto,
202 false,
203 vec![Column::new(Some("s"), "id", ColumnType::Int, 0, 0, true)],
204 Vec::new(),
205 Vec::new(),
206 Vec::new(),
207 Vec::new(),
208 Vec::new(),
209 Vec::new(),
210 Vec::new(),
211 Vec::new(),
212 );
213 let table2 = Table::new(
214 Some("schema"),
215 "Table2",
216 Option::<&str>::None,
217 crate::model::types::LockEscalation::Auto,
218 false,
219 Vec::new(),
220 Vec::new(),
221 Vec::new(),
222 Vec::new(),
223 Vec::new(),
224 Vec::new(),
225 Vec::new(),
226 Vec::new(),
227 Vec::new(),
228 );
229 schema.add_table(table1);
230 schema.add_table(table2);
231 assert_eq!(schema.get_table("Table2").name(), "Table2"); let names: Vec<_> = schema.tables().iter().map(|t| t.name()).collect();
233 assert_eq!(names, vec!["Table1", "Table2"]);
234 assert_eq!(schema.get_table("Table1").name(), "Table1");
236 }
237
238 #[test]
239 fn views_filtered_by_database_type() {
240 let mut s = make_schema();
241 s.add_view(View::new(Some("s"), "v1", "sql1", Some(DatabaseType::Postgresql)));
242 s.add_view(View::new(Some("s"), "v2", "sql2", Some(DatabaseType::SqlServer)));
243 let pg = s.views(DatabaseType::Postgresql);
244 assert_eq!(pg.len(), 1);
245 assert_eq!(pg[0].name(), "v1");
246 }
247
248 #[test]
249 fn validate_setnull_error_when_required() {
250 let mut s = make_schema();
251 let parent = Table::new(
252 Some("s"),
253 "parent",
254 Option::<&str>::None,
255 crate::model::types::LockEscalation::Auto,
256 false,
257 vec![Column::new(Some("s"), "id", ColumnType::Int, 0, 0, true)],
258 Vec::new(),
259 Vec::new(),
260 Vec::new(),
261 Vec::new(),
262 Vec::new(),
263 Vec::new(),
264 Vec::new(),
265 Vec::new(),
266 );
267 s.add_table(parent);
268
269 let child = Table::new(
270 Some("s"),
271 "child",
272 Option::<&str>::None,
273 crate::model::types::LockEscalation::Auto,
274 false,
275 vec![Column::new(Some("s"), "pid", ColumnType::Int, 0, 0, true)],
276 Vec::new(),
277 Vec::new(),
278 vec![Relation::new(
279 "parent",
280 "id",
281 "child",
282 "pid",
283 RelationType::SetNull,
284 false,
285 )],
286 Vec::new(),
287 Vec::new(),
288 Vec::new(),
289 Vec::new(),
290 Vec::new(),
291 );
292 s.add_table(child);
293
294 let errors = s.validate();
295 assert_eq!(errors.len(), 1);
296 assert!(errors[0].contains("setnull"));
297 }
298
299 }