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}
17
18impl SchemaColumn {
19    /// 构造列快照;类型名称会统一转为 ASCII 小写。
20    pub fn new(
21        name: impl Into<String>,
22        data_type: impl Into<String>,
23        column_type: impl Into<String>,
24        nullable: bool,
25        max_length: Option<u64>,
26    ) -> Self {
27        Self {
28            name: name.into(),
29            data_type: data_type.into().to_ascii_lowercase(),
30            column_type: column_type.into().to_ascii_lowercase(),
31            nullable,
32            max_length,
33        }
34    }
35}
36
37/// TableConfig 运行期契约与数据库列不兼容的原因。
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum SchemaIssueKind {
41    /// 声明字段在数据库中不存在。
42    MissingColumn,
43    /// 数据库列不能承载声明的运行期字段类型。
44    IncompatibleType,
45    /// 必填字段在数据库中仍允许 NULL。
46    NullabilityMismatch,
47}
48
49/// 一项 schema 兼容性问题。
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct SchemaIssue {
52    /// TableConfig 字段名。
53    pub field: String,
54    /// 问题类型。
55    pub kind: SchemaIssueKind,
56    /// TableConfig 的期望描述。
57    pub expected: String,
58    /// 数据库实际描述;缺列时为 None。
59    pub actual: Option<String>,
60}
61
62/// TableConfig 对当前数据库 schema 的只读验证报告。
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct SchemaValidationReport {
65    /// 被验证的表名。
66    pub table: String,
67    /// 确定性排序的问题列表。
68    pub issues: Vec<SchemaIssue>,
69}
70
71impl SchemaValidationReport {
72    /// 当前数据库是否足以承载 TableConfig 声明的运行期访问契约。
73    pub fn is_compatible(&self) -> bool {
74        self.issues.is_empty()
75    }
76}
77
78impl TableConfig {
79    /// 验证声明字段能否由给定数据库列提供。
80    ///
81    /// 这是只读、单向的运行期兼容检查:数据库额外列、索引、默认值、触发器等不属于
82    /// TableConfig 的所有权范围,因此不会作为问题,也不会生成 ALTER/回滚 SQL。
83    pub fn validate_schema(&self, columns: &[SchemaColumn]) -> SchemaValidationReport {
84        let mut fields: Vec<_> = self.fields.values().collect();
85        fields.sort_by(|left, right| left.name.cmp(&right.name));
86        let mut issues = Vec::new();
87
88        for field in fields {
89            let Some(column) = columns.iter().find(|column| column.name == field.name) else {
90                issues.push(SchemaIssue {
91                    field: field.name.clone(),
92                    kind: SchemaIssueKind::MissingColumn,
93                    expected: field.field_type.display_name().to_string(),
94                    actual: None,
95                });
96                continue;
97            };
98            if !is_type_compatible(&field.field_type, column) {
99                issues.push(SchemaIssue {
100                    field: field.name.clone(),
101                    kind: SchemaIssueKind::IncompatibleType,
102                    expected: field.field_type.display_name().to_string(),
103                    actual: Some(column.column_type.clone()),
104                });
105            }
106            if field.required && column.nullable {
107                issues.push(SchemaIssue {
108                    field: field.name.clone(),
109                    kind: SchemaIssueKind::NullabilityMismatch,
110                    expected: "NOT NULL".to_string(),
111                    actual: Some("NULL".to_string()),
112                });
113            }
114        }
115
116        SchemaValidationReport {
117            table: self.table_name.clone(),
118            issues,
119        }
120    }
121}
122
123fn is_type_compatible(field_type: &FieldType, column: &SchemaColumn) -> bool {
124    let data_type = column.data_type.as_str();
125    match field_type {
126        FieldType::String { max_length } => {
127            matches!(data_type, "varchar" | "char")
128                && column
129                    .max_length
130                    .is_some_and(|actual| actual >= *max_length as u64)
131        }
132        FieldType::Integer => matches!(
133            data_type,
134            "tinyint" | "smallint" | "mediumint" | "int" | "integer" | "bigint"
135        ),
136        FieldType::BigInt => data_type == "bigint",
137        FieldType::Float => matches!(data_type, "float" | "double" | "decimal"),
138        FieldType::Double => matches!(data_type, "double" | "decimal"),
139        FieldType::Boolean => {
140            matches!(data_type, "bool" | "boolean")
141                || (data_type == "tinyint" && column.column_type.starts_with("tinyint(1)"))
142        }
143        FieldType::Date => data_type == "date",
144        FieldType::DateTime => matches!(data_type, "datetime" | "timestamp"),
145        FieldType::Timestamp => data_type == "bigint",
146        FieldType::Json => data_type == "json",
147        FieldType::Text => matches!(data_type, "tinytext" | "text" | "mediumtext" | "longtext"),
148        FieldType::Enum { .. } => matches!(data_type, "enum" | "varchar" | "char"),
149        FieldType::ForeignKey { .. } => true,
150    }
151}