Skip to main content

schema_sql_generator/common/
column_generator.rs

1use crate::common::column_type_generator::ColumnTypeGenerator;
2use crate::common::constraint_naming;
3use crate::common::generator_context::GeneratorContext;
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 DF_PREFIX: &str = "df_";
10
11/// Controls how a column's `default` constraint is named in generated DDL.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum DefaultConstraintNaming {
14    /// `default {value}` - no named constraint (e.g. Postgres).
15    Unnamed,
16    /// `constraint {column} default {value}` - named after the bare column (e.g. SQLite).
17    NamedByColumn,
18    /// `constraint df_{table[0..9]}_{column[0..9]}_{HASH8} default {value}` - matches the
19    /// legacy Java codegen tool's SQL Server naming scheme.
20    NamedWithHash,
21}
22
23pub trait ColumnGenerator {
24    fn column_definitions(&self, table: &Table) -> Vec<String>;
25
26    fn column_sql(&self, table: &Table, column: &Column) -> String;
27
28    fn column_options(&self, table: &Table, column: &Column) -> String;
29
30    fn default_value(&self, table: &Table, column: &Column) -> Option<String>;
31}
32
33pub struct DefaultColumnGenerator {
34    context: GeneratorContext,
35    column_type_generator: Box<dyn ColumnTypeGenerator>,
36    default_constraint_naming: DefaultConstraintNaming,
37}
38
39impl DefaultColumnGenerator {
40    pub fn new(
41        context: GeneratorContext,
42        column_type_generator: Box<dyn ColumnTypeGenerator>,
43        default_constraint_naming: DefaultConstraintNaming,
44    ) -> Self {
45        Self {
46            column_type_generator,
47            context,
48            default_constraint_naming,
49        }
50    }
51
52    fn convert_boolean_default_constraint(&self, value: bool) -> String {
53        match self.context.settings().boolean_mode() {
54            BooleanMode::Native => self.column_type_generator.native_boolean_literal(value),
55            BooleanMode::YesNo => {
56                if value {
57                    "'Yes'".to_string()
58                } else {
59                    "'No'".to_string()
60                }
61            }
62            BooleanMode::YN => {
63                if value {
64                    "'Y'".to_string()
65                } else {
66                    "'N'".to_string()
67                }
68            }
69        }
70    }
71
72    fn boolean_default_value(&self, default_constraint: Option<&str>) -> Option<String> {
73        // No `default` attribute at all means no default constraint - unlike the old
74        // behaviour here, this must *not* fall back to `default false`: that made a nullable
75        // boolean column with no default inexpressible (H2). `parse_boolean_default` already
76        // recognizes the `null` sentinel as "no default constraint" (`Ok(None)`), distinct
77        // from this "attribute absent" case.
78        let default_constraint = default_constraint?;
79
80        // `Schema::validate()` rejects any value `parse_boolean_default` can't parse before
81        // generation ever runs, so `Err(())` here is unreachable through the CLI/installer -
82        // but a caller going straight to the generator without validating first should still
83        // get a working (if surprising) `false` rather than a panic.
84        match schema_model::model::column::parse_boolean_default(default_constraint) {
85            Ok(Some(value)) => Some(self.convert_boolean_default_constraint(value)),
86            Ok(None) => None,
87            Err(()) => Some(self.convert_boolean_default_constraint(false)),
88        }
89    }
90
91    fn uuid_default_value(
92        &self,
93        table: &Table,
94        column: &Column,
95        default_constraint: Option<&str>,
96    ) -> Option<String> {
97        let schema = self
98            .context
99            .settings()
100            .database_model()
101            .find_schema(table.schema_name());
102        let primary_key_columns = table.primary_key_columns();
103
104        if column.required()
105            && primary_key_columns.is_some_and(|columns| columns.contains(&column.name().to_string()))
106            && table.column_relation(column).is_none()
107        {
108            return Some(self.column_type_generator.uuid_default_value_sql(schema));
109        }
110
111        if default_constraint.is_some_and(|dc| dc.eq_ignore_ascii_case("generate_uuid()")) {
112            return Some(self.column_type_generator.uuid_default_value_sql(schema));
113        }
114
115        None
116    }
117
118    fn default_constraint(&self, table: &Table, column: &Column, default_value: &str) -> String {
119        match self.default_constraint_naming {
120            DefaultConstraintNaming::Unnamed => format!("default {}", default_value),
121            DefaultConstraintNaming::NamedByColumn => {
122                format!("constraint {} default {}", column.name(), default_value)
123            }
124            DefaultConstraintNaming::NamedWithHash => {
125                let constraint_name =
126                    constraint_naming::hashed_constraint_name(DF_PREFIX, table.name(), column.name());
127                format!("constraint {} default {}", constraint_name, default_value)
128            }
129        }
130    }
131}
132
133impl ColumnGenerator for DefaultColumnGenerator {
134    fn column_definitions(&self, table: &Table) -> Vec<String> {
135        table
136            .columns()
137            .iter()
138            .map(|column| self.column_sql(table, column))
139            .collect()
140    }
141
142    fn column_sql(&self, table: &Table, column: &Column) -> String {
143        let column_options = self.column_options(table, column);
144
145        if column_options.is_empty() {
146            return format!(
147                "   {} {}",
148                column.name(),
149                self.column_type_generator.column_type_sql(table, column)
150            );
151        }
152
153        format!(
154            "   {} {} {}",
155            column.name(),
156            self.column_type_generator.column_type_sql(table, column),
157            column_options
158        )
159    }
160
161    fn column_options(&self, table: &Table, column: &Column) -> String {
162        let mut options = String::new();
163
164        if column.required() {
165            if column.length() > 0 {
166                options.push(' ');
167            }
168
169            options.push_str("not null")
170        }
171
172        let default_value = self.default_value(table, column);
173
174        if let Some(default_value) = default_value {
175            if !options.is_empty() {
176                options.push(' ');
177            }
178
179            options.push_str(self.default_constraint(table, column, default_value.as_ref()).as_str());
180        }
181
182        options.trim().to_string()
183    }
184
185    fn default_value(&self, table: &Table, column: &Column) -> Option<String> {
186        let default_constraint = column.default_constraint();
187
188        match column.column_type() {
189            ColumnType::Boolean => self.boolean_default_value(default_constraint),
190            ColumnType::Uuid => self.uuid_default_value(table, column, default_constraint),
191            _ => default_constraint.map(String::from),
192        }
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::common::test_support::make_context;
200    use schema_model::builder::{ColumnBuilder, SchemaBuilder, TableBuilder};
201    use schema_model::model::database_model::DatabaseModel;
202    use schema_model::model::schema::Schema;
203    use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode};
204
205    /// Bare-minimum `ColumnTypeGenerator` - only `native_boolean_sql` matters here, the rest
206    /// exist purely to satisfy the trait's other required methods.
207    struct DummyColumnTypeGenerator(GeneratorContext);
208    impl ColumnTypeGenerator for DummyColumnTypeGenerator {
209        fn context(&self) -> &GeneratorContext { &self.0 }
210        fn sequence_sql(&self) -> String { String::new() }
211        fn long_sequence_sql(&self) -> String { String::new() }
212        fn text_sql(&self, _column: &Column) -> String { String::new() }
213        fn citext_sql(&self) -> String { String::new() }
214        fn cstext_sql(&self) -> String { String::new() }
215        fn binary_sql(&self, _column: &Column) -> String { String::new() }
216        fn uuid_default_value_sql(&self, _schema: &Schema) -> String { String::new() }
217        fn array_sql(&self, _column: &Column) -> String { String::new() }
218        fn json_sql(&self, _column: &Column) -> String { String::new() }
219        fn native_boolean_sql(&self) -> String { "boolean".to_string() }
220    }
221
222    fn boolean_column_default(default_constraint: Option<&str>) -> Option<String> {
223        let mut builder = ColumnBuilder::new(None::<&str>, "active", ColumnType::Boolean);
224        if let Some(default_constraint) = default_constraint {
225            builder = builder.default_constraint(Some(default_constraint.to_string()));
226        }
227        let table = TableBuilder::new(None::<&str>, "widget").add_column(builder.build()).build();
228        let schema = SchemaBuilder::new(None::<&str>).add_table(table.clone()).build();
229        let model = DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
230        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
231
232        let generator = DefaultColumnGenerator::new(
233            ctx.clone(),
234            Box::new(DummyColumnTypeGenerator(ctx)),
235            DefaultConstraintNaming::Unnamed,
236        );
237        let column = table.columns()[0].clone();
238        generator.default_value(&table, &column)
239    }
240
241    #[test]
242    fn boolean_column_with_no_default_attribute_gets_no_default_constraint() {
243        // Regression test for H2: omitting `default` used to silently force `default false`,
244        // making a nullable boolean column with no default inexpressible.
245        assert_eq!(boolean_column_default(None), None);
246    }
247
248    #[test]
249    fn boolean_column_default_null_sentinel_means_no_default_constraint() {
250        assert_eq!(boolean_column_default(Some("null")), None);
251        assert_eq!(boolean_column_default(Some("NULL")), None);
252    }
253
254    #[test]
255    fn boolean_column_default_recognizes_truthy_spellings() {
256        for value in ["true", "TRUE", " true ", "1", "yes", "on"] {
257            assert_eq!(boolean_column_default(Some(value)), Some("true".to_string()), "value: {:?}", value);
258        }
259    }
260
261    #[test]
262    fn boolean_column_default_recognizes_falsy_spellings() {
263        for value in ["false", "FALSE", "0", "no", "off"] {
264            assert_eq!(boolean_column_default(Some(value)), Some("false".to_string()), "value: {:?}", value);
265        }
266    }
267
268    #[test]
269    fn boolean_column_default_falls_back_to_false_for_an_unrecognized_value() {
270        // `Schema::validate()` rejects this before generation ever runs (see schema-model's
271        // `Schema::validate` tests), so this only exercises the defensive fallback for a
272        // caller that invokes the generator directly without validating first.
273        assert_eq!(boolean_column_default(Some("maybe")), Some("false".to_string()));
274    }
275}