Skip to main content

schema_model/model/
table.rs

1use crate::model::aggregation::Aggregation;
2use crate::model::column::Column;
3use crate::model::column_type::ColumnType;
4use crate::model::constraint::Constraint;
5use crate::model::initial_data::InitialData;
6use crate::model::key::Key;
7use crate::model::relation::Relation;
8use crate::model::trigger::Trigger;
9use crate::model::types::{BooleanMode, DatabaseType, KeyType, LockEscalation, TableOption};
10use std::fmt;
11
12#[derive(Debug, Clone)]
13pub struct Table {
14    schema_name: Option<String>,
15    name: String,
16    export_date_column: Option<String>,
17    lock_escalation: LockEscalation,
18    no_export: bool,
19    columns: Vec<Column>,
20    keys: Vec<Key>,
21    indexes: Vec<Key>,
22    relations: Vec<Relation>,
23    reverse_relations: Vec<Relation>,
24    triggers: Vec<Trigger>,
25    constraints: Vec<Constraint>,
26    initial_data: Vec<InitialData>,
27    options: Vec<TableOption>,
28    aggregations: Vec<Aggregation>,
29}
30
31impl Table {
32    #[allow(clippy::too_many_arguments)]
33    pub fn new<S: Into<String>>(
34        schema_name: Option<S>,
35        name: S,
36        export_date_column: Option<S>,
37        lock_escalation: LockEscalation,
38        no_export: bool,
39        columns: Vec<Column>,
40        keys: Vec<Key>,
41        indexes: Vec<Key>,
42        relations: Vec<Relation>,
43        triggers: Vec<Trigger>,
44        constraints: Vec<Constraint>,
45        initial_data: Vec<InitialData>,
46        options: Vec<TableOption>,
47        aggregations: Vec<Aggregation>,
48    ) -> Self {
49        Self {
50            schema_name: schema_name.map(|s| s.into()),
51            name: name.into(),
52            export_date_column: export_date_column.map(|s| s.into()),
53            lock_escalation,
54            no_export,
55            columns,
56            keys,
57            indexes,
58            relations,
59            reverse_relations: Vec::new(),
60            triggers,
61            constraints,
62            initial_data,
63            options,
64            aggregations,
65        }
66    }
67
68    pub fn schema_name(&self) -> Option<&str> {
69        self.schema_name.as_deref()
70    }
71
72    pub fn name(&self) -> &str {
73        &self.name
74    }
75
76    pub fn export_date_column(&self) -> Option<&str> {
77        self.export_date_column.as_deref()
78    }
79
80    pub fn lock_escalation(&self) -> LockEscalation {
81        self.lock_escalation
82    }
83
84    pub fn is_no_export(&self) -> bool {
85        self.no_export
86    }
87
88    pub fn columns(&self) -> &[Column] {
89        &self.columns
90    }
91
92    pub fn keys(&self) -> &[Key] {
93        &self.keys
94    }
95
96    pub fn indexes(&self) -> &[Key] {
97        &self.indexes
98    }
99
100    pub fn relations(&self) -> &[Relation] {
101        &self.relations
102    }
103
104    pub fn reverse_relations(&self) -> &[Relation] {
105        &self.reverse_relations
106    }
107
108    pub fn triggers(&self) -> &[Trigger] {
109        &self.triggers
110    }
111
112    pub fn constraints(&self) -> &[Constraint] {
113        &self.constraints
114    }
115
116    pub fn initial_data(&self) -> &[InitialData] {
117        &self.initial_data
118    }
119
120    pub fn options(&self) -> &[TableOption] {
121        &self.options
122    }
123
124    pub fn aggregations(&self) -> &[Aggregation] {
125        &self.aggregations
126    }
127
128    pub fn column(&self, column_name: &str) -> &Column {
129        let lower = column_name.to_lowercase();
130        self.columns
131            .iter()
132            .find(|c| c.name().eq_ignore_ascii_case(&lower))
133            .unwrap_or_else(|| {
134                panic!(
135                    "Unable to locate a column with the name '{}' in table '{}'",
136                    column_name, self.name
137                )
138            })
139    }
140
141    pub fn primary_key(&self) -> Option<&Key> {
142        self.keys.iter().find(|k| k.key_type() == KeyType::Primary)
143    }
144
145    pub fn has_column(&self, column_name: &str) -> bool {
146        let lower = column_name.to_lowercase();
147        self.columns
148            .iter()
149            .any(|c| c.name().eq_ignore_ascii_case(&lower))
150    }
151
152    pub fn identity_column(&self) -> Option<&Column> {
153        self.columns.iter().find(|c| {
154            let t = c.column_type();
155            matches!(t, ColumnType::Sequence | ColumnType::LongSequence)
156        })
157    }
158
159    pub fn primary_key_columns(&self) -> Option<Vec<String>> {
160        self.primary_key()
161            .map(|k| k.columns().iter().map(|kc| kc.name().to_string()).collect())
162    }
163
164    pub fn has_option(&self, option: TableOption) -> bool {
165        self.options.iter().any(|o| *o == option)
166    }
167
168    pub fn has_column_constraints(&self, boolean_mode: BooleanMode) -> bool {
169        self.columns
170            .iter()
171            .any(|c| c.needs_check_constraints(boolean_mode))
172    }
173
174    pub fn columns_with_check_constraints(&self, boolean_mode: BooleanMode) -> Vec<Column> {
175        self.columns
176            .iter()
177            .filter(|c| c.needs_check_constraints(boolean_mode))
178            .cloned()
179            .collect()
180    }
181
182    pub fn column_relation(&self, column: &Column) -> Option<&Relation> {
183        let name = column.name();
184        self.relations
185            .iter()
186            .find(|r| r.from_column_name().eq_ignore_ascii_case(name))
187    }
188
189    pub fn fully_qualified_table_name(&self, database_type: DatabaseType) -> String {
190        database_type.qualified_name(self.schema_name(), self.name())
191    }
192
193    pub fn add_reverse_relation(&mut self, relation: Relation) {
194        self.reverse_relations.push(relation);
195    }
196}
197
198impl fmt::Display for Table {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        match &self.schema_name {
201            Some(schema) => write!(f, "{}.{}", schema, self.name),
202            None => write!(f, "{}", self.name),
203        }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    use super::*;
210    use crate::model::types::LockEscalation;
211
212    fn sample_table() -> Table {
213        Table::new(
214            Some("schema"),
215            "table",
216            Option::<&str>::None,
217            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    }
230
231    #[test]
232    fn constructor_and_basic_getters() {
233        let t = sample_table();
234        assert_eq!(t.schema_name().unwrap(), "schema");
235        assert_eq!(t.name(), "table");
236        assert_eq!(t.export_date_column(), None);
237        assert_eq!(t.lock_escalation(), LockEscalation::Auto);
238        assert!(!t.is_no_export());
239        assert_eq!(format!("{}", t), "schema.table");
240    }
241
242    #[test]
243    fn fully_qualified_table_name_uses_explicit_schema() {
244        let t = sample_table();
245        assert_eq!(t.fully_qualified_table_name(DatabaseType::Postgresql), "schema.table");
246        assert_eq!(t.fully_qualified_table_name(DatabaseType::SqlServer), "schema.table");
247    }
248
249    #[test]
250    fn fully_qualified_table_name_falls_back_to_default_schema() {
251        let mut t = sample_table();
252        t.schema_name = None;
253        assert_eq!(t.fully_qualified_table_name(DatabaseType::Postgresql), "public.table");
254        assert_eq!(t.fully_qualified_table_name(DatabaseType::SqlServer), "dbo.table");
255        assert_eq!(t.fully_qualified_table_name(DatabaseType::Sqlite), "table");
256    }
257}