Skip to main content

schema_sql_generator/common/
table_generator.rs

1use crate::common::column_constraint_generator::ColumnConstraintGenerator;
2use crate::common::column_generator::ColumnGenerator;
3use crate::common::generator_context::GeneratorContext;
4use crate::common::index_generator::IndexGenerator;
5use crate::common::key_generator::KeyGenerator;
6use crate::common::table_constraint_generator::TableConstraintGenerator;
7use crate::{sql_newline, sql_print, sql_println};
8use schema_model::model::database_model::DatabaseModel;
9use schema_model::model::table::Table;
10use schema_model::model::types::DatabaseType;
11use std::collections::{HashMap, HashSet, VecDeque};
12
13pub trait TableGenerator {
14    fn output_tables(&self);
15    fn output_table(&self, table: &Table);
16    fn output_table_drop(&self, table: &Table);
17    fn output_table_header(&self, table: &Table);
18    fn output_table_definition(&self, table: &Table);
19    fn output_table_footer(&self, table: &Table);
20    fn output_indexes(&self, table: &Table);
21    fn output_initial_data(&self, table: &Table);
22}
23
24/// Returns every table across all schemas, ordered so that a table with a foreign key
25/// to another table is listed before it (children before parents - the reverse of
26/// dependency order).
27///
28/// Used to emit all `drop table` statements up front instead of interleaved with each
29/// table's own `create` (H17): dropping in declaration order can try to drop a table
30/// that another, not-yet-dropped table still holds a foreign key to, which fails on
31/// SQL Server and SQLite (PostgreSQL is unaffected - its drop uses `cascade`).
32///
33/// A table caught in a dependency cycle (mutually-referencing foreign keys) falls back
34/// to declaration order for the tables in that cycle - no ordering satisfies a cycle,
35/// and this at least matches the pre-fix behavior instead of looping forever.
36pub fn tables_in_drop_order(database_model: &DatabaseModel) -> Vec<&Table> {
37    let tables = database_model.all_tables();
38    let table_count = tables.len();
39
40    let index_of_table: HashMap<*const Table, usize> = tables
41        .iter()
42        .enumerate()
43        .map(|(index, table)| (*table as *const Table, index))
44        .collect();
45
46    let mut in_degree = vec![0usize; table_count];
47    let mut successors: Vec<Vec<usize>> = vec![Vec::new(); table_count];
48
49    for (child_index, table) in tables.iter().enumerate() {
50        for relation in table.relations() {
51            let Some(parent_table) = database_model.find_table_by_qualified_name_checked(relation.to_table_name()) else {
52                continue;
53            };
54            let Some(&parent_index) = index_of_table.get(&(parent_table as *const Table)) else {
55                continue;
56            };
57
58            if parent_index == child_index {
59                continue; // self-referencing FK - a single drop handles both sides
60            }
61
62            successors[child_index].push(parent_index);
63            in_degree[parent_index] += 1;
64        }
65    }
66
67    let mut queue: VecDeque<usize> = (0..table_count).filter(|&index| in_degree[index] == 0).collect();
68    let mut order = Vec::with_capacity(table_count);
69
70    while let Some(index) = queue.pop_front() {
71        order.push(index);
72
73        for &successor in &successors[index] {
74            in_degree[successor] -= 1;
75
76            if in_degree[successor] == 0 {
77                queue.push_back(successor);
78            }
79        }
80    }
81
82    if order.len() < table_count {
83        let already_ordered: HashSet<usize> = order.iter().copied().collect();
84        order.extend((0..table_count).filter(|index| !already_ordered.contains(index)));
85    }
86
87    order.into_iter().map(|index| tables[index]).collect()
88}
89
90pub struct DefaultTableGenerator {
91    context: GeneratorContext,
92    column_generator: Box<dyn ColumnGenerator>,
93    key_generator: Box<dyn KeyGenerator>,
94    column_constraint_generator: Box<dyn ColumnConstraintGenerator>,
95    table_constraint_generator: Box<dyn TableConstraintGenerator>,
96    index_generator: Box<dyn IndexGenerator>,
97}
98
99impl DefaultTableGenerator {
100    pub fn new(
101        context: GeneratorContext,
102        column_generator: Box<dyn ColumnGenerator>,
103        key_generator: Box<dyn KeyGenerator>,
104        column_constraint_generator: Box<dyn ColumnConstraintGenerator>,
105        table_constraint_generator: Box<dyn TableConstraintGenerator>,
106        index_generator: Box<dyn IndexGenerator>,
107    ) -> Self {
108        Self {
109            column_generator,
110            key_generator,
111            column_constraint_generator,
112            table_constraint_generator,
113            index_generator,
114            context,
115        }
116    }
117
118    /// Same as `output_table_definition`, but appends `extra` definition clauses
119    /// (e.g. dialect-specific inline foreign key constraints) to the comma-separated
120    /// list before printing.
121    pub fn output_table_definition_with_extra(&self, table: &Table, extra: Vec<String>) {
122        let table_definitions: Vec<String> = self.column_generator.column_definitions(table)
123            .into_iter()
124            .chain(self.key_generator.key_constraints(table))
125            .chain(self.column_constraint_generator.column_check_constraints(table))
126            .chain(self.table_constraint_generator.table_check_constraints(table))
127            .chain(extra)
128            .filter(|sql| !sql.is_empty())
129            .collect();
130
131        self.context.with_writer(|writer| {
132            for (i, sql) in table_definitions.iter().enumerate() {
133                sql_print!(writer, "{}", sql);
134
135                if i < table_definitions.len() - 1 {
136                    sql_print!(writer, ",");
137                }
138
139                sql_newline!(writer);
140            }
141        });
142    }
143}
144
145impl TableGenerator for DefaultTableGenerator {
146    fn output_tables(&self) {
147        let database_model = self.context.settings().database_model();
148
149        // All drops up front, in reverse-dependency order, rather than interleaved with
150        // each table's own create (H17) - see `tables_in_drop_order`.
151        for table in tables_in_drop_order(database_model) {
152            self.output_table_drop(table);
153        }
154
155        for schema in database_model.schemas() {
156            for table in schema.tables() {
157                self.output_table_header(table);
158                self.output_table_definition(table);
159                self.output_table_footer(table);
160                self.output_indexes(table);
161                self.output_initial_data(table);
162            };
163        }
164    }
165
166
167    fn output_table(&self, table: &Table) {
168        self.output_table_drop(table);
169        self.output_table_header(table);
170        self.output_table_definition(table);
171        self.output_table_footer(table);
172        self.output_indexes(table);
173        self.output_initial_data(table);
174    }
175
176    fn output_table_drop(&self, table: &Table) {
177        let is_postgres = self.context.settings().database_type() == DatabaseType::Postgresql;
178        let cascade_suffix = if is_postgres { " cascade" } else { "" };
179        let separator = self.context.settings().statement_separator().to_string();
180        let fully_qualified_table_name = table.fully_qualified_table_name(self.context.settings().database_type());
181
182        self.context.with_writer(|writer| {
183            if is_postgres {
184                sql_println!(writer, "/* {} */", fully_qualified_table_name);
185                sql_println!(writer, "drop table if exists {}{}{}", fully_qualified_table_name, cascade_suffix, separator);
186                sql_println!(writer, "");
187            } else {
188                sql_println!(writer, "drop table if exists {}{}{}", fully_qualified_table_name, cascade_suffix, separator);
189                sql_println!(writer, "/* {} */", fully_qualified_table_name);
190            }
191        });
192    }
193
194    fn output_table_header(&self, table: &Table) {
195        let fully_qualified_table_name = table.fully_qualified_table_name(self.context.settings().database_type());
196
197        self.context.with_writer(|writer| {
198            sql_println!(writer, "create table {}", fully_qualified_table_name);
199            sql_println!(writer, "(");
200        });
201    }
202
203    fn output_table_definition(&self, table: &Table) {
204        self.output_table_definition_with_extra(table, Vec::new());
205    }
206
207    fn output_table_footer(&self, _table: &Table) {
208        self.context.with_writer(|writer| {
209            sql_println!(writer, "){}", self.context.settings().statement_separator());
210            sql_newline!(writer);
211        });
212    }
213
214    fn output_indexes(&self, table: &Table) {
215        self.context.with_writer(|writer| {
216            self.index_generator.output_indexes_for_table(writer, table);
217        });
218    }
219
220    fn output_initial_data(&self, table: &Table) {
221        let initial_data = table.initial_data()
222            .iter()
223            .filter(|it| { it.database_type().is_none() || it.database_type().unwrap() == self.context.settings().database_type() })
224            .collect::<Vec<_>>();
225
226        if !initial_data.is_empty() {
227            self.context.with_writer(|writer| {
228                initial_data.iter().for_each(|it| {
229                    sql_println!(writer, "{}{}", it.sql(), self.context.settings().statement_separator());
230                });
231
232                writer.newline();
233            });
234        }
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use crate::common::column_generator::ColumnGenerator;
242    use crate::common::index_generator::IndexGenerator;
243    use crate::common::key_generator::KeyGenerator;
244    use crate::common::table_constraint_generator::TableConstraintGenerator;
245    use crate::common::test_support::make_context;
246    use schema_model::builder::{SchemaBuilder, TableBuilder};
247    use schema_model::model::column::Column;
248    use schema_model::model::database_model::DatabaseModel;
249    use schema_model::model::initial_data::InitialData;
250    use schema_model::model::key::Key;
251    use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode};
252
253    struct NoopColumnGenerator;
254    impl ColumnGenerator for NoopColumnGenerator {
255        fn column_definitions(&self, _table: &Table) -> Vec<String> { Vec::new() }
256        fn column_sql(&self, _table: &Table, _column: &Column) -> String { String::new() }
257        fn column_options(&self, _table: &Table, _column: &Column) -> String { String::new() }
258        fn default_value(&self, _table: &Table, _column: &Column) -> Option<String> { None }
259    }
260
261    struct NoopKeyGenerator;
262    impl KeyGenerator for NoopKeyGenerator {
263        fn key_constraints(&self, _table: &Table) -> Vec<String> { Vec::new() }
264    }
265
266    struct NoopColumnConstraintGenerator;
267    impl ColumnConstraintGenerator for NoopColumnConstraintGenerator {
268        fn column_check_constraints(&self, _table: &Table) -> Vec<String> { Vec::new() }
269    }
270
271    /// Reproduces H6: a constraint generator that produces an empty string for a column
272    /// that was flagged as needing a check constraint but ultimately has none (e.g. a
273    /// Boolean column with `min`/`max` set under `BooleanMode::Native`).
274    struct EmptyStringColumnConstraintGenerator;
275    impl ColumnConstraintGenerator for EmptyStringColumnConstraintGenerator {
276        fn column_check_constraints(&self, _table: &Table) -> Vec<String> { vec![String::new()] }
277    }
278
279    struct NoopTableConstraintGenerator;
280    impl TableConstraintGenerator for NoopTableConstraintGenerator {
281        fn table_check_constraints(&self, _table: &Table) -> Vec<String> { Vec::new() }
282    }
283
284    struct NoopIndexGenerator;
285    impl IndexGenerator for NoopIndexGenerator {
286        fn output_indexes(&self) {}
287        fn output_indexes_for_table(&self, _writer: &mut crate::common::sql_writer::SqlWriter, _table: &Table) {}
288        fn output_index(&self, _writer: &mut crate::common::sql_writer::SqlWriter, _statement_separator: &str, _table: &Table, _key_name: &str, _key: &Key) {}
289        fn index_options(&self, _key: &Key) -> Option<String> { None }
290    }
291
292    fn make_generator(context: GeneratorContext) -> DefaultTableGenerator {
293        DefaultTableGenerator::new(
294            context,
295            Box::new(NoopColumnGenerator),
296            Box::new(NoopKeyGenerator),
297            Box::new(NoopColumnConstraintGenerator),
298            Box::new(NoopTableConstraintGenerator),
299            Box::new(NoopIndexGenerator),
300        )
301    }
302
303    #[test]
304    fn output_initial_data_includes_rows_for_current_database_type_or_unspecified() {
305        let table = TableBuilder::new(None::<&str>, "users")
306            .add_initial_data(InitialData::new("insert into users values (1)", None))
307            .add_initial_data(InitialData::new("insert into users values (2)", Some(DatabaseType::Sqlite)))
308            .add_initial_data(InitialData::new("insert into users values (3)", Some(DatabaseType::Postgresql)))
309            .build();
310        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
311        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
312        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
313
314        let generator = make_generator(ctx);
315        generator.output_initial_data(&table);
316
317        let output = buffer.contents();
318        assert!(output.contains("insert into users values (1)"));
319        assert!(output.contains("insert into users values (2)"));
320        assert!(!output.contains("insert into users values (3)"));
321    }
322
323    #[test]
324    fn output_initial_data_writes_nothing_when_table_has_no_rows() {
325        let table = TableBuilder::new(None::<&str>, "users").build();
326        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
327        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
328        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
329
330        let generator = make_generator(ctx);
331        generator.output_initial_data(&table);
332
333        assert_eq!(buffer.contents(), "");
334    }
335
336    #[test]
337    fn output_table_runs_all_steps_in_order() {
338        let table = TableBuilder::new(None::<&str>, "users")
339            .add_initial_data(InitialData::new("insert into users values (1)", None))
340            .build();
341        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
342        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
343        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
344
345        let generator = make_generator(ctx);
346        generator.output_table(&table);
347
348        let output = buffer.contents();
349        let header_pos = output.find("create table users").unwrap();
350        let footer_pos = output.find(")").unwrap();
351        let data_pos = output.find("insert into users values (1)").unwrap();
352        assert!(header_pos < footer_pos);
353        assert!(footer_pos < data_pos);
354    }
355
356    #[test]
357    fn output_table_definition_drops_empty_constraint_strings() {
358        let table = TableBuilder::new(None::<&str>, "orders").build();
359        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
360        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
361        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
362
363        let generator = DefaultTableGenerator::new(
364            ctx,
365            Box::new(NoopColumnGenerator),
366            Box::new(NoopKeyGenerator),
367            Box::new(EmptyStringColumnConstraintGenerator),
368            Box::new(NoopTableConstraintGenerator),
369            Box::new(NoopIndexGenerator),
370        );
371        generator.output_table_definition(&table);
372
373        let output = buffer.contents();
374        // No stray leading comma and no blank line between "(" and ")" from the empty entry.
375        assert!(!output.contains(","));
376        assert!(!output.contains("\n\n"));
377    }
378
379    fn table_names(tables: Vec<&Table>) -> Vec<String> {
380        tables.iter().map(|t| t.name().to_string()).collect()
381    }
382
383    #[test]
384    fn tables_in_drop_order_puts_child_before_parent() {
385        use schema_model::model::relation::Relation;
386        use schema_model::model::types::RelationType;
387
388        // Declared in create order (parent before the child that references it) -
389        // drop order must be the reverse.
390        let parent = TableBuilder::new(None::<&str>, "parent").build();
391        let child = TableBuilder::new(None::<&str>, "child")
392            .add_relation(Relation::new("parent", "id", "child", "parent_id", RelationType::Cascade, false))
393            .build();
394        let schema = SchemaBuilder::new(None::<&str>).add_table(parent).add_table(child).build();
395        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
396
397        assert_eq!(table_names(tables_in_drop_order(&model)), vec!["child", "parent"]);
398    }
399
400    #[test]
401    fn tables_in_drop_order_handles_chain_of_three() {
402        use schema_model::model::relation::Relation;
403        use schema_model::model::types::RelationType;
404
405        let grandparent = TableBuilder::new(None::<&str>, "grandparent").build();
406        let parent = TableBuilder::new(None::<&str>, "parent")
407            .add_relation(Relation::new("grandparent", "id", "parent", "grandparent_id", RelationType::Cascade, false))
408            .build();
409        let child = TableBuilder::new(None::<&str>, "child")
410            .add_relation(Relation::new("parent", "id", "child", "parent_id", RelationType::Cascade, false))
411            .build();
412        let schema = SchemaBuilder::new(None::<&str>)
413            .add_table(grandparent)
414            .add_table(parent)
415            .add_table(child)
416            .build();
417        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
418
419        assert_eq!(table_names(tables_in_drop_order(&model)), vec!["child", "parent", "grandparent"]);
420    }
421
422    #[test]
423    fn tables_in_drop_order_ignores_self_referencing_relation() {
424        use schema_model::model::relation::Relation;
425        use schema_model::model::types::RelationType;
426
427        // e.g. employee.manager_id -> employee.id - must not be treated as a cycle
428        // against itself (which would leave it stuck with a permanent in-degree).
429        let employee = TableBuilder::new(None::<&str>, "employee")
430            .add_relation(Relation::new("employee", "id", "employee", "manager_id", RelationType::SetNull, false))
431            .build();
432        let schema = SchemaBuilder::new(None::<&str>).add_table(employee).build();
433        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
434
435        assert_eq!(table_names(tables_in_drop_order(&model)), vec!["employee"]);
436    }
437
438    #[test]
439    fn tables_in_drop_order_falls_back_to_declaration_order_on_a_cycle() {
440        use schema_model::model::relation::Relation;
441        use schema_model::model::types::RelationType;
442
443        // "a" references "b" and "b" references "a" - no ordering satisfies both, so
444        // this must not panic or loop forever, and should fall back predictably.
445        let a = TableBuilder::new(None::<&str>, "a")
446            .add_relation(Relation::new("b", "id", "a", "b_id", RelationType::SetNull, false))
447            .build();
448        let b = TableBuilder::new(None::<&str>, "b")
449            .add_relation(Relation::new("a", "id", "b", "a_id", RelationType::SetNull, false))
450            .build();
451        let schema = SchemaBuilder::new(None::<&str>).add_table(a).add_table(b).build();
452        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
453
454        assert_eq!(table_names(tables_in_drop_order(&model)), vec!["a", "b"]);
455    }
456}