Skip to main content

yang_base/table/
schema_validation.rs

1use super::{FieldType, TableConfig};
2
3/// 数据库 introspection 得到的最小列快照。
4#[derive(Debug, Clone, PartialEq, Eq)]
5pub struct SchemaColumn {
6    /// 列名。
7    pub name: String,
8    /// information_schema 的规范数据类型。
9    pub data_type: String,
10    /// 方言完整列类型,如 `varchar(255)` / `tinyint(1)`。
11    pub column_type: String,
12    /// 数据库是否允许 NULL。
13    pub nullable: bool,
14    /// 字符列最大长度。
15    pub max_length: Option<u64>,
16    /// information_schema 返回的数据库默认值;无默认值和 DEFAULT NULL 均为 None。
17    pub database_default: Option<String>,
18}
19
20impl SchemaColumn {
21    /// 构造列快照;类型名称会统一转为 ASCII 小写。
22    pub fn new(
23        name: impl Into<String>,
24        data_type: impl Into<String>,
25        column_type: impl Into<String>,
26        nullable: bool,
27        max_length: Option<u64>,
28        database_default: Option<String>,
29    ) -> Self {
30        Self {
31            name: name.into(),
32            data_type: data_type.into().to_ascii_lowercase(),
33            column_type: column_type.into(),
34            nullable,
35            max_length,
36            database_default,
37        }
38    }
39
40    /// 在完整列类型描述中标记 `AUTO_INCREMENT`。
41    ///
42    /// 该信息保存在 `column_type` 描述中,便于与 information_schema 的其它列属性
43    /// 一起形成单个只读快照。
44    pub fn with_auto_increment(mut self, auto_increment: bool) -> Self {
45        let has_marker = self
46            .column_type
47            .split_whitespace()
48            .any(|part| part.eq_ignore_ascii_case("auto_increment"));
49        if auto_increment && !has_marker {
50            self.column_type.push_str(" auto_increment");
51        }
52        self
53    }
54}
55
56/// [`super::TableDefinition`] 与数据库列不兼容的原因。
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58#[non_exhaustive]
59pub enum SchemaIssueKind {
60    /// 声明字段在数据库中不存在。
61    MissingColumn,
62    /// 数据库列不能承载声明的运行期字段类型。
63    IncompatibleType,
64    /// 必填字段在数据库中仍允许 NULL。
65    NullabilityMismatch,
66    /// 声明要求自增,但数据库列没有自增属性,或反之。
67    AutoIncrementMismatch,
68    /// 声明默认值与数据库默认值不一致。
69    DefaultMismatch,
70}
71
72/// 一项 schema 兼容性问题。
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub struct SchemaIssue {
75    /// 表定义中的字段名。
76    pub field: String,
77    /// 问题类型。
78    pub kind: SchemaIssueKind,
79    /// 表定义的期望描述。
80    pub expected: String,
81    /// 数据库实际描述;缺列时为 None。
82    pub actual: Option<String>,
83}
84
85/// [`super::TableDefinition`] 对当前数据库 schema 的只读验证报告。
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct SchemaValidationReport {
88    /// 被验证的表名。
89    pub table: String,
90    /// 确定性排序的问题列表。
91    pub issues: Vec<SchemaIssue>,
92}
93
94impl SchemaValidationReport {
95    /// 当前数据库是否足以承载表定义声明的运行期访问契约。
96    pub fn is_compatible(&self) -> bool {
97        self.issues.is_empty()
98    }
99}
100
101impl TableConfig {
102    /// 验证声明字段能否由给定数据库列提供。
103    ///
104    /// 这是只读的运行期契约检查:数据库额外列、索引、触发器等不属于表定义的
105    /// 所有权范围,因此不会作为问题,也不会生成 ALTER/回滚 SQL。
106    pub fn validate_schema(&self, columns: &[SchemaColumn]) -> SchemaValidationReport {
107        let mut fields: Vec<_> = self.fields.values().collect();
108        fields.sort_by(|left, right| left.name.cmp(&right.name));
109        let mut issues = Vec::new();
110
111        for field in fields {
112            let Some(column) = columns.iter().find(|column| column.name == field.name) else {
113                issues.push(SchemaIssue {
114                    field: field.name.clone(),
115                    kind: SchemaIssueKind::MissingColumn,
116                    expected: field.field_type.display_name().to_string(),
117                    actual: None,
118                });
119                continue;
120            };
121            if !is_type_compatible(&field.field_type, column) {
122                issues.push(SchemaIssue {
123                    field: field.name.clone(),
124                    kind: SchemaIssueKind::IncompatibleType,
125                    expected: field.field_type.display_name().to_string(),
126                    actual: Some(column.column_type.clone()),
127                });
128            }
129            let expected_nullable = !field.required;
130            if expected_nullable != column.nullable {
131                issues.push(SchemaIssue {
132                    field: field.name.clone(),
133                    kind: SchemaIssueKind::NullabilityMismatch,
134                    expected: if expected_nullable {
135                        "NULL".to_string()
136                    } else {
137                        "NOT NULL".to_string()
138                    },
139                    actual: Some(if column.nullable {
140                        "NULL".to_string()
141                    } else {
142                        "NOT NULL".to_string()
143                    }),
144                });
145            }
146            let actual_auto_increment = column
147                .column_type
148                .split_whitespace()
149                .any(|part| part.eq_ignore_ascii_case("auto_increment"));
150            if field.auto_increment != actual_auto_increment {
151                issues.push(SchemaIssue {
152                    field: field.name.clone(),
153                    kind: SchemaIssueKind::AutoIncrementMismatch,
154                    expected: if field.auto_increment {
155                        "AUTO_INCREMENT".to_string()
156                    } else {
157                        "非 AUTO_INCREMENT".to_string()
158                    },
159                    actual: Some(if actual_auto_increment {
160                        "AUTO_INCREMENT".to_string()
161                    } else {
162                        "非 AUTO_INCREMENT".to_string()
163                    }),
164                });
165            }
166            let expected_default =
167                normalize_declared_default(&field.field_type, field.default_value.as_ref());
168            let actual_default =
169                normalize_database_default(&field.field_type, column.database_default.as_deref());
170            if expected_default != actual_default {
171                issues.push(SchemaIssue {
172                    field: field.name.clone(),
173                    kind: SchemaIssueKind::DefaultMismatch,
174                    expected: describe_default(expected_default.as_deref()),
175                    actual: Some(describe_default(actual_default.as_deref())),
176                });
177            }
178        }
179
180        SchemaValidationReport {
181            table: self.table_name.clone(),
182            issues,
183        }
184    }
185}
186
187fn is_type_compatible(field_type: &FieldType, column: &SchemaColumn) -> bool {
188    let data_type = column.data_type.as_str();
189    match field_type {
190        FieldType::String { max_length } => {
191            matches!(data_type, "varchar" | "char")
192                && column
193                    .max_length
194                    .is_some_and(|actual| actual >= *max_length as u64)
195        }
196        FieldType::Integer => matches!(
197            data_type,
198            "tinyint" | "smallint" | "mediumint" | "int" | "integer" | "bigint"
199        ),
200        FieldType::BigInt => data_type == "bigint",
201        FieldType::Float => matches!(data_type, "float" | "double" | "decimal"),
202        FieldType::Double => matches!(data_type, "double" | "decimal"),
203        FieldType::Decimal { precision, scale } => {
204            data_type == "decimal"
205                && column
206                    .column_type
207                    .eq_ignore_ascii_case(&format!("decimal({precision},{scale})"))
208        }
209        FieldType::Boolean => {
210            matches!(data_type, "bool" | "boolean")
211                || (data_type == "tinyint"
212                    && column
213                        .column_type
214                        .to_ascii_lowercase()
215                        .starts_with("tinyint(1)"))
216        }
217        FieldType::Date => data_type == "date",
218        FieldType::DateTime => data_type == "datetime",
219        FieldType::Timestamp => data_type == "bigint",
220        FieldType::Json => data_type == "json",
221        FieldType::Text => matches!(data_type, "text" | "mediumtext" | "longtext"),
222        FieldType::Enum { values } => {
223            data_type == "enum"
224                && parse_mysql_enum_values(&column.column_type)
225                    .is_some_and(|actual| actual.as_slice() == values.as_slice())
226        }
227    }
228}
229
230fn normalize_declared_default(
231    field_type: &FieldType,
232    default: Option<&serde_json::Value>,
233) -> Option<String> {
234    let value = default?;
235    if value.is_null() {
236        return None;
237    }
238    match field_type {
239        FieldType::Boolean => value
240            .as_bool()
241            .map(|value| if value { "1" } else { "0" }.to_string()),
242        FieldType::Float | FieldType::Double => value.as_f64().map(normalize_float),
243        FieldType::Decimal { .. } => match value {
244            serde_json::Value::String(value) => Some(value.clone()),
245            serde_json::Value::Number(value) => Some(value.to_string()),
246            _ => None,
247        },
248        _ => match value {
249            serde_json::Value::String(value) => Some(value.clone()),
250            serde_json::Value::Number(value) => Some(value.to_string()),
251            serde_json::Value::Bool(value) => Some(if *value { "1" } else { "0" }.to_string()),
252            serde_json::Value::Null
253            | serde_json::Value::Array(_)
254            | serde_json::Value::Object(_) => None,
255        },
256    }
257}
258
259fn normalize_database_default(field_type: &FieldType, default: Option<&str>) -> Option<String> {
260    let value = default?;
261    match field_type {
262        FieldType::Boolean => match value.to_ascii_lowercase().as_str() {
263            "1" | "true" => Some("1".to_string()),
264            "0" | "false" => Some("0".to_string()),
265            _ => Some(value.to_string()),
266        },
267        FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
268            value.parse::<i64>().map_or_else(
269                |_| Some(value.to_string()),
270                |number| Some(number.to_string()),
271            )
272        }
273        FieldType::Float | FieldType::Double => value
274            .parse::<f64>()
275            .ok()
276            .filter(|number| number.is_finite())
277            .map_or_else(
278                || Some(value.to_string()),
279                |number| Some(normalize_float(number)),
280            ),
281        FieldType::Decimal { .. } => Some(value.to_string()),
282        _ => Some(value.to_string()),
283    }
284}
285
286fn normalize_float(value: f64) -> String {
287    if value == 0.0 {
288        "0".to_string()
289    } else {
290        value.to_string()
291    }
292}
293
294fn describe_default(default: Option<&str>) -> String {
295    default.map_or_else(
296        || "无默认值(等价于 DEFAULT NULL)".to_string(),
297        |value| format!("规范默认值 {value:?}"),
298    )
299}
300
301fn parse_mysql_enum_values(column_type: &str) -> Option<Vec<String>> {
302    let column_type = column_type.trim();
303    let opening = column_type.find('(')?;
304    if !column_type[..opening].trim().eq_ignore_ascii_case("enum") || !column_type.ends_with(')') {
305        return None;
306    }
307    let mut chars = column_type[opening + 1..column_type.len() - 1]
308        .chars()
309        .peekable();
310    let mut values = Vec::new();
311
312    loop {
313        while chars
314            .next_if(|character| character.is_whitespace())
315            .is_some()
316        {}
317        if chars.peek().is_none() {
318            break;
319        }
320        if chars.next()? != '\'' {
321            return None;
322        }
323
324        let mut value = String::new();
325        loop {
326            match chars.next()? {
327                '\\' => {
328                    let escaped = chars.next()?;
329                    value.push(match escaped {
330                        '0' => '\0',
331                        'n' => '\n',
332                        'r' => '\r',
333                        't' => '\t',
334                        'Z' => '\u{001a}',
335                        other => other,
336                    });
337                }
338                '\'' if chars.peek() == Some(&'\'') => {
339                    chars.next();
340                    value.push('\'');
341                }
342                '\'' => break,
343                character => value.push(character),
344            }
345        }
346        values.push(value);
347
348        while chars
349            .next_if(|character| character.is_whitespace())
350            .is_some()
351        {}
352        match chars.peek() {
353            Some(',') => {
354                chars.next();
355            }
356            None => break,
357            Some(_) => return None,
358        }
359    }
360
361    Some(values)
362}