Skip to main content

schema_model/model/
column.rs

1use crate::model::column_type::ColumnType;
2use crate::model::types::BooleanMode;
3
4/// Parses a boolean column's `default` attribute (an untyped `xsd:string` in the schema XSD,
5/// not `xsd:boolean` - it has to tolerate whatever a hand-written schema file spells out) into
6/// either an explicit default value or, for the `null` sentinel, an explicit request for *no*
7/// default constraint to be emitted at all (distinct from the attribute being absent, which
8/// callers should handle before ever calling this).
9///
10/// Recognizes `true`/`1`/`yes`/`on` and `false`/`0`/`no`/`off`, trimmed and case-insensitive.
11/// Returns `Err(())` for anything else - shared by `Schema::validate()` (which reports it as a
12/// validation error up front) and the SQL generator (which can then treat any value reaching it
13/// as already validated, rather than silently guessing).
14#[allow(clippy::result_unit_err)] // the only failure is "not a recognized boolean"; callers supply their own message
15pub fn parse_boolean_default(value: &str) -> Result<Option<bool>, ()> {
16    let trimmed = value.trim();
17
18    if trimmed.eq_ignore_ascii_case("null") {
19        return Ok(None);
20    }
21
22    match trimmed.to_ascii_lowercase().as_str() {
23        "true" | "1" | "yes" | "on" => Ok(Some(true)),
24        "false" | "0" | "no" | "off" => Ok(Some(false)),
25        _ => Err(()),
26    }
27}
28
29#[derive(Debug, Clone)]
30pub struct Column {
31    schema_name: Option<String>,
32    name: String,
33    column_type: ColumnType,
34    length: i32,
35    scale: i32,
36    required: bool,
37    check_constraint: Option<String>,
38    default_constraint: Option<String>,
39    generated: Option<String>,
40    min_value: Option<f64>,
41    max_value: Option<f64>,
42    enum_type: Option<String>,
43    element_type: Option<String>,
44}
45
46impl Column {
47    pub fn new<S: Into<String>>(
48        schema_name: Option<S>,
49        name: S,
50        column_type: ColumnType,
51        length: i32,
52        scale: i32,
53        required: bool,
54    ) -> Self {
55        Self {
56            schema_name: schema_name.map(|s| s.into()),
57            name: name.into(),
58            column_type,
59            length,
60            scale,
61            required,
62            check_constraint: None,
63            default_constraint: None,
64            generated: None,
65            min_value: None,
66            max_value: None,
67            enum_type: None,
68            element_type: None,
69        }
70    }
71
72    #[allow(clippy::too_many_arguments)] // flat constructor mirroring every Column field; builders are the normal entry point
73    pub fn new_all<S: Into<String>>(
74        schema_name: Option<S>,
75        name: S,
76        column_type: ColumnType,
77        length: i32,
78        scale: i32,
79        required: bool,
80        check_constraint: Option<String>,
81        default_constraint: Option<String>,
82        generated: Option<String>,
83        min_value: Option<f64>,
84        max_value: Option<f64>,
85        enum_type: Option<String>,
86        element_type: Option<String>,
87    ) -> Self {
88        Self {
89            schema_name: schema_name.map(|s| s.into()),
90            name: name.into(),
91            column_type,
92            length,
93            scale,
94            required,
95            check_constraint,
96            default_constraint,
97            generated,
98            min_value,
99            max_value,
100            enum_type,
101            element_type,
102        }
103    }
104
105    pub fn schema_name(&self) -> Option<&str> {
106        self.schema_name.as_deref()
107    }
108
109    pub fn name(&self) -> &str {
110        &self.name
111    }
112
113    pub fn column_type(&self) -> ColumnType {
114        self.column_type
115    }
116
117    pub fn length(&self) -> i32 {
118        self.length
119    }
120
121    pub fn scale(&self) -> i32 {
122        self.scale
123    }
124
125    pub fn required(&self) -> bool {
126        self.required
127    }
128
129    // Compatibility alias: elsewhere in the codebase `is_required()` is used.
130    pub fn is_required(&self) -> bool {
131        self.required
132    }
133
134    pub fn check_constraint(&self) -> Option<&str> {
135        self.check_constraint.as_deref()
136    }
137
138    pub fn default_constraint(&self) -> Option<&str> {
139        self.default_constraint.as_deref()
140    }
141
142    pub fn generated(&self) -> Option<&str> {
143        self.generated.as_deref()
144    }
145
146    pub fn min_value(&self) -> Option<f64> {
147        self.min_value
148    }
149
150    pub fn max_value(&self) -> Option<f64> {
151        self.max_value
152    }
153
154    pub fn enum_type(&self) -> Option<&str> {
155        self.enum_type.as_deref()
156    }
157
158    pub fn element_type(&self) -> Option<&str> {
159        self.element_type.as_deref()
160    }
161
162    pub fn has_min_or_max_value(&self) -> bool {
163        self.min_value.is_some() || self.max_value.is_some()
164    }
165
166    pub fn needs_check_constraints(&self, boolean_mode: BooleanMode) -> bool {
167        self.check_constraint.is_some()
168            || self.min_value.is_some()
169            || self.max_value.is_some()
170            || self.enum_type.is_some()
171            || (self.column_type == ColumnType::Boolean && boolean_mode != BooleanMode::Native)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use crate::model::types::BooleanMode;
179
180    #[test]
181    fn constructor_and_getters() {
182        let c = Column::new(None, "name", ColumnType::Varchar, 255, 0, true);
183        assert_eq!(c.name(), "name");
184        assert_eq!(c.column_type(), ColumnType::Varchar);
185        assert_eq!(c.length(), 255);
186        assert_eq!(c.scale(), 0);
187        assert!(c.required());
188        assert!(c.is_required());
189    }
190
191    #[test]
192    fn parse_boolean_default_recognizes_truthy_spellings() {
193        for value in ["true", "TRUE", " true ", "1", "yes", "YES", "on"] {
194            assert_eq!(
195                parse_boolean_default(value),
196                Ok(Some(true)),
197                "value: {:?}",
198                value
199            );
200        }
201    }
202
203    #[test]
204    fn parse_boolean_default_recognizes_falsy_spellings() {
205        for value in ["false", "FALSE", " false ", "0", "no", "NO", "off"] {
206            assert_eq!(
207                parse_boolean_default(value),
208                Ok(Some(false)),
209                "value: {:?}",
210                value
211            );
212        }
213    }
214
215    #[test]
216    fn parse_boolean_default_null_sentinel_means_no_default() {
217        assert_eq!(parse_boolean_default("null"), Ok(None));
218        assert_eq!(parse_boolean_default("NULL"), Ok(None));
219        assert_eq!(parse_boolean_default(" null "), Ok(None));
220    }
221
222    #[test]
223    fn parse_boolean_default_rejects_unrecognized_values() {
224        for value in ["maybe", "T", "getdate()", ""] {
225            assert_eq!(parse_boolean_default(value), Err(()), "value: {:?}", value);
226        }
227    }
228
229    #[test]
230    fn needs_check_constraints_logic() {
231        let c = Column::new(None, "b", ColumnType::Boolean, 0, 0, false);
232        // boolean with non-native boolean mode => needs constraints
233        assert!(c.needs_check_constraints(BooleanMode::YesNo));
234        // boolean with native => no unless other attributes set
235        assert!(!c.needs_check_constraints(BooleanMode::Native));
236    }
237
238    #[test]
239    fn has_min_or_max_value() {
240        let c = Column::new(None, "n", ColumnType::Int, 0, 0, false);
241        assert!(!c.has_min_or_max_value());
242    }
243}