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) =
52                database_model.find_table_by_qualified_name_checked(relation.to_table_name())
53            else {
54                continue;
55            };
56            let Some(&parent_index) = index_of_table.get(&(parent_table as *const Table)) else {
57                continue;
58            };
59
60            if parent_index == child_index {
61                continue; // self-referencing FK - a single drop handles both sides
62            }
63
64            successors[child_index].push(parent_index);
65            in_degree[parent_index] += 1;
66        }
67    }
68
69    let mut queue: VecDeque<usize> = (0..table_count)
70        .filter(|&index| in_degree[index] == 0)
71        .collect();
72    let mut order = Vec::with_capacity(table_count);
73
74    while let Some(index) = queue.pop_front() {
75        order.push(index);
76
77        for &successor in &successors[index] {
78            in_degree[successor] -= 1;
79
80            if in_degree[successor] == 0 {
81                queue.push_back(successor);
82            }
83        }
84    }
85
86    if order.len() < table_count {
87        let already_ordered: HashSet<usize> = order.iter().copied().collect();
88        order.extend((0..table_count).filter(|index| !already_ordered.contains(index)));
89    }
90
91    order.into_iter().map(|index| tables[index]).collect()
92}
93
94pub struct DefaultTableGenerator {
95    context: GeneratorContext,
96    column_generator: Box<dyn ColumnGenerator>,
97    key_generator: Box<dyn KeyGenerator>,
98    column_constraint_generator: Box<dyn ColumnConstraintGenerator>,
99    table_constraint_generator: Box<dyn TableConstraintGenerator>,
100    index_generator: Box<dyn IndexGenerator>,
101}
102
103impl DefaultTableGenerator {
104    pub fn new(
105        context: GeneratorContext,
106        column_generator: Box<dyn ColumnGenerator>,
107        key_generator: Box<dyn KeyGenerator>,
108        column_constraint_generator: Box<dyn ColumnConstraintGenerator>,
109        table_constraint_generator: Box<dyn TableConstraintGenerator>,
110        index_generator: Box<dyn IndexGenerator>,
111    ) -> Self {
112        Self {
113            column_generator,
114            key_generator,
115            column_constraint_generator,
116            table_constraint_generator,
117            index_generator,
118            context,
119        }
120    }
121
122    /// Same as `output_table_definition`, but appends `extra` definition clauses
123    /// (e.g. dialect-specific inline foreign key constraints) to the comma-separated
124    /// list before printing.
125    pub fn output_table_definition_with_extra(&self, table: &Table, extra: Vec<String>) {
126        let table_definitions: Vec<String> = self
127            .column_generator
128            .column_definitions(table)
129            .into_iter()
130            .chain(self.key_generator.key_constraints(table))
131            .chain(
132                self.column_constraint_generator
133                    .column_check_constraints(table),
134            )
135            .chain(
136                self.table_constraint_generator
137                    .table_check_constraints(table),
138            )
139            .chain(extra)
140            .filter(|sql| !sql.is_empty())
141            .collect();
142
143        self.context.with_writer(|writer| {
144            for (i, sql) in table_definitions.iter().enumerate() {
145                sql_print!(writer, "{}", sql);
146
147                if i < table_definitions.len() - 1 {
148                    sql_print!(writer, ",");
149                }
150
151                sql_newline!(writer);
152            }
153        });
154    }
155}
156
157impl TableGenerator for DefaultTableGenerator {
158    fn output_tables(&self) {
159        let database_model = self.context.settings().database_model();
160
161        // All drops up front, in reverse-dependency order, rather than interleaved with
162        // each table's own create (H17) - see `tables_in_drop_order`.
163        for table in tables_in_drop_order(database_model) {
164            self.output_table_drop(table);
165        }
166
167        for schema in database_model.schemas() {
168            for table in schema.tables() {
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    }
177
178    fn output_table(&self, table: &Table) {
179        self.output_table_drop(table);
180        self.output_table_header(table);
181        self.output_table_definition(table);
182        self.output_table_footer(table);
183        self.output_indexes(table);
184        self.output_initial_data(table);
185    }
186
187    fn output_table_drop(&self, table: &Table) {
188        let is_postgres = self.context.settings().database_type() == DatabaseType::Postgresql;
189        let cascade_suffix = if is_postgres { " cascade" } else { "" };
190        let separator = self.context.settings().statement_separator().to_string();
191        let fully_qualified_table_name =
192            table.fully_qualified_table_name(self.context.settings().database_type());
193
194        self.context.with_writer(|writer| {
195            if is_postgres {
196                sql_println!(writer, "/* {} */", fully_qualified_table_name);
197                sql_println!(
198                    writer,
199                    "drop table if exists {}{}{}",
200                    fully_qualified_table_name,
201                    cascade_suffix,
202                    separator
203                );
204                sql_println!(writer, "");
205            } else {
206                sql_println!(
207                    writer,
208                    "drop table if exists {}{}{}",
209                    fully_qualified_table_name,
210                    cascade_suffix,
211                    separator
212                );
213                sql_println!(writer, "/* {} */", fully_qualified_table_name);
214            }
215        });
216    }
217
218    fn output_table_header(&self, table: &Table) {
219        let fully_qualified_table_name =
220            table.fully_qualified_table_name(self.context.settings().database_type());
221
222        self.context.with_writer(|writer| {
223            sql_println!(writer, "create table {}", fully_qualified_table_name);
224            sql_println!(writer, "(");
225        });
226    }
227
228    fn output_table_definition(&self, table: &Table) {
229        self.output_table_definition_with_extra(table, Vec::new());
230    }
231
232    fn output_table_footer(&self, _table: &Table) {
233        self.context.with_writer(|writer| {
234            sql_println!(writer, "){}", self.context.settings().statement_separator());
235            sql_newline!(writer);
236        });
237    }
238
239    fn output_indexes(&self, table: &Table) {
240        self.context.with_writer(|writer| {
241            self.index_generator.output_indexes_for_table(writer, table);
242        });
243    }
244
245    fn output_initial_data(&self, table: &Table) {
246        let initial_data = table
247            .initial_data()
248            .iter()
249            .filter(|it| {
250                it.database_type().is_none()
251                    || it.database_type().unwrap() == self.context.settings().database_type()
252            })
253            .collect::<Vec<_>>();
254
255        if !initial_data.is_empty() {
256            self.context.with_writer(|writer| {
257                initial_data.iter().for_each(|it| {
258                    sql_println!(
259                        writer,
260                        "{}{}",
261                        it.sql(),
262                        self.context.settings().statement_separator()
263                    );
264                });
265
266                writer.newline();
267            });
268        }
269    }
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use crate::common::column_generator::ColumnGenerator;
276    use crate::common::index_generator::IndexGenerator;
277    use crate::common::key_generator::KeyGenerator;
278    use crate::common::table_constraint_generator::TableConstraintGenerator;
279    use crate::common::test_support::make_context;
280    use schema_model::builder::{SchemaBuilder, TableBuilder};
281    use schema_model::model::column::Column;
282    use schema_model::model::database_model::DatabaseModel;
283    use schema_model::model::initial_data::InitialData;
284    use schema_model::model::key::Key;
285    use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode};
286
287    struct NoopColumnGenerator;
288    impl ColumnGenerator for NoopColumnGenerator {
289        fn column_definitions(&self, _table: &Table) -> Vec<String> {
290            Vec::new()
291        }
292        fn column_sql(&self, _table: &Table, _column: &Column) -> String {
293            String::new()
294        }
295        fn column_options(&self, _table: &Table, _column: &Column) -> String {
296            String::new()
297        }
298        fn default_value(&self, _table: &Table, _column: &Column) -> Option<String> {
299            None
300        }
301    }
302
303    struct NoopKeyGenerator;
304    impl KeyGenerator for NoopKeyGenerator {
305        fn key_constraints(&self, _table: &Table) -> Vec<String> {
306            Vec::new()
307        }
308    }
309
310    struct NoopColumnConstraintGenerator;
311    impl ColumnConstraintGenerator for NoopColumnConstraintGenerator {
312        fn column_check_constraints(&self, _table: &Table) -> Vec<String> {
313            Vec::new()
314        }
315    }
316
317    /// Reproduces H6: a constraint generator that produces an empty string for a column
318    /// that was flagged as needing a check constraint but ultimately has none (e.g. a
319    /// Boolean column with `min`/`max` set under `BooleanMode::Native`).
320    struct EmptyStringColumnConstraintGenerator;
321    impl ColumnConstraintGenerator for EmptyStringColumnConstraintGenerator {
322        fn column_check_constraints(&self, _table: &Table) -> Vec<String> {
323            vec![String::new()]
324        }
325    }
326
327    struct NoopTableConstraintGenerator;
328    impl TableConstraintGenerator for NoopTableConstraintGenerator {
329        fn table_check_constraints(&self, _table: &Table) -> Vec<String> {
330            Vec::new()
331        }
332    }
333
334    struct NoopIndexGenerator;
335    impl IndexGenerator for NoopIndexGenerator {
336        fn output_indexes(&self) {}
337        fn output_indexes_for_table(
338            &self,
339            _writer: &mut crate::common::sql_writer::SqlWriter,
340            _table: &Table,
341        ) {
342        }
343        fn output_index(
344            &self,
345            _writer: &mut crate::common::sql_writer::SqlWriter,
346            _statement_separator: &str,
347            _table: &Table,
348            _key_name: &str,
349            _key: &Key,
350        ) {
351        }
352        fn index_options(&self, _key: &Key) -> Option<String> {
353            None
354        }
355    }
356
357    fn make_generator(context: GeneratorContext) -> DefaultTableGenerator {
358        DefaultTableGenerator::new(
359            context,
360            Box::new(NoopColumnGenerator),
361            Box::new(NoopKeyGenerator),
362            Box::new(NoopColumnConstraintGenerator),
363            Box::new(NoopTableConstraintGenerator),
364            Box::new(NoopIndexGenerator),
365        )
366    }
367
368    #[test]
369    fn output_initial_data_includes_rows_for_current_database_type_or_unspecified() {
370        let table = TableBuilder::new(None::<&str>, "users")
371            .add_initial_data(InitialData::new("insert into users values (1)", None))
372            .add_initial_data(InitialData::new(
373                "insert into users values (2)",
374                Some(DatabaseType::Sqlite),
375            ))
376            .add_initial_data(InitialData::new(
377                "insert into users values (3)",
378                Some(DatabaseType::Postgresql),
379            ))
380            .build();
381        let schema = SchemaBuilder::new(None::<&str>)
382            .add_table(table.clone())
383            .build();
384        let model =
385            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
386        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
387
388        let generator = make_generator(ctx);
389        generator.output_initial_data(&table);
390
391        let output = buffer.contents();
392        assert!(output.contains("insert into users values (1)"));
393        assert!(output.contains("insert into users values (2)"));
394        assert!(!output.contains("insert into users values (3)"));
395    }
396
397    #[test]
398    fn output_initial_data_writes_nothing_when_table_has_no_rows() {
399        let table = TableBuilder::new(None::<&str>, "users").build();
400        let schema = SchemaBuilder::new(None::<&str>)
401            .add_table(table.clone())
402            .build();
403        let model =
404            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
405        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
406
407        let generator = make_generator(ctx);
408        generator.output_initial_data(&table);
409
410        assert_eq!(buffer.contents(), "");
411    }
412
413    #[test]
414    fn output_table_runs_all_steps_in_order() {
415        let table = TableBuilder::new(None::<&str>, "users")
416            .add_initial_data(InitialData::new("insert into users values (1)", None))
417            .build();
418        let schema = SchemaBuilder::new(None::<&str>)
419            .add_table(table.clone())
420            .build();
421        let model =
422            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
423        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
424
425        let generator = make_generator(ctx);
426        generator.output_table(&table);
427
428        let output = buffer.contents();
429        let header_pos = output.find("create table users").unwrap();
430        let footer_pos = output.find(")").unwrap();
431        let data_pos = output.find("insert into users values (1)").unwrap();
432        assert!(header_pos < footer_pos);
433        assert!(footer_pos < data_pos);
434    }
435
436    #[test]
437    fn output_table_definition_drops_empty_constraint_strings() {
438        let table = TableBuilder::new(None::<&str>, "orders").build();
439        let schema = SchemaBuilder::new(None::<&str>)
440            .add_table(table.clone())
441            .build();
442        let model =
443            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
444        let (ctx, buffer) = make_context(model, DatabaseType::Sqlite);
445
446        let generator = DefaultTableGenerator::new(
447            ctx,
448            Box::new(NoopColumnGenerator),
449            Box::new(NoopKeyGenerator),
450            Box::new(EmptyStringColumnConstraintGenerator),
451            Box::new(NoopTableConstraintGenerator),
452            Box::new(NoopIndexGenerator),
453        );
454        generator.output_table_definition(&table);
455
456        let output = buffer.contents();
457        // No stray leading comma and no blank line between "(" and ")" from the empty entry.
458        assert!(!output.contains(","));
459        assert!(!output.contains("\n\n"));
460    }
461
462    fn table_names(tables: Vec<&Table>) -> Vec<String> {
463        tables.iter().map(|t| t.name().to_string()).collect()
464    }
465
466    #[test]
467    fn tables_in_drop_order_puts_child_before_parent() {
468        use schema_model::model::relation::Relation;
469        use schema_model::model::types::RelationType;
470
471        // Declared in create order (parent before the child that references it) -
472        // drop order must be the reverse.
473        let parent = TableBuilder::new(None::<&str>, "parent").build();
474        let child = TableBuilder::new(None::<&str>, "child")
475            .add_relation(Relation::new(
476                "parent",
477                "id",
478                "child",
479                "parent_id",
480                RelationType::Cascade,
481                false,
482            ))
483            .build();
484        let schema = SchemaBuilder::new(None::<&str>)
485            .add_table(parent)
486            .add_table(child)
487            .build();
488        let model =
489            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
490
491        assert_eq!(
492            table_names(tables_in_drop_order(&model)),
493            vec!["child", "parent"]
494        );
495    }
496
497    #[test]
498    fn tables_in_drop_order_handles_chain_of_three() {
499        use schema_model::model::relation::Relation;
500        use schema_model::model::types::RelationType;
501
502        let grandparent = TableBuilder::new(None::<&str>, "grandparent").build();
503        let parent = TableBuilder::new(None::<&str>, "parent")
504            .add_relation(Relation::new(
505                "grandparent",
506                "id",
507                "parent",
508                "grandparent_id",
509                RelationType::Cascade,
510                false,
511            ))
512            .build();
513        let child = TableBuilder::new(None::<&str>, "child")
514            .add_relation(Relation::new(
515                "parent",
516                "id",
517                "child",
518                "parent_id",
519                RelationType::Cascade,
520                false,
521            ))
522            .build();
523        let schema = SchemaBuilder::new(None::<&str>)
524            .add_table(grandparent)
525            .add_table(parent)
526            .add_table(child)
527            .build();
528        let model =
529            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
530
531        assert_eq!(
532            table_names(tables_in_drop_order(&model)),
533            vec!["child", "parent", "grandparent"]
534        );
535    }
536
537    #[test]
538    fn tables_in_drop_order_ignores_self_referencing_relation() {
539        use schema_model::model::relation::Relation;
540        use schema_model::model::types::RelationType;
541
542        // e.g. employee.manager_id -> employee.id - must not be treated as a cycle
543        // against itself (which would leave it stuck with a permanent in-degree).
544        let employee = TableBuilder::new(None::<&str>, "employee")
545            .add_relation(Relation::new(
546                "employee",
547                "id",
548                "employee",
549                "manager_id",
550                RelationType::SetNull,
551                false,
552            ))
553            .build();
554        let schema = SchemaBuilder::new(None::<&str>).add_table(employee).build();
555        let model =
556            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
557
558        assert_eq!(table_names(tables_in_drop_order(&model)), vec!["employee"]);
559    }
560
561    #[test]
562    fn tables_in_drop_order_falls_back_to_declaration_order_on_a_cycle() {
563        use schema_model::model::relation::Relation;
564        use schema_model::model::types::RelationType;
565
566        // "a" references "b" and "b" references "a" - no ordering satisfies both, so
567        // this must not panic or loop forever, and should fall back predictably.
568        let a = TableBuilder::new(None::<&str>, "a")
569            .add_relation(Relation::new(
570                "b",
571                "id",
572                "a",
573                "b_id",
574                RelationType::SetNull,
575                false,
576            ))
577            .build();
578        let b = TableBuilder::new(None::<&str>, "b")
579            .add_relation(Relation::new(
580                "a",
581                "id",
582                "b",
583                "a_id",
584                RelationType::SetNull,
585                false,
586            ))
587            .build();
588        let schema = SchemaBuilder::new(None::<&str>)
589            .add_table(a)
590            .add_table(b)
591            .build();
592        let model =
593            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
594
595        assert_eq!(table_names(tables_in_drop_order(&model)), vec!["a", "b"]);
596    }
597}