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
106                .is_some_and(|columns| columns.contains(&column.name().to_string()))
107            && table.column_relation(column).is_none()
108        {
109            return Some(self.column_type_generator.uuid_default_value_sql(schema));
110        }
111
112        if default_constraint.is_some_and(|dc| dc.eq_ignore_ascii_case("generate_uuid()")) {
113            return Some(self.column_type_generator.uuid_default_value_sql(schema));
114        }
115
116        None
117    }
118
119    fn default_constraint(&self, table: &Table, column: &Column, default_value: &str) -> String {
120        match self.default_constraint_naming {
121            DefaultConstraintNaming::Unnamed => format!("default {}", default_value),
122            DefaultConstraintNaming::NamedByColumn => {
123                format!("constraint {} default {}", column.name(), default_value)
124            }
125            DefaultConstraintNaming::NamedWithHash => {
126                let constraint_name = constraint_naming::hashed_constraint_name(
127                    DF_PREFIX,
128                    table.name(),
129                    column.name(),
130                );
131                format!("constraint {} default {}", constraint_name, default_value)
132            }
133        }
134    }
135}
136
137impl ColumnGenerator for DefaultColumnGenerator {
138    fn column_definitions(&self, table: &Table) -> Vec<String> {
139        table
140            .columns()
141            .iter()
142            .map(|column| self.column_sql(table, column))
143            .collect()
144    }
145
146    fn column_sql(&self, table: &Table, column: &Column) -> String {
147        // Generated/computed columns take no DEFAULT in any dialect, so they bypass
148        // `column_options` entirely.
149        if let Some(expression) = column.generated() {
150            let definition = self
151                .column_type_generator
152                .generated_column_sql(table, column, expression);
153            let not_null = if column.required() { " not null" } else { "" };
154            return format!("   {} {}{}", column.name(), definition, not_null);
155        }
156
157        let column_options = self.column_options(table, column);
158
159        if column_options.is_empty() {
160            return format!(
161                "   {} {}",
162                column.name(),
163                self.column_type_generator.column_type_sql(table, column)
164            );
165        }
166
167        format!(
168            "   {} {} {}",
169            column.name(),
170            self.column_type_generator.column_type_sql(table, column),
171            column_options
172        )
173    }
174
175    fn column_options(&self, table: &Table, column: &Column) -> String {
176        let mut options = String::new();
177
178        if column.required() {
179            if column.length() > 0 {
180                options.push(' ');
181            }
182
183            options.push_str("not null")
184        }
185
186        let default_value = self.default_value(table, column);
187
188        if let Some(default_value) = default_value {
189            if !options.is_empty() {
190                options.push(' ');
191            }
192
193            options.push_str(
194                self.default_constraint(table, column, default_value.as_ref())
195                    .as_str(),
196            );
197        }
198
199        options.trim().to_string()
200    }
201
202    fn default_value(&self, table: &Table, column: &Column) -> Option<String> {
203        let default_constraint = column.default_constraint();
204
205        match column.column_type() {
206            ColumnType::Boolean => self.boolean_default_value(default_constraint),
207            ColumnType::Uuid => self.uuid_default_value(table, column, default_constraint),
208            _ => default_constraint.map(String::from),
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216    use crate::common::test_support::make_context;
217    use schema_model::builder::{ColumnBuilder, SchemaBuilder, TableBuilder};
218    use schema_model::model::database_model::DatabaseModel;
219    use schema_model::model::schema::Schema;
220    use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode};
221
222    /// Bare-minimum `ColumnTypeGenerator` - only `native_boolean_sql` matters here, the rest
223    /// exist purely to satisfy the trait's other required methods.
224    struct DummyColumnTypeGenerator(GeneratorContext);
225    impl ColumnTypeGenerator for DummyColumnTypeGenerator {
226        fn context(&self) -> &GeneratorContext {
227            &self.0
228        }
229        fn sequence_sql(&self) -> String {
230            String::new()
231        }
232        fn long_sequence_sql(&self) -> String {
233            String::new()
234        }
235        fn text_sql(&self, _column: &Column) -> String {
236            String::new()
237        }
238        fn citext_sql(&self) -> String {
239            String::new()
240        }
241        fn cstext_sql(&self) -> String {
242            String::new()
243        }
244        fn binary_sql(&self, _column: &Column) -> String {
245            String::new()
246        }
247        fn uuid_default_value_sql(&self, _schema: &Schema) -> String {
248            String::new()
249        }
250        fn array_sql(&self, _column: &Column) -> String {
251            String::new()
252        }
253        fn json_sql(&self, _column: &Column) -> String {
254            String::new()
255        }
256        fn native_boolean_sql(&self) -> String {
257            "boolean".to_string()
258        }
259    }
260
261    fn boolean_column_default(default_constraint: Option<&str>) -> Option<String> {
262        let mut builder = ColumnBuilder::new(None::<&str>, "active", ColumnType::Boolean);
263        if let Some(default_constraint) = default_constraint {
264            builder = builder.default_constraint(Some(default_constraint.to_string()));
265        }
266        let table = TableBuilder::new(None::<&str>, "widget")
267            .add_column(builder.build())
268            .build();
269        let schema = SchemaBuilder::new(None::<&str>)
270            .add_table(table.clone())
271            .build();
272        let model =
273            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
274        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
275
276        let generator = DefaultColumnGenerator::new(
277            ctx.clone(),
278            Box::new(DummyColumnTypeGenerator(ctx)),
279            DefaultConstraintNaming::Unnamed,
280        );
281        let column = table.columns()[0].clone();
282        generator.default_value(&table, &column)
283    }
284
285    #[test]
286    fn boolean_column_with_no_default_attribute_gets_no_default_constraint() {
287        // Regression test for H2: omitting `default` used to silently force `default false`,
288        // making a nullable boolean column with no default inexpressible.
289        assert_eq!(boolean_column_default(None), None);
290    }
291
292    #[test]
293    fn boolean_column_default_null_sentinel_means_no_default_constraint() {
294        assert_eq!(boolean_column_default(Some("null")), None);
295        assert_eq!(boolean_column_default(Some("NULL")), None);
296    }
297
298    #[test]
299    fn boolean_column_default_recognizes_truthy_spellings() {
300        for value in ["true", "TRUE", " true ", "1", "yes", "on"] {
301            assert_eq!(
302                boolean_column_default(Some(value)),
303                Some("true".to_string()),
304                "value: {:?}",
305                value
306            );
307        }
308    }
309
310    #[test]
311    fn boolean_column_default_recognizes_falsy_spellings() {
312        for value in ["false", "FALSE", "0", "no", "off"] {
313            assert_eq!(
314                boolean_column_default(Some(value)),
315                Some("false".to_string()),
316                "value: {:?}",
317                value
318            );
319        }
320    }
321
322    #[test]
323    fn boolean_column_default_falls_back_to_false_for_an_unrecognized_value() {
324        // `Schema::validate()` rejects this before generation ever runs (see schema-model's
325        // `Schema::validate` tests), so this only exercises the defensive fallback for a
326        // caller that invokes the generator directly without validating first.
327        assert_eq!(
328            boolean_column_default(Some("maybe")),
329            Some("false".to_string())
330        );
331    }
332
333    #[test]
334    fn generated_column_skips_default_and_appends_not_null() {
335        let column = ColumnBuilder::new(None::<&str>, "total", ColumnType::Int)
336            .required(true)
337            .generated(Some("a + b".to_string()))
338            .build();
339        let table = TableBuilder::new(None::<&str>, "widget")
340            .add_column(column.clone())
341            .build();
342        let schema = SchemaBuilder::new(None::<&str>)
343            .add_table(table.clone())
344            .build();
345        let model =
346            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
347        let (context, _buffer) = make_context(model, DatabaseType::Postgresql);
348        let generator = DefaultColumnGenerator::new(
349            context.clone(),
350            Box::new(DummyColumnTypeGenerator(context)),
351            DefaultConstraintNaming::Unnamed,
352        );
353        let sql = generator.column_sql(&table, &column);
354        assert!(
355            sql.contains("generated always as (a + b) stored not null"),
356            "{sql}"
357        );
358        assert!(!sql.contains("default"));
359    }
360}