Skip to main content

schema_sql_generator/common/
column_constraint_generator.rs

1use crate::common::constraint_naming;
2use crate::common::generator_context::GeneratorContext;
3use crate::common::sql_string::escape_sql_literal;
4use schema_model::model::column::Column;
5use schema_model::model::column_type::ColumnType;
6use schema_model::model::table::Table;
7use schema_model::model::types::BooleanMode;
8
9const CK_PREFIX: &str = "ck_";
10
11pub trait ColumnConstraintGenerator {
12    fn column_check_constraints(&self, table: &Table) -> Vec<String>;
13}
14
15pub struct DefaultColumnConstraintGenerator {
16    context: GeneratorContext,
17}
18
19impl DefaultColumnConstraintGenerator {
20    pub fn new(context: GeneratorContext) -> Self {
21        Self { context }
22    }
23
24    pub fn context(&self) -> &GeneratorContext {
25        &self.context
26    }
27
28    pub fn generate_constraint(&self, table: &Table, column: &Column) -> String {
29        let constraint_sql = self.check_constraint_sql(column);
30
31        if let Some(constraint_sql) = constraint_sql {
32            return format!(
33                "   constraint {} {}",
34                self.constraint_name(table.name(), column.name()),
35                constraint_sql
36            );
37        }
38
39        String::new()
40    }
41
42    fn constraint_name(&self, table_name: &str, column_name: &str) -> String {
43        constraint_naming::hashed_constraint_name(CK_PREFIX, table_name, column_name)
44    }
45
46    pub fn check_constraint_sql(&self, column: &Column) -> Option<String> {
47        if column.column_type() == ColumnType::Boolean {
48            self.boolean_check_constraint(column)
49        } else if let Some(constraint) = column.check_constraint() {
50            Some(Self::wrap_in_check(constraint))
51        } else if column.column_type() == ColumnType::Enum {
52            self.enum_check_constraint_sql(column)
53        } else if column.has_min_or_max_value() {
54            self.min_max_constraint_sql(column)
55        } else {
56            None
57        }
58    }
59
60    /// The `<check>` element holds just the boolean expression (e.g. `foo = 'ABC'`), not a
61    /// full `check(...)` clause - wrap it, unless the user already wrote the `check(...)`
62    /// wrapper themselves, in which case wrapping again would double it.
63    fn wrap_in_check(expression: &str) -> String {
64        let trimmed = expression.trim();
65
66        if trimmed.to_ascii_lowercase().starts_with("check") {
67            trimmed.to_string()
68        } else {
69            format!("check({})", trimmed)
70        }
71    }
72
73    fn boolean_check_constraint(&self, column: &Column) -> Option<String> {
74        match self.context.settings().boolean_mode() {
75            BooleanMode::YesNo => Some(format!("check({} in ('Yes','No'))", column.name())),
76            BooleanMode::YN => Some(format!("check({} in ('Y','N'))", column.name())),
77            BooleanMode::Native => None,
78        }
79    }
80
81    fn enum_check_constraint_sql(&self, column: &Column) -> Option<String> {
82        let schema_name = column.schema_name();
83        let schema = self
84            .context
85            .settings()
86            .database_model()
87            .find_schema(schema_name);
88        let enum_type = column.enum_type();
89        let enum_values = schema.get_enum_type(enum_type?).values().clone();
90
91        let joined_values = enum_values
92            .iter()
93            .map(|value| format!("'{}'", escape_sql_literal(value.code())))
94            .collect::<Vec<_>>()
95            .join(",");
96
97        Some(format!("check({} in ({}))", column.name(), joined_values))
98    }
99
100    fn min_max_constraint_sql(&self, column: &Column) -> Option<String> {
101        let min_value = column.min_value();
102        let max_value = column.max_value();
103        let mut sql = String::from("check(");
104
105        if let Some(min_value) = min_value {
106            sql.push_str(column.name());
107            sql.push_str(" >= ");
108            sql.push_str(min_value.to_string().as_str());
109        }
110
111        if min_value.is_some() && max_value.is_some() {
112            sql.push_str(" and ");
113        }
114
115        if let Some(max_value) = max_value {
116            sql.push_str(column.name());
117            sql.push_str(" <= ");
118            sql.push_str(max_value.to_string().as_str());
119        }
120
121        sql.push(')');
122
123        Some(sql)
124    }
125}
126
127impl ColumnConstraintGenerator for DefaultColumnConstraintGenerator {
128    fn column_check_constraints(&self, table: &Table) -> Vec<String> {
129        let columns = table.columns_with_check_constraints(self.context.settings().boolean_mode());
130
131        columns
132            .iter()
133            .map(|column| self.generate_constraint(table, column))
134            .collect()
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use crate::common::test_support::make_context;
142    use schema_model::builder::{ColumnBuilder, SchemaBuilder, TableBuilder};
143    use schema_model::model::database_model::DatabaseModel;
144    use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode};
145
146    #[test]
147    fn user_check_constraint_is_wrapped_in_check() {
148        let table = TableBuilder::new(None::<&str>, "test")
149            .add_column(
150                ColumnBuilder::new(None::<&str>, "varcharWithCheck", ColumnType::Varchar)
151                    .length(10)
152                    .check_constraint(Some("varcharWithCheck = 'ABC123'".to_string()))
153                    .build(),
154            )
155            .build();
156        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
157        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
158        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
159
160        let generator = DefaultColumnConstraintGenerator::new(ctx);
161        let constraints = generator.column_check_constraints(&table);
162
163        assert_eq!(constraints.len(), 1);
164        assert!(constraints[0].contains("check(varcharWithCheck = 'ABC123')"));
165    }
166
167    #[test]
168    fn user_check_constraint_already_wrapped_is_not_double_wrapped() {
169        let table = TableBuilder::new(None::<&str>, "test")
170            .add_column(
171                ColumnBuilder::new(None::<&str>, "code", ColumnType::Varchar)
172                    .length(10)
173                    .check_constraint(Some("check(code <> '')".to_string()))
174                    .build(),
175            )
176            .build();
177        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
178        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
179        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
180
181        let generator = DefaultColumnConstraintGenerator::new(ctx);
182        let constraints = generator.column_check_constraints(&table);
183
184        assert_eq!(constraints.len(), 1);
185        assert!(constraints[0].contains("check(code <> '')"));
186        assert!(!constraints[0].contains("check(check("));
187    }
188}