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