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        if let Some(default_constraint) = default_constraint {
74            if default_constraint.eq_ignore_ascii_case("null") {
75                return None;
76            }
77
78            let value = matches!(default_constraint.to_ascii_lowercase().as_str(), "true");
79            return Some(self.convert_boolean_default_constraint(value));
80        }
81
82        Some(self.convert_boolean_default_constraint(false))
83    }
84
85    fn uuid_default_value(
86        &self,
87        table: &Table,
88        column: &Column,
89        default_constraint: Option<&str>,
90    ) -> Option<String> {
91        let schema = self
92            .context
93            .settings()
94            .database_model()
95            .find_schema(table.schema_name());
96        let primary_key_columns = table.primary_key_columns();
97
98        if column.required()
99            && primary_key_columns.is_some_and(|columns| columns.contains(&column.name().to_string()))
100            && table.column_relation(column).is_none()
101        {
102            return Some(self.column_type_generator.uuid_default_value_sql(schema));
103        }
104
105        if default_constraint.is_some_and(|dc| dc.eq_ignore_ascii_case("generate_uuid()")) {
106            return Some(self.column_type_generator.uuid_default_value_sql(schema));
107        }
108
109        None
110    }
111
112    fn default_constraint(&self, table: &Table, column: &Column, default_value: &str) -> String {
113        match self.default_constraint_naming {
114            DefaultConstraintNaming::Unnamed => format!("default {}", default_value),
115            DefaultConstraintNaming::NamedByColumn => {
116                format!("constraint {} default {}", column.name(), default_value)
117            }
118            DefaultConstraintNaming::NamedWithHash => {
119                let constraint_name =
120                    constraint_naming::hashed_constraint_name(DF_PREFIX, table.name(), column.name());
121                format!("constraint {} default {}", constraint_name, default_value)
122            }
123        }
124    }
125}
126
127impl ColumnGenerator for DefaultColumnGenerator {
128    fn column_definitions(&self, table: &Table) -> Vec<String> {
129        table
130            .columns()
131            .iter()
132            .map(|column| self.column_sql(table, column))
133            .collect()
134    }
135
136    fn column_sql(&self, table: &Table, column: &Column) -> String {
137        let column_options = self.column_options(table, column);
138
139        if column_options.is_empty() {
140            return format!(
141                "   {} {}",
142                column.name(),
143                self.column_type_generator.column_type_sql(table, column)
144            );
145        }
146
147        format!(
148            "   {} {} {}",
149            column.name(),
150            self.column_type_generator.column_type_sql(table, column),
151            column_options
152        )
153    }
154
155    fn column_options(&self, table: &Table, column: &Column) -> String {
156        let mut options = String::new();
157
158        if column.required() {
159            if column.length() > 0 {
160                options.push(' ');
161            }
162
163            options.push_str("not null")
164        }
165
166        let default_value = self.default_value(table, column);
167
168        if let Some(default_value) = default_value {
169            if !options.is_empty() {
170                options.push(' ');
171            }
172
173            options.push_str(self.default_constraint(table, column, default_value.as_ref()).as_str());
174        }
175
176        options.trim().to_string()
177    }
178
179    fn default_value(&self, table: &Table, column: &Column) -> Option<String> {
180        let default_constraint = column.default_constraint();
181
182        match column.column_type() {
183            ColumnType::Boolean => self.boolean_default_value(default_constraint),
184            ColumnType::Uuid => self.uuid_default_value(table, column, default_constraint),
185            _ => default_constraint.map(String::from),
186        }
187    }
188}