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).
14pub fn parse_boolean_default(value: &str) -> Result<Option<bool>, ()> {
15    let trimmed = value.trim();
16
17    if trimmed.eq_ignore_ascii_case("null") {
18        return Ok(None);
19    }
20
21    match trimmed.to_ascii_lowercase().as_str() {
22        "true" | "1" | "yes" | "on" => Ok(Some(true)),
23        "false" | "0" | "no" | "off" => Ok(Some(false)),
24        _ => Err(()),
25    }
26}
27
28#[derive(Debug, Clone)]
29pub struct Column {
30    schema_name: Option<String>,
31    name: String,
32    column_type: ColumnType,
33    length: i32,
34    scale: i32,
35    required: bool,
36    check_constraint: Option<String>,
37    default_constraint: Option<String>,
38    generated: Option<String>,
39    min_value: Option<f64>,
40    max_value: Option<f64>,
41    enum_type: Option<String>,
42    element_type: Option<String>,
43}
44
45impl Column {
46    pub fn new<S: Into<String>>(
47        schema_name: Option<S>,
48        name: S,
49        column_type: ColumnType,
50        length: i32,
51        scale: i32,
52        required: bool,
53    ) -> Self {
54        Self {
55            schema_name: schema_name.map(|s| s.into()),
56            name: name.into(),
57            column_type,
58            length,
59            scale,
60            required,
61            check_constraint: None,
62            default_constraint: None,
63            generated: None,
64            min_value: None,
65            max_value: None,
66            enum_type: None,
67            element_type: None,
68        }
69    }
70
71    pub fn new_all<S: Into<String>>(
72        schema_name: Option<S>,
73        name: S,
74        column_type: ColumnType,
75        length: i32,
76        scale: i32,
77        required: bool,
78        check_constraint: Option<String>,
79        default_constraint: Option<String>,
80        generated: Option<String>,
81        min_value: Option<f64>,
82        max_value: Option<f64>,
83        enum_type: Option<String>,
84        element_type: Option<String>,
85    ) -> Self {
86        Self {
87            schema_name: schema_name.map(|s| s.into()),
88            name: name.into(),
89            column_type,
90            length,
91            scale,
92            required,
93            check_constraint,
94            default_constraint,
95            generated,
96            min_value,
97            max_value,
98            enum_type,
99            element_type,
100        }
101    }
102
103    pub fn schema_name(&self) -> Option<&str> {
104        self.schema_name.as_deref()
105    }
106
107    pub fn name(&self) -> &str {
108        &self.name
109    }
110
111    pub fn column_type(&self) -> ColumnType {
112        self.column_type
113    }
114
115    pub fn length(&self) -> i32 {
116        self.length
117    }
118
119    pub fn scale(&self) -> i32 {
120        self.scale
121    }
122
123    pub fn required(&self) -> bool {
124        self.required
125    }
126
127    // Compatibility alias: elsewhere in the codebase `is_required()` is used.
128    pub fn is_required(&self) -> bool {
129        self.required
130    }
131
132    pub fn check_constraint(&self) -> Option<&str> {
133        self.check_constraint.as_deref()
134    }
135
136    pub fn default_constraint(&self) -> Option<&str> {
137        self.default_constraint.as_deref()
138    }
139
140    pub fn generated(&self) -> Option<&str> {
141        self.generated.as_deref()
142    }
143
144    pub fn min_value(&self) -> Option<f64> {
145        self.min_value
146    }
147
148    pub fn max_value(&self) -> Option<f64> {
149        self.max_value
150    }
151
152    pub fn enum_type(&self) -> Option<&str> {
153        self.enum_type.as_deref()
154    }
155
156    pub fn element_type(&self) -> Option<&str> {
157        self.element_type.as_deref()
158    }
159
160    pub fn has_min_or_max_value(&self) -> bool {
161        self.min_value.is_some() || self.max_value.is_some()
162    }
163
164    pub fn needs_check_constraints(&self, boolean_mode: BooleanMode) -> bool {
165        self.check_constraint.is_some()
166            || self.min_value.is_some()
167            || self.max_value.is_some()
168            || self.enum_type.is_some()
169            || (self.column_type == ColumnType::Boolean && boolean_mode != BooleanMode::Native)
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::model::types::BooleanMode;
177
178    #[test]
179    fn constructor_and_getters() {
180        let c = Column::new(None, "name", ColumnType::Varchar, 255, 0, true);
181        assert_eq!(c.name(), "name");
182        assert_eq!(c.column_type(), ColumnType::Varchar);
183        assert_eq!(c.length(), 255);
184        assert_eq!(c.scale(), 0);
185        assert!(c.required());
186        assert!(c.is_required());
187    }
188
189    #[test]
190    fn parse_boolean_default_recognizes_truthy_spellings() {
191        for value in ["true", "TRUE", " true ", "1", "yes", "YES", "on"] {
192            assert_eq!(parse_boolean_default(value), Ok(Some(true)), "value: {:?}", value);
193        }
194    }
195
196    #[test]
197    fn parse_boolean_default_recognizes_falsy_spellings() {
198        for value in ["false", "FALSE", " false ", "0", "no", "NO", "off"] {
199            assert_eq!(parse_boolean_default(value), Ok(Some(false)), "value: {:?}", value);
200        }
201    }
202
203    #[test]
204    fn parse_boolean_default_null_sentinel_means_no_default() {
205        assert_eq!(parse_boolean_default("null"), Ok(None));
206        assert_eq!(parse_boolean_default("NULL"), Ok(None));
207        assert_eq!(parse_boolean_default(" null "), Ok(None));
208    }
209
210    #[test]
211    fn parse_boolean_default_rejects_unrecognized_values() {
212        for value in ["maybe", "T", "getdate()", ""] {
213            assert_eq!(parse_boolean_default(value), Err(()), "value: {:?}", value);
214        }
215    }
216
217    #[test]
218    fn needs_check_constraints_logic() {
219        let c = Column::new(None, "b", ColumnType::Boolean, 0, 0, false);
220        // boolean with non-native boolean mode => needs constraints
221        assert!(c.needs_check_constraints(BooleanMode::YesNo));
222        // boolean with native => no unless other attributes set
223        assert!(!c.needs_check_constraints(BooleanMode::Native));
224    }
225
226    #[test]
227    fn has_min_or_max_value() {
228        let c = Column::new(None, "n", ColumnType::Int, 0, 0, false);
229        assert!(!c.has_min_or_max_value());
230    }
231}