Skip to main content

yang_base/database/schema_sync/
mod.rs

1//! 基于模块 [`TableDefinition`] 的启动期保数据 schema 演进。
2//!
3//! 同步器创建缺失结构,并支持显式列改名、受控列修改、唯一索引、CHECK 与外键;
4//! 永不自动删除未知列、索引或约束。任何可能被旧数据阻止的变更都会先只读扫描,
5//! 返回表、对象和主键后拒绝全部 DDL。
6//!
7//! 方言差异集中在 [`dialect::SchemaDialect`],数据库访问由 [`driver::SchemaDriver`]
8//! 分派:MySQL 使用早前行为(`GET_LOCK`、DDL 隐式提交,预检先于 DDL);PostgreSQL
9//! 使用 `pg_advisory_lock(bigint)` 串行化多实例启动,先在同一事务内落地建表/加列
10//! 再预检(预检 SQL 因此能看到新列),违规则整体回滚;并发索引与
11//! `VALIDATE CONSTRAINT` 在提交后以 autocommit 执行。
12
13mod binding;
14mod dialect;
15mod driver;
16#[cfg(feature = "mysql")]
17mod inspect;
18mod model;
19#[cfg(feature = "postgres")]
20mod pg;
21mod plan;
22mod preflight;
23#[cfg(feature = "mysql")]
24mod render;
25mod sync;
26
27#[cfg(test)]
28mod __tests__;
29
30pub use binding::SchemaBindingMode;
31#[cfg(all(test, feature = "mysql"))]
32pub(super) use model::SchemaPreflightCheck;
33#[cfg(test)]
34pub(super) use model::{ExistingIndex, ExistingTableSchema};
35#[cfg(all(test, feature = "mysql"))]
36pub(super) use plan::plan_table_sync;
37#[cfg(all(test, feature = "postgres"))]
38pub(super) use plan::plan_table_sync_with;
39
40/// schema 同步变更类型。
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum SchemaSyncChangeKind {
44    /// 创建整张表。
45    CreatedTable,
46    /// 增加字段。
47    AddedColumn,
48    /// 原位改名字段并保留全部数据。
49    RenamedColumn,
50    /// 在旧数据预检通过后修改字段类型、NULL 或默认值。
51    ModifiedColumn,
52    /// 增加主键。
53    AddedPrimaryKey,
54    /// 增加普通或唯一索引。
55    AddedIndex,
56    /// 创建 PostgreSQL 原生枚举类型。
57    CreatedEnumType,
58    /// 向 PostgreSQL 原生枚举类型追加取值。
59    AddedEnumValue,
60    /// 增加 CHECK 约束。
61    AddedCheck,
62    /// 仅验证(`VALIDATE CONSTRAINT`)一个既有但尚未验证的 CHECK 约束。
63    ValidatedCheck,
64    /// 更新列注释(PostgreSQL `COMMENT ON COLUMN`)。
65    CommentedColumn,
66    /// 增加外键约束。
67    AddedForeignKey,
68    /// 仅验证(`VALIDATE CONSTRAINT`)一个既有但尚未验证的外键约束。
69    ValidatedForeignKey,
70}
71
72/// 一项实际执行的 schema 变更。
73#[derive(Debug, Clone, PartialEq, Eq)]
74#[non_exhaustive]
75pub struct SchemaSyncChange {
76    /// 表名。
77    pub table: String,
78    /// 变更对象;建表时等于表名,其它变更为字段或索引名。
79    pub object: String,
80    /// 变更类型。
81    pub kind: SchemaSyncChangeKind,
82}
83
84/// 一次同步后写入的所有权绑定。
85#[derive(Debug, Clone, PartialEq, Eq)]
86#[non_exhaustive]
87pub struct SchemaBindingChange {
88    /// 逻辑数据源;多源合并报告时必须与表名一起定位。
89    pub datasource: crate::datasource::DatasourceId,
90    /// 表名。
91    pub table: String,
92    /// 当前所有权模式。
93    pub mode: SchemaBindingMode,
94    /// 本次同步是否首次登记该表(存量表接管)。
95    pub newly_bound: bool,
96}
97
98/// 启动期 schema 同步报告。
99#[derive(Debug, Clone, Default, PartialEq, Eq)]
100#[non_exhaustive]
101pub struct SchemaSyncReport {
102    /// 已检查的表名,按名称确定性排序。
103    pub tables: Vec<String>,
104    /// 本次实际执行的 additive 变更。
105    pub changes: Vec<SchemaSyncChange>,
106    /// 事务内执行的 DDL 文本,供 dry-run 审计;实际同步时同样携带。
107    pub statements: Vec<String>,
108    /// 事务提交后执行的 deferred DDL 文本(`VALIDATE CONSTRAINT`、并发索引等)。
109    pub deferred_statements: Vec<String>,
110    /// 本次同步新增/更新的 `_yang_schema_binding` 记录。
111    pub bindings: Vec<SchemaBindingChange>,
112}
113
114/// 一项阻止 Schema 更新的旧数据问题。
115#[derive(Debug, Clone, PartialEq, Eq)]
116#[non_exhaustive]
117pub struct SchemaDataViolation {
118    /// 问题表。
119    pub table: String,
120    /// 将要增加的约束或索引名。
121    pub object: String,
122    /// 命中的主键文本,最多返回 20 条且按主键排序。
123    pub primary_keys: Vec<String>,
124}
125
126/// 只读 Schema 预检结果。
127#[derive(Debug, Clone, Default, PartialEq, Eq)]
128#[non_exhaustive]
129pub struct SchemaPreflightReport {
130    /// 待执行的结构变更。
131    pub plan: SchemaSyncReport,
132    /// 必须人工处理的旧数据问题。
133    pub violations: Vec<SchemaDataViolation>,
134}
135
136impl SchemaPreflightReport {
137    /// 是否可以安全进入 DDL 阶段。
138    pub fn is_safe(&self) -> bool {
139        self.violations.is_empty()
140    }
141}
142
143impl SchemaSyncReport {
144    /// 是否没有执行任何 DDL。
145    pub fn is_noop(&self) -> bool {
146        self.changes.is_empty()
147    }
148}