Skip to main content

yang_base/table/
schema_validation.rs

1use super::{FieldType, TableConfig, MYSQL_MAX_VARCHAR_LENGTH};
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            // 这是 MySQL 语义的只读契约检查:超过 MySQL 上界的声明(双 feature
192            // 构建期允许 PostgreSQL 上界)在 MySQL 后端一律判为不兼容。
193            *max_length <= MYSQL_MAX_VARCHAR_LENGTH
194                && matches!(data_type, "varchar" | "char")
195                && column
196                    .max_length
197                    .is_some_and(|actual| actual >= *max_length as u64)
198        }
199        FieldType::Integer => matches!(
200            data_type,
201            "smallint" | "mediumint" | "int" | "integer" | "bigint"
202        ),
203        FieldType::BigInt => data_type == "bigint",
204        FieldType::Float => matches!(data_type, "float" | "double" | "decimal"),
205        FieldType::Double => matches!(data_type, "double" | "decimal"),
206        FieldType::Decimal { precision, scale } => {
207            data_type == "decimal"
208                && column
209                    .column_type
210                    .eq_ignore_ascii_case(&format!("decimal({precision},{scale})"))
211        }
212        FieldType::Boolean => {
213            matches!(data_type, "bool" | "boolean")
214                || (data_type == "tinyint"
215                    && column
216                        .column_type
217                        .to_ascii_lowercase()
218                        .starts_with("tinyint(1)"))
219        }
220        FieldType::Date => data_type == "date",
221        FieldType::DateTime => data_type == "datetime",
222        FieldType::Timestamp => data_type == "bigint",
223        FieldType::Json => data_type == "json",
224        FieldType::Text => matches!(data_type, "text" | "mediumtext" | "longtext"),
225        FieldType::Enum { values } => {
226            data_type == "enum"
227                && parse_mysql_enum_values(&column.column_type)
228                    .is_some_and(|actual| actual.as_slice() == values.as_slice())
229        }
230        // MySQL 方言:UUID 映射为 CHAR(36)。
231        FieldType::Uuid => {
232            matches!(data_type, "char" | "varchar")
233                && column.max_length.is_some_and(|actual| actual >= 36)
234        }
235        // MySQL 方言:二进制映射为 BLOB / BINARY / VARBINARY 族。
236        FieldType::Bytes => {
237            matches!(data_type, "blob" | "tinyblob" | "mediumblob" | "longblob")
238                || matches!(data_type, "binary" | "varbinary")
239        }
240        // MySQL 没有数组类型,声明了也无法由任何 MySQL 列承载。
241        FieldType::Array(_) => false,
242    }
243}
244
245fn normalize_declared_default(
246    field_type: &FieldType,
247    default: Option<&serde_json::Value>,
248) -> Option<String> {
249    let value = default?;
250    if value.is_null() {
251        return None;
252    }
253    match field_type {
254        FieldType::Boolean => value
255            .as_bool()
256            .map(|value| if value { "1" } else { "0" }.to_string()),
257        FieldType::Float | FieldType::Double => value.as_f64().map(normalize_float),
258        FieldType::Decimal { .. } => match value {
259            serde_json::Value::String(value) => Some(value.clone()),
260            serde_json::Value::Number(value) => Some(value.to_string()),
261            _ => None,
262        },
263        _ => match value {
264            serde_json::Value::String(value) => Some(value.clone()),
265            serde_json::Value::Number(value) => Some(value.to_string()),
266            serde_json::Value::Bool(value) => Some(if *value { "1" } else { "0" }.to_string()),
267            serde_json::Value::Null
268            | serde_json::Value::Array(_)
269            | serde_json::Value::Object(_) => None,
270        },
271    }
272}
273
274fn normalize_database_default(field_type: &FieldType, default: Option<&str>) -> Option<String> {
275    let value = default?;
276    match field_type {
277        FieldType::Boolean => match value.to_ascii_lowercase().as_str() {
278            "1" | "true" => Some("1".to_string()),
279            "0" | "false" => Some("0".to_string()),
280            _ => Some(value.to_string()),
281        },
282        FieldType::Integer | FieldType::BigInt | FieldType::Timestamp => {
283            value.parse::<i64>().map_or_else(
284                |_| Some(value.to_string()),
285                |number| Some(number.to_string()),
286            )
287        }
288        FieldType::Float | FieldType::Double => value
289            .parse::<f64>()
290            .ok()
291            .filter(|number| number.is_finite())
292            .map_or_else(
293                || Some(value.to_string()),
294                |number| Some(normalize_float(number)),
295            ),
296        FieldType::Decimal { .. } => Some(value.to_string()),
297        _ => Some(value.to_string()),
298    }
299}
300
301fn normalize_float(value: f64) -> String {
302    if value == 0.0 {
303        "0".to_string()
304    } else {
305        value.to_string()
306    }
307}
308
309fn describe_default(default: Option<&str>) -> String {
310    default.map_or_else(
311        || "无默认值(等价于 DEFAULT NULL)".to_string(),
312        |value| format!("规范默认值 {value:?}"),
313    )
314}
315
316fn parse_mysql_enum_values(column_type: &str) -> Option<Vec<String>> {
317    let column_type = column_type.trim();
318    let opening = column_type.find('(')?;
319    if !column_type[..opening].trim().eq_ignore_ascii_case("enum") || !column_type.ends_with(')') {
320        return None;
321    }
322    let mut chars = column_type[opening + 1..column_type.len() - 1]
323        .chars()
324        .peekable();
325    let mut values = Vec::new();
326
327    loop {
328        while chars
329            .next_if(|character| character.is_whitespace())
330            .is_some()
331        {}
332        if chars.peek().is_none() {
333            break;
334        }
335        if chars.next()? != '\'' {
336            return None;
337        }
338
339        let mut value = String::new();
340        loop {
341            match chars.next()? {
342                '\\' => {
343                    let escaped = chars.next()?;
344                    value.push(match escaped {
345                        '0' => '\0',
346                        'n' => '\n',
347                        'r' => '\r',
348                        't' => '\t',
349                        'Z' => '\u{001a}',
350                        other => other,
351                    });
352                }
353                '\'' if chars.peek() == Some(&'\'') => {
354                    chars.next();
355                    value.push('\'');
356                }
357                '\'' => break,
358                character => value.push(character),
359            }
360        }
361        values.push(value);
362
363        while chars
364            .next_if(|character| character.is_whitespace())
365            .is_some()
366        {}
367        match chars.peek() {
368            Some(',') => {
369                chars.next();
370            }
371            None => break,
372            Some(_) => return None,
373        }
374    }
375
376    Some(values)
377}