Skip to main content

schema_sql_generator/common/
table_constraint_generator.rs

1use crate::common::generator_context::GeneratorContext;
2use schema_model::model::constraint::Constraint;
3use schema_model::model::table::Table;
4#[cfg(test)]
5use schema_model::model::types::DatabaseType;
6
7pub trait TableConstraintGenerator {
8    fn table_check_constraints(&self, table: &Table) -> Vec<String>;
9}
10
11pub struct DefaultTableConstraintGenerator {
12    context: GeneratorContext,
13}
14
15impl DefaultTableConstraintGenerator {
16    pub fn new(context: GeneratorContext) -> Self {
17        Self {
18            context,
19        }
20    }
21
22    pub fn context(&self) -> &GeneratorContext {
23        &self.context
24    }
25
26    fn generator_constraint(&self, constraint: &Constraint) -> String {
27        format!("   constraint {} {}",
28               constraint.name(),
29               constraint.sql())
30    }
31}
32
33impl TableConstraintGenerator for DefaultTableConstraintGenerator {
34    fn table_check_constraints(&self, table: &Table) -> Vec<String> {
35        let database_type = self.context.settings().database_type();
36        table.constraints().iter()
37            .filter(|constraint| constraint.database_type() == database_type)
38            .map(|constraint| {
39                self.generator_constraint(constraint)
40            }).collect()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47    use crate::common::test_support::make_context;
48    use schema_model::builder::{SchemaBuilder, TableBuilder};
49    use schema_model::model::database_model::DatabaseModel;
50    use schema_model::model::types::{BooleanMode, ForeignKeyMode};
51
52    /// H18: a table-level `<constraint databaseType="…">` must only be emitted into the
53    /// script for the database it targets - the same rule already applied to views
54    /// (`Schema::views`) and initial data (`output_initial_data`).
55    #[test]
56    fn table_check_constraints_filters_by_database_type() {
57        let table = TableBuilder::new(None::<&str>, "users")
58            .add_constraint(Constraint::new("ck_email_pg", "check (email ~ '^[^@]+@')", DatabaseType::Postgresql))
59            .add_constraint(Constraint::new("ck_email_lite", "check (email like '%@%')", DatabaseType::Sqlite))
60            .build();
61        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
62        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
63        let (ctx, _buffer) = make_context(model, DatabaseType::Sqlite);
64
65        let generator = DefaultTableConstraintGenerator::new(ctx);
66        let constraints = generator.table_check_constraints(&table);
67
68        assert_eq!(constraints.len(), 1);
69        assert!(constraints[0].contains("ck_email_lite"));
70        assert!(!constraints[0].contains("ck_email_pg"));
71    }
72}