Skip to main content

sqltrail_core/
model.rs

1//! 结构模型:描述数据库的「期望结构」与「实际结构」。
2//!
3//! 本模块是纯数据定义,不依赖数据库连接。
4//! 所有业务表结构最终都会被转换为 [`SchemaModel`],
5//! 差异计算(`diff.rs`)与迁移计划(`plan.rs`)都基于该模型进行。
6
7use serde::{Deserialize, Serialize};
8
9/// 数据库整体结构:schema 列表 + 表列表。
10///
11/// 三种来源都会归一化到该模型:
12/// 1. Rust struct(期望结构,由 `#[derive(DbSchema)]` 生成)
13/// 2. PostgreSQL 元数据(实际结构,由 introspection 读取)
14#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
15pub struct SchemaModel {
16    /// 是否把表/字段注释纳入差异管理。默认 false,兼容旧 JSON。
17    #[serde(default)]
18    pub manage_comments: bool,
19    /// 是否把数据库函数纳入差异管理。默认 false,兼容旧 JSON。
20    #[serde(default)]
21    pub manage_functions: bool,
22    /// 需要确保存在的 schema 名称(`public` 由 PostgreSQL 自带,无需列出)
23    pub schemas: Vec<String>,
24    /// 全部业务表(期望结构或实际结构)
25    pub tables: Vec<TableModel>,
26    /// 数据库函数。函数以 schema + 名称 + identity arguments 唯一标识。
27    #[serde(default)]
28    pub functions: Vec<FunctionModel>,
29}
30
31impl SchemaModel {
32    /// 构造一个完整的结构模型
33    pub fn new(schemas: Vec<String>, tables: Vec<TableModel>) -> Self {
34        Self {
35            manage_comments: false,
36            manage_functions: false,
37            schemas,
38            tables,
39            functions: Vec::new(),
40        }
41    }
42
43    /// 构造包含数据库函数的完整模型。
44    pub fn with_functions(
45        schemas: Vec<String>,
46        tables: Vec<TableModel>,
47        functions: Vec<FunctionModel>,
48    ) -> Self {
49        let manage_comments = tables.iter().any(|table| {
50            table.comment.is_some() || table.columns.iter().any(|column| column.comment.is_some())
51        }) || functions.iter().any(|function| function.comment.is_some());
52        Self {
53            manage_comments,
54            manage_functions: true,
55            schemas,
56            tables,
57            functions,
58        }
59    }
60
61    /// 由一组表构造模型,并自动收集它们所属的 schema(跳过 `public`)
62    pub fn from_tables(tables: Vec<TableModel>) -> Self {
63        let mut schemas = Vec::new();
64        for t in &tables {
65            if t.schema != "public" && !schemas.contains(&t.schema) {
66                schemas.push(t.schema.clone());
67            }
68        }
69        let manage_comments = tables.iter().any(|table| {
70            table.comment.is_some() || table.columns.iter().any(|column| column.comment.is_some())
71        });
72        Self {
73            manage_comments,
74            manage_functions: false,
75            schemas,
76            tables,
77            functions: Vec::new(),
78        }
79    }
80
81    /// 是否没有任何受管理对象
82    pub fn is_empty(&self) -> bool {
83        self.tables.is_empty() && (!self.manage_functions || self.functions.is_empty())
84    }
85}
86
87/// 单张表的期望/实际结构。
88#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
89pub struct TableModel {
90    /// 所属 schema 名称,例如 auth、flow、finance、public
91    pub schema: String,
92    /// 表名
93    pub name: String,
94    /// 当前表名由旧名改名而来时填写旧表名,用于生成 RENAME 迁移。
95    /// 重命名不允许按名称相似度猜测,必须显式声明。
96    pub rename_from: Option<String>,
97    /// `COMMENT ON TABLE` 的内容;`None` 表示不设置注释。
98    #[serde(default)]
99    pub comment: Option<String>,
100    /// 字段列表(按创建顺序)
101    pub columns: Vec<ColumnModel>,
102    /// 主键约束(单列或联合主键)
103    pub primary_key: Option<PrimaryKeyModel>,
104    /// 唯一约束(表级;单字段唯一约束也会归一化到这里)
105    pub unique_constraints: Vec<UniqueConstraintModel>,
106    /// 外键约束
107    pub foreign_keys: Vec<ForeignKeyModel>,
108    /// 普通索引(不含主键/唯一约束背书的索引)
109    pub indexes: Vec<IndexModel>,
110}
111
112impl TableModel {
113    /// 表在结构比较中的唯一键:schema + 表名
114    pub fn key(&self) -> (String, String) {
115        (self.schema.clone(), self.name.clone())
116    }
117}
118
119/// 字段(列)模型。
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct ColumnModel {
122    /// 数据库字段名
123    pub name: String,
124    /// PostgreSQL 类型,例如 bigint、varchar(64)、timestamptz、jsonb
125    pub sql_type: String,
126    /// 是否可空(`Option<T>` 默认可空)
127    pub nullable: bool,
128    /// 是否主键字段(单列主键;联合主键请使用 [`TableModel::primary_key`])
129    pub primary_key: bool,
130    /// 当前字段由旧字段名改名而来时填写旧字段名
131    pub rename_from: Option<String>,
132    /// 数据库默认值表达式,例如 now()、'{}'、gen_random_uuid()::text
133    pub default_sql: Option<String>,
134    /// `COMMENT ON COLUMN` 的内容;`None` 表示不设置注释。
135    #[serde(default)]
136    pub comment: Option<String>,
137}
138
139/// 主键约束模型。
140#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
141pub struct PrimaryKeyModel {
142    /// 约束名(实际结构来自数据库;期望结构通常为 None,让数据库自动命名)
143    pub name: Option<String>,
144    /// 主键字段(按顺序,联合主键时多于一个)
145    pub columns: Vec<String>,
146}
147
148/// 唯一约束模型。
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150pub struct UniqueConstraintModel {
151    /// 约束名(可空,数据库会自动命名)
152    pub name: Option<String>,
153    /// 参与唯一约束的字段(按顺序)
154    pub columns: Vec<String>,
155}
156
157/// 外键约束模型。
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159pub struct ForeignKeyModel {
160    /// 约束名(可空,数据库会自动命名)
161    pub name: Option<String>,
162    /// 本地字段(按顺序)
163    pub columns: Vec<String>,
164    /// 引用表,格式为 "schema.table" 或 "table"(与本地同 schema 时可省略 schema)
165    pub ref_table: String,
166    /// 引用字段(按顺序)
167    pub ref_columns: Vec<String>,
168    /// ON DELETE 规则:CASCADE / SET NULL / RESTRICT / SET DEFAULT;缺省为 NO ACTION
169    pub on_delete: Option<String>,
170    /// ON UPDATE 规则,同上
171    pub on_update: Option<String>,
172}
173
174/// 普通索引模型(不含主键/唯一约束背书的索引)。
175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176pub struct IndexModel {
177    /// 索引名(可空,数据库会自动命名)
178    pub name: Option<String>,
179    /// 索引字段(按顺序)
180    pub columns: Vec<String>,
181    /// 是否唯一索引
182    pub unique: bool,
183    /// 部分索引条件,例如 `WHERE deleted_at IS NOT NULL`
184    pub predicate: Option<String>,
185}
186
187/// PostgreSQL 数据库函数。
188///
189/// `identity_arguments` 使用 PostgreSQL 可用于 `DROP FUNCTION` / `COMMENT ON FUNCTION`
190/// 的参数类型列表,例如 `"integer, text"`;无参数函数使用空字符串。
191/// `definition_sql` 是完整的 `CREATE OR REPLACE FUNCTION ...` 定义。
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub struct FunctionModel {
194    pub schema: String,
195    pub name: String,
196    #[serde(default)]
197    pub identity_arguments: String,
198    pub definition_sql: String,
199    #[serde(default)]
200    pub comment: Option<String>,
201}
202
203impl FunctionModel {
204    /// 函数重载的唯一键。
205    pub fn key(&self) -> (String, String, String) {
206        (
207            self.schema.clone(),
208            self.name.clone(),
209            normalize_identity_arguments(&self.identity_arguments),
210        )
211    }
212}
213
214/// 归一化函数 identity arguments 中无意义的空白。
215pub fn normalize_identity_arguments(arguments: &str) -> String {
216    arguments
217        .split(',')
218        .map(str::trim)
219        .collect::<Vec<_>>()
220        .join(", ")
221}