Skip to main content

yang_base/database/schema_sync/
mod.rs

1//! 基于模块 [`TableDefinition`] 的 MySQL 启动期保数据 schema 演进。
2//!
3//! 同步器创建缺失结构,并支持显式列改名、受控列修改、唯一索引、CHECK 与外键;
4//! 永不自动删除未知列、索引或约束。任何可能被旧数据阻止的变更都会先只读扫描,
5//! 返回表、对象和主键后拒绝全部 DDL。多实例启动使用同一 MySQL 会话持有 advisory
6//! lock,DDL 中断后可按 information_schema 重新规划并幂等续作。
7
8mod inspect;
9mod model;
10mod plan;
11mod preflight;
12mod render;
13mod sync;
14
15#[cfg(test)]
16mod __tests__;
17
18#[cfg(test)]
19pub(super) use model::{ExistingIndex, ExistingTableSchema};
20#[cfg(test)]
21pub(super) use plan::plan_table_sync;
22
23/// schema 同步变更类型。
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum SchemaSyncChangeKind {
27    /// 创建整张表。
28    CreatedTable,
29    /// 增加字段。
30    AddedColumn,
31    /// 原位改名字段并保留全部数据。
32    RenamedColumn,
33    /// 在旧数据预检通过后修改字段类型、NULL 或默认值。
34    ModifiedColumn,
35    /// 增加主键。
36    AddedPrimaryKey,
37    /// 增加普通或唯一索引。
38    AddedIndex,
39    /// 增加 CHECK 约束。
40    AddedCheck,
41    /// 增加外键约束。
42    AddedForeignKey,
43}
44
45/// 一项实际执行的 schema 变更。
46#[derive(Debug, Clone, PartialEq, Eq)]
47#[non_exhaustive]
48pub struct SchemaSyncChange {
49    /// 表名。
50    pub table: String,
51    /// 变更对象;建表时等于表名,其它变更为字段或索引名。
52    pub object: String,
53    /// 变更类型。
54    pub kind: SchemaSyncChangeKind,
55}
56
57/// 启动期 schema 同步报告。
58#[derive(Debug, Clone, Default, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct SchemaSyncReport {
61    /// 已检查的表名,按名称确定性排序。
62    pub tables: Vec<String>,
63    /// 本次实际执行的 additive 变更。
64    pub changes: Vec<SchemaSyncChange>,
65}
66
67/// 一项阻止 Schema 更新的旧数据问题。
68#[derive(Debug, Clone, PartialEq, Eq)]
69#[non_exhaustive]
70pub struct SchemaDataViolation {
71    /// 问题表。
72    pub table: String,
73    /// 将要增加的约束或索引名。
74    pub object: String,
75    /// 命中的主键文本,最多返回 20 条且按主键排序。
76    pub primary_keys: Vec<String>,
77}
78
79/// 只读 Schema 预检结果。
80#[derive(Debug, Clone, Default, PartialEq, Eq)]
81#[non_exhaustive]
82pub struct SchemaPreflightReport {
83    /// 待执行的结构变更。
84    pub plan: SchemaSyncReport,
85    /// 必须人工处理的旧数据问题。
86    pub violations: Vec<SchemaDataViolation>,
87}
88
89impl SchemaPreflightReport {
90    /// 是否可以安全进入 DDL 阶段。
91    pub fn is_safe(&self) -> bool {
92        self.violations.is_empty()
93    }
94}
95
96impl SchemaSyncReport {
97    /// 是否没有执行任何 DDL。
98    pub fn is_noop(&self) -> bool {
99        self.changes.is_empty()
100    }
101}