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        let column_options = self.column_options(table, column);
148
149        if column_options.is_empty() {
150            return format!(
151                "   {} {}",
152                column.name(),
153                self.column_type_generator.column_type_sql(table, column)
154            );
155        }
156
157        format!(
158            "   {} {} {}",
159            column.name(),
160            self.column_type_generator.column_type_sql(table, column),
161            column_options
162        )
163    }
164
165    fn column_options(&self, table: &Table, column: &Column) -> String {
166        let mut options = String::new();
167
168        if column.required() {
169            if column.length() > 0 {
170                options.push(' ');
171            }
172
173            options.push_str("not null")
174        }
175
176        let default_value = self.default_value(table, column);
177
178        if let Some(default_value) = default_value {
179            if !options.is_empty() {
180                options.push(' ');
181            }
182
183            options.push_str(
184                self.default_constraint(table, column, default_value.as_ref())
185                    .as_str(),
186            );
187        }
188
189        options.trim().to_string()
190    }
191
192    fn default_value(&self, table: &Table, column: &Column) -> Option<String> {
193        let default_constraint = column.default_constraint();
194
195        match column.column_type() {
196            ColumnType::Boolean => self.boolean_default_value(default_constraint),
197            ColumnType::Uuid => self.uuid_default_value(table, column, default_constraint),
198            _ => default_constraint.map(String::from),
199        }
200    }
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::common::test_support::make_context;
207    use schema_model::builder::{ColumnBuilder, SchemaBuilder, TableBuilder};
208    use schema_model::model::database_model::DatabaseModel;
209    use schema_model::model::schema::Schema;
210    use schema_model::model::types::{BooleanMode, DatabaseType, ForeignKeyMode};
211
212    /// Bare-minimum `ColumnTypeGenerator` - only `native_boolean_sql` matters here, the rest
213    /// exist purely to satisfy the trait's other required methods.
214    struct DummyColumnTypeGenerator(GeneratorContext);
215    impl ColumnTypeGenerator for DummyColumnTypeGenerator {
216        fn context(&self) -> &GeneratorContext {
217            &self.0
218        }
219        fn sequence_sql(&self) -> String {
220            String::new()
221        }
222        fn long_sequence_sql(&self) -> String {
223            String::new()
224        }
225        fn text_sql(&self, _column: &Column) -> String {
226            String::new()
227        }
228        fn citext_sql(&self) -> String {
229            String::new()
230        }
231        fn cstext_sql(&self) -> String {
232            String::new()
233        }
234        fn binary_sql(&self, _column: &Column) -> String {
235            String::new()
236        }
237        fn uuid_default_value_sql(&self, _schema: &Schema) -> String {
238            String::new()
239        }
240        fn array_sql(&self, _column: &Column) -> String {
241            String::new()
242        }
243        fn json_sql(&self, _column: &Column) -> String {
244            String::new()
245        }
246        fn native_boolean_sql(&self) -> String {
247            "boolean".to_string()
248        }
249    }
250
251    fn boolean_column_default(default_constraint: Option<&str>) -> Option<String> {
252        let mut builder = ColumnBuilder::new(None::<&str>, "active", ColumnType::Boolean);
253        if let Some(default_constraint) = default_constraint {
254            builder = builder.default_constraint(Some(default_constraint.to_string()));
255        }
256        let table = TableBuilder::new(None::<&str>, "widget")
257            .add_column(builder.build())
258            .build();
259        let schema = SchemaBuilder::new(None::<&str>)
260            .add_table(table.clone())
261            .build();
262        let model =
263            DatabaseModel::new(BooleanMode::Native, ForeignKeyMode::Relations, vec![schema]);
264        let (ctx, _buffer) = make_context(model, DatabaseType::Postgresql);
265
266        let generator = DefaultColumnGenerator::new(
267            ctx.clone(),
268            Box::new(DummyColumnTypeGenerator(ctx)),
269            DefaultConstraintNaming::Unnamed,
270        );
271        let column = table.columns()[0].clone();
272        generator.default_value(&table, &column)
273    }
274
275    #[test]
276    fn boolean_column_with_no_default_attribute_gets_no_default_constraint() {
277        // Regression test for H2: omitting `default` used to silently force `default false`,
278        // making a nullable boolean column with no default inexpressible.
279        assert_eq!(boolean_column_default(None), None);
280    }
281
282    #[test]
283    fn boolean_column_default_null_sentinel_means_no_default_constraint() {
284        assert_eq!(boolean_column_default(Some("null")), None);
285        assert_eq!(boolean_column_default(Some("NULL")), None);
286    }
287
288    #[test]
289    fn boolean_column_default_recognizes_truthy_spellings() {
290        for value in ["true", "TRUE", " true ", "1", "yes", "on"] {
291            assert_eq!(
292                boolean_column_default(Some(value)),
293                Some("true".to_string()),
294                "value: {:?}",
295                value
296            );
297        }
298    }
299
300    #[test]
301    fn boolean_column_default_recognizes_falsy_spellings() {
302        for value in ["false", "FALSE", "0", "no", "off"] {
303            assert_eq!(
304                boolean_column_default(Some(value)),
305                Some("false".to_string()),
306                "value: {:?}",
307                value
308            );
309        }
310    }
311
312    #[test]
313    fn boolean_column_default_falls_back_to_false_for_an_unrecognized_value() {
314        // `Schema::validate()` rejects this before generation ever runs (see schema-model's
315        // `Schema::validate` tests), so this only exercises the defensive fallback for a
316        // caller that invokes the generator directly without validating first.
317        assert_eq!(
318            boolean_column_default(Some("maybe")),
319            Some("false".to_string())
320        );
321    }
322}