Skip to main content

sqltrail_core/
diff.rs

1//! 结构差异计算:比较「期望结构」与「实际结构」,产生 [`SchemaDiff`]。
2//!
3//! 差异计算是纯函数,不依赖数据库连接,因此可以针对每一种差异编写单元测试。
4//! 规则要点:
5//! - 重命名(表/字段)必须通过 `rename_from` 显式声明,绝不按名称相似度猜测。
6//! - 类型/可空性/默认值的变化会单独归类,供后续阶段进行危险等级判断。
7
8use std::collections::HashSet;
9
10use serde::{Deserialize, Serialize};
11
12use crate::model::*;
13
14/// 顶层差异:需要新建的 schema + 各表差异。
15#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
16pub struct SchemaDiff {
17    /// 期望结构中存在、但数据库中不存在的 schema
18    pub create_schemas: Vec<String>,
19    /// 每张表的差异
20    pub tables: Vec<TableDiff>,
21    /// 数据库函数差异
22    pub functions: Vec<FunctionDiff>,
23}
24
25/// 注释变化。`desired = None` 表示删除现有注释。
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
27pub struct CommentChange {
28    pub desired: Option<String>,
29}
30
31/// 单张表的差异类型。
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub enum TableDiff {
34    /// 数据库中不存在该表,需要新建
35    CreateTable(TableModel),
36    /// 期望结构中不存在该表,需要删除(危险操作)
37    DropTable { schema: String, name: String },
38    /// 通过 rename_from 显式声明的表重命名
39    RenameTable {
40        schema: String,
41        old_name: String,
42        new_name: String,
43    },
44    /// 表已存在,需要修改其字段/约束/索引
45    AlterTable {
46        schema: String,
47        name: String,
48        columns: Vec<ColumnDiff>,
49        primary_key: Option<PrimaryKeyDiff>,
50        uniques: Vec<ConstraintDiff>,
51        foreign_keys: Vec<ForeignKeyDiff>,
52        indexes: Vec<IndexDiff>,
53        table_comment: Option<CommentChange>,
54    },
55}
56
57/// 字段级差异类型。
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59pub enum ColumnDiff {
60    /// 新增字段
61    AddColumn { model: ColumnModel },
62    /// 删除字段(危险操作)
63    DropColumn {
64        schema: String,
65        table: String,
66        name: String,
67    },
68    /// 字段重命名(rename_from 显式声明)
69    RenameColumn {
70        schema: String,
71        table: String,
72        old_name: String,
73        new_name: String,
74    },
75    /// 字段类型变化(危险等级由 plan 阶段进一步判断)
76    AlterType {
77        schema: String,
78        table: String,
79        column: String,
80        old_type: String,
81        new_type: String,
82    },
83    /// 由可空改为不可空(危险操作)
84    SetNotNull {
85        schema: String,
86        table: String,
87        column: String,
88    },
89    /// 由不可空改为可空(安全)
90    DropNotNull {
91        schema: String,
92        table: String,
93        column: String,
94    },
95    /// 设置默认值(安全)
96    SetDefault {
97        schema: String,
98        table: String,
99        column: String,
100        default_sql: String,
101    },
102    /// 删除默认值(安全)
103    DropDefault {
104        schema: String,
105        table: String,
106        column: String,
107    },
108    /// 设置或删除字段注释
109    SetComment {
110        schema: String,
111        table: String,
112        column: String,
113        comment: Option<String>,
114    },
115}
116
117/// 主键差异。
118#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
119pub struct PrimaryKeyDiff {
120    /// 期望主键(Some 表示需要建立该主键)
121    pub desired: Option<Vec<String>>,
122    /// 实际主键(用于删除旧约束)
123    pub actual: Option<PrimaryKeyModel>,
124}
125
126/// 唯一约束差异。
127#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
128pub enum ConstraintDiff {
129    Add {
130        name: Option<String>,
131        columns: Vec<String>,
132    },
133    Drop {
134        name: Option<String>,
135        columns: Vec<String>,
136    },
137}
138
139/// 外键差异。
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141pub enum ForeignKeyDiff {
142    Add {
143        fk: ForeignKeyModel,
144    },
145    Drop {
146        name: Option<String>,
147        fk: ForeignKeyModel,
148    },
149}
150
151/// 普通索引差异。
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153pub enum IndexDiff {
154    Add { index: IndexModel },
155    Drop { index: IndexModel },
156}
157
158/// 数据库函数差异。
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
160pub enum FunctionDiff {
161    Create(FunctionModel),
162    Drop(FunctionModel),
163    Replace(FunctionModel),
164    SetComment {
165        schema: String,
166        name: String,
167        identity_arguments: String,
168        comment: Option<String>,
169    },
170}
171
172/// 计算期望结构与实际结构之间的全部差异。
173///
174/// # 表匹配规则
175/// 1. 优先按 (schema, 表名) 精确匹配;
176/// 2. 匹配不到时,若期望表声明了 `rename_from`,且实际表中存在该旧名,则视为重命名;
177/// 3. 期望有、实际无 → `CreateTable`;实际有、期望无 → `DropTable`。
178///
179/// # 字段匹配规则
180/// 与表匹配规则相同,字段级也优先精确匹配、其次按 `rename_from`。
181pub fn compute_diff(desired: &SchemaModel, actual: &SchemaModel) -> SchemaDiff {
182    let mut create_schemas = Vec::new();
183    for s in &desired.schemas {
184        if !actual.schemas.contains(s) {
185            create_schemas.push(s.clone());
186        }
187    }
188
189    let mut tables = Vec::new();
190    // 记录已匹配的实际表,避免把匹配过的表误判为「待删除」
191    let mut used: HashSet<(String, String)> = HashSet::new();
192
193    for d in &desired.tables {
194        // 1) 按 (schema, name) 精确匹配
195        let mut matched: Option<&TableModel> = actual
196            .tables
197            .iter()
198            .find(|a| a.schema == d.schema && a.name == d.name);
199
200        // 2) 未匹配时按 rename_from 查找
201        if matched.is_none() {
202            if let Some(old) = &d.rename_from {
203                if let Some(a) = actual
204                    .tables
205                    .iter()
206                    .find(|a| a.schema == d.schema && &a.name == old)
207                {
208                    tables.push(TableDiff::RenameTable {
209                        schema: d.schema.clone(),
210                        old_name: old.clone(),
211                        new_name: d.name.clone(),
212                    });
213                    matched = Some(a);
214                }
215            }
216        }
217
218        match matched {
219            Some(a) => {
220                used.insert(a.key());
221                tables.push(diff_table(d, a, desired.manage_comments));
222            }
223            None => {
224                let mut table = d.clone();
225                if !desired.manage_comments {
226                    table.comment = None;
227                    for column in &mut table.columns {
228                        column.comment = None;
229                    }
230                }
231                tables.push(TableDiff::CreateTable(table));
232            }
233        }
234    }
235
236    // 实际存在、但期望结构中不存在的表 → 删除
237    for a in &actual.tables {
238        if !used.contains(&a.key()) {
239            tables.push(TableDiff::DropTable {
240                schema: a.schema.clone(),
241                name: a.name.clone(),
242            });
243        }
244    }
245
246    let mut functions = Vec::new();
247    if desired.manage_functions {
248        let mut used_functions: HashSet<(String, String, String)> = HashSet::new();
249        for desired_fn in &desired.functions {
250            let key = desired_fn.key();
251            match actual
252                .functions
253                .iter()
254                .find(|actual_fn| actual_fn.key() == key)
255            {
256                Some(actual_fn) => {
257                    used_functions.insert(key);
258                    if normalize_function_definition(&desired_fn.definition_sql)
259                        != normalize_function_definition(&actual_fn.definition_sql)
260                    {
261                        functions.push(FunctionDiff::Replace(desired_fn.clone()));
262                    }
263                    if desired.manage_comments && desired_fn.comment != actual_fn.comment {
264                        functions.push(FunctionDiff::SetComment {
265                            schema: desired_fn.schema.clone(),
266                            name: desired_fn.name.clone(),
267                            identity_arguments: desired_fn.identity_arguments.clone(),
268                            comment: desired_fn.comment.clone(),
269                        });
270                    }
271                }
272                None => functions.push(FunctionDiff::Create(desired_fn.clone())),
273            }
274        }
275        for actual_fn in &actual.functions {
276            if !used_functions.contains(&actual_fn.key()) {
277                functions.push(FunctionDiff::Drop(actual_fn.clone()));
278            }
279        }
280    }
281
282    SchemaDiff {
283        create_schemas,
284        tables,
285        functions,
286    }
287}
288
289/// 计算一张表的字段/约束/索引差异。
290fn diff_table(d: &TableModel, a: &TableModel, manage_comments: bool) -> TableDiff {
291    let mut columns = Vec::new();
292    let mut used: HashSet<String> = HashSet::new();
293
294    // —— 字段差异 ——
295    for dc in &d.columns {
296        let mut ac: Option<&ColumnModel> = a.columns.iter().find(|c| c.name == dc.name);
297        if ac.is_none() {
298            if let Some(old) = &dc.rename_from {
299                if let Some(c) = a.columns.iter().find(|c| &c.name == old) {
300                    columns.push(ColumnDiff::RenameColumn {
301                        schema: d.schema.clone(),
302                        table: d.name.clone(),
303                        old_name: old.clone(),
304                        new_name: dc.name.clone(),
305                    });
306                    used.insert(c.name.clone());
307                    ac = Some(c);
308                }
309            }
310        }
311        match ac {
312            Some(ac) => {
313                used.insert(ac.name.clone());
314                columns.extend(diff_column(d, a, dc, ac, manage_comments));
315            }
316            None => {
317                let mut model = dc.clone();
318                if !manage_comments {
319                    model.comment = None;
320                }
321                columns.push(ColumnDiff::AddColumn { model });
322            }
323        }
324    }
325    for ac in &a.columns {
326        if !used.contains(&ac.name) {
327            columns.push(ColumnDiff::DropColumn {
328                schema: a.schema.clone(),
329                table: a.name.clone(),
330                name: ac.name.clone(),
331            });
332        }
333    }
334
335    // —— 主键差异 ——
336    let d_pk = effective_primary_key(d);
337    let a_pk = effective_primary_key(a);
338    let primary_key = if d_pk != a_pk {
339        Some(PrimaryKeyDiff {
340            desired: if d_pk.is_empty() { None } else { Some(d_pk) },
341            actual: a.primary_key.clone(),
342        })
343    } else {
344        None
345    };
346
347    // —— 唯一约束差异(按字段集合匹配,忽略名称)——
348    let mut uniques = Vec::new();
349    for u in &d.unique_constraints {
350        if !a.unique_constraints.iter().any(|x| x.columns == u.columns) {
351            uniques.push(ConstraintDiff::Add {
352                name: u.name.clone(),
353                columns: u.columns.clone(),
354            });
355        }
356    }
357    for u in &a.unique_constraints {
358        if !d.unique_constraints.iter().any(|x| x.columns == u.columns) {
359            uniques.push(ConstraintDiff::Drop {
360                name: u.name.clone(),
361                columns: u.columns.clone(),
362            });
363        }
364    }
365
366    // —— 外键差异(按本地字段/引用表/引用字段/级联规则整体匹配)——
367    let mut foreign_keys = Vec::new();
368    for fk in &d.foreign_keys {
369        if !a.foreign_keys.iter().any(|x| fk_eq(x, fk)) {
370            foreign_keys.push(ForeignKeyDiff::Add { fk: fk.clone() });
371        }
372    }
373    for fk in &a.foreign_keys {
374        if !d.foreign_keys.iter().any(|x| fk_eq(x, fk)) {
375            foreign_keys.push(ForeignKeyDiff::Drop {
376                name: fk.name.clone(),
377                fk: fk.clone(),
378            });
379        }
380    }
381
382    // —— 普通索引差异(按字段/谓词/唯一性整体匹配)——
383    let mut indexes = Vec::new();
384    for ix in &d.indexes {
385        if !a.indexes.iter().any(|x| index_eq(x, ix)) {
386            indexes.push(IndexDiff::Add { index: ix.clone() });
387        }
388    }
389    for ix in &a.indexes {
390        if !d.indexes.iter().any(|x| index_eq(x, ix)) {
391            indexes.push(IndexDiff::Drop { index: ix.clone() });
392        }
393    }
394
395    let table_comment = manage_comments
396        .then(|| {
397            (d.comment != a.comment).then(|| CommentChange {
398                desired: d.comment.clone(),
399            })
400        })
401        .flatten();
402
403    TableDiff::AlterTable {
404        schema: d.schema.clone(),
405        name: d.name.clone(),
406        columns,
407        primary_key,
408        uniques,
409        foreign_keys,
410        indexes,
411        table_comment,
412    }
413}
414
415/// 计算单字段的类型/可空性/默认值差异。
416fn diff_column(
417    d: &TableModel,
418    _a: &TableModel,
419    dc: &ColumnModel,
420    ac: &ColumnModel,
421    manage_comments: bool,
422) -> Vec<ColumnDiff> {
423    let mut out = Vec::new();
424    let schema = d.schema.clone();
425    let table = d.name.clone();
426
427    // 类型变化(先做规范化再比较)
428    if normalize_type(&dc.sql_type) != normalize_type(&ac.sql_type) {
429        out.push(ColumnDiff::AlterType {
430            schema: schema.clone(),
431            table: table.clone(),
432            column: dc.name.clone(),
433            old_type: ac.sql_type.clone(),
434            new_type: dc.sql_type.clone(),
435        });
436    }
437
438    // 可空性变化
439    match (dc.nullable, ac.nullable) {
440        (false, true) => out.push(ColumnDiff::SetNotNull {
441            schema: schema.clone(),
442            table: table.clone(),
443            column: dc.name.clone(),
444        }),
445        (true, false) => out.push(ColumnDiff::DropNotNull {
446            schema: schema.clone(),
447            table: table.clone(),
448            column: dc.name.clone(),
449        }),
450        _ => {}
451    }
452
453    // 默认值变化
454    match (&dc.default_sql, &ac.default_sql) {
455        (Some(dv), Some(av)) => {
456            if !default_eq(dv, av) {
457                out.push(ColumnDiff::SetDefault {
458                    schema: schema.clone(),
459                    table: table.clone(),
460                    column: dc.name.clone(),
461                    default_sql: dv.clone(),
462                });
463            }
464        }
465        (Some(dv), None) => out.push(ColumnDiff::SetDefault {
466            schema: schema.clone(),
467            table: table.clone(),
468            column: dc.name.clone(),
469            default_sql: dv.clone(),
470        }),
471        (None, Some(_)) => out.push(ColumnDiff::DropDefault {
472            schema,
473            table,
474            column: dc.name.clone(),
475        }),
476        (None, None) => {}
477    }
478
479    if manage_comments && dc.comment != ac.comment {
480        out.push(ColumnDiff::SetComment {
481            schema: d.schema.clone(),
482            table: d.name.clone(),
483            column: dc.name.clone(),
484            comment: dc.comment.clone(),
485        });
486    }
487
488    out
489}
490
491/// 保留函数体内部语义,只统一换行和定义末尾的分号/空白。
492pub fn normalize_function_definition(definition: &str) -> String {
493    definition
494        .replace("\r\n", "\n")
495        .trim()
496        .trim_end_matches(';')
497        .trim()
498        .to_string()
499}
500
501/// 取表的有效主键字段列表。
502/// 优先使用 `TableModel::primary_key`;若未设置则从字段的 `primary_key` 标记推导。
503fn effective_primary_key(t: &TableModel) -> Vec<String> {
504    if let Some(pk) = &t.primary_key {
505        return pk.columns.clone();
506    }
507    t.columns
508        .iter()
509        .filter(|c| c.primary_key)
510        .map(|c| c.name.clone())
511        .collect()
512}
513
514/// 外键是否等价(级联规则忽略大小写、NO ACTION 视为缺省)。
515fn fk_rule(r: &Option<String>) -> Option<String> {
516    r.as_ref().map(|s| s.to_lowercase())
517}
518
519fn fk_eq(a: &ForeignKeyModel, b: &ForeignKeyModel) -> bool {
520    a.columns == b.columns
521        && a.ref_table == b.ref_table
522        && a.ref_columns == b.ref_columns
523        && fk_rule(&a.on_delete) == fk_rule(&b.on_delete)
524        && fk_rule(&a.on_update) == fk_rule(&b.on_update)
525}
526
527/// 索引是否等价(谓词做归一化后比较)。
528fn index_eq(a: &IndexModel, b: &IndexModel) -> bool {
529    a.columns == b.columns
530        && a.unique == b.unique
531        && normalize_predicate(&a.predicate) == normalize_predicate(&b.predicate)
532}
533
534/// 归一化部分索引谓词:
535/// `WHERE deleted_at IS NOT NULL`、`(deleted_at IS NOT NULL)` 统一为 `deleted_at is not null`。
536pub fn normalize_predicate(p: &Option<String>) -> Option<String> {
537    p.as_ref().map(|s| {
538        let mut t = s.trim().to_lowercase();
539        if let Some(rest) = t.strip_prefix("where ") {
540            t = rest.trim().to_string();
541        }
542        // 去掉最外层括号(循环直到不再是括号包裹)
543        while t.len() > 2 && t.starts_with('(') && t.ends_with(')') {
544            t = t[1..t.len() - 1].trim().to_string();
545        }
546        t
547    })
548}
549
550/// 归一化 PostgreSQL 类型写法,使期望结构与实际结构可比较。
551pub fn normalize_type(t: &str) -> String {
552    let t = t.trim().to_lowercase();
553    match t.as_str() {
554        "character varying" | "character varying()" => "varchar".to_string(),
555        "character" | "character()" => "char".to_string(),
556        "timestamp without time zone" | "timestamp without time zone()" => "timestamp".to_string(),
557        "timestamp with time zone" | "timestamp with time zone()" => "timestamptz".to_string(),
558        "time without time zone" => "time".to_string(),
559        "time with time zone" => "timetz".to_string(),
560        other => other.to_string(),
561    }
562}
563
564/// 归一化默认值表达式:
565/// - 转小写、去首尾空白;
566/// - 移除末尾的 `::类型` 强制转换(如 `'{}'::jsonb` → `'{}'`)。
567pub fn normalize_default(d: &str) -> String {
568    let mut s = d.trim().to_lowercase();
569    while let Some(pos) = find_outer_cast(&s) {
570        s.truncate(pos);
571        s = s.trim().to_string();
572    }
573    s
574}
575
576/// 查找最外层(不在引号内、不在括号内)的 `::` 位置。
577/// 说明:serial 的 `nextval(...)::regclass` 在 introspection 阶段已被归一化,
578/// 不会进入本函数;这里只处理 `'{}'::jsonb`、`''::character varying` 这类字面量强转。
579fn find_outer_cast(s: &str) -> Option<usize> {
580    let bytes = s.as_bytes();
581    let mut quote = false;
582    let mut depth = 0usize;
583    let mut last_outer = None;
584    let mut i = 0;
585    while i + 1 < s.len() {
586        let c = bytes[i];
587        match c {
588            b'\'' => quote = !quote,
589            b'(' if !quote => depth += 1,
590            b')' if !quote => depth = depth.saturating_sub(1),
591            b':' if !quote && depth == 0 && bytes[i + 1] == b':' => {
592                last_outer = Some(i);
593                i += 1;
594            }
595            _ => {}
596        }
597        i += 1;
598    }
599    last_outer
600}
601
602/// 默认值等价性判断:`now()` 与 `CURRENT_TIMESTAMP` 视为等价。
603fn default_eq(a: &str, b: &str) -> bool {
604    let na = normalize_default(a);
605    let nb = normalize_default(b);
606    if na == nb {
607        return true;
608    }
609    let ts_aliases = ["now()", "current_timestamp", "transaction_timestamp()"];
610    ts_aliases.contains(&na.as_str()) && ts_aliases.contains(&nb.as_str())
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    /// 构造测试用字段
618    fn col(name: &str, sql_type: &str, nullable: bool) -> ColumnModel {
619        ColumnModel {
620            name: name.into(),
621            sql_type: sql_type.into(),
622            nullable,
623            primary_key: false,
624            rename_from: None,
625            default_sql: None,
626            comment: None,
627        }
628    }
629
630    /// 构造测试用表
631    fn tbl(schema: &str, name: &str, columns: Vec<ColumnModel>) -> TableModel {
632        TableModel {
633            schema: schema.into(),
634            name: name.into(),
635            rename_from: None,
636            comment: None,
637            columns,
638            primary_key: None,
639            unique_constraints: vec![],
640            foreign_keys: vec![],
641            indexes: vec![],
642        }
643    }
644
645    #[test]
646    fn 归一化类型() {
647        assert_eq!(
648            normalize_type("character varying(64)"),
649            "character varying(64)"
650        );
651        assert_eq!(normalize_type("VARCHAR(64)"), "varchar(64)");
652        assert_eq!(normalize_type("timestamp without time zone"), "timestamp");
653        assert_eq!(normalize_type("timestamp with time zone"), "timestamptz");
654    }
655
656    #[test]
657    fn 归一化默认值() {
658        assert_eq!(normalize_default("'{}'::jsonb"), "'{}'");
659        assert_eq!(normalize_default("''::character varying"), "''");
660        assert_eq!(normalize_default("NOW()"), "now()");
661        assert_eq!(
662            normalize_default("gen_random_uuid()::text"),
663            "gen_random_uuid()"
664        );
665    }
666
667    #[test]
668    fn 归一化谓词() {
669        assert_eq!(
670            normalize_predicate(&Some("WHERE deleted_at IS NOT NULL".into())),
671            normalize_predicate(&Some("(deleted_at IS NOT NULL)".into()))
672        );
673    }
674
675    #[test]
676    fn 新增表被识别() {
677        let desired = SchemaModel::from_tables(vec![tbl(
678            "public",
679            "users",
680            vec![col("id", "bigint", false)],
681        )]);
682        let actual = SchemaModel::default();
683        let diff = compute_diff(&desired, &actual);
684        assert!(matches!(&diff.tables[0], TableDiff::CreateTable(t) if t.name == "users"));
685    }
686
687    #[test]
688    fn 删除表被识别() {
689        let desired = SchemaModel::default();
690        let actual = SchemaModel::from_tables(vec![tbl(
691            "public",
692            "users",
693            vec![col("id", "bigint", false)],
694        )]);
695        let diff = compute_diff(&desired, &actual);
696        assert!(matches!(&diff.tables[0], TableDiff::DropTable { name, .. } if name == "users"));
697    }
698
699    #[test]
700    fn 表重命名被识别() {
701        let mut t = tbl("public", "staff", vec![col("id", "bigint", false)]);
702        t.rename_from = Some("employees".into());
703        let desired = SchemaModel::from_tables(vec![t]);
704        let actual = SchemaModel::from_tables(vec![tbl(
705            "public",
706            "employees",
707            vec![col("id", "bigint", false)],
708        )]);
709        let diff = compute_diff(&desired, &actual);
710        assert!(
711            matches!(&diff.tables[0], TableDiff::RenameTable { old_name, new_name, .. } if old_name == "employees" && new_name == "staff")
712        );
713    }
714
715    #[test]
716    fn 新增与删除字段被识别() {
717        let desired = tbl(
718            "public",
719            "users",
720            vec![col("id", "bigint", false), col("email", "text", false)],
721        );
722        let actual = tbl(
723            "public",
724            "users",
725            vec![col("id", "bigint", false), col("phone", "text", true)],
726        );
727        let diff = compute_diff(
728            &SchemaModel::from_tables(vec![desired]),
729            &SchemaModel::from_tables(vec![actual]),
730        );
731        let TableDiff::AlterTable { columns, .. } = &diff.tables[0] else {
732            panic!("应为 AlterTable");
733        };
734        assert!(
735            columns
736                .iter()
737                .any(|c| matches!(c, ColumnDiff::AddColumn { model } if model.name == "email"))
738        );
739        assert!(
740            columns
741                .iter()
742                .any(|c| matches!(c, ColumnDiff::DropColumn { name, .. } if name == "phone"))
743        );
744    }
745
746    #[test]
747    fn 字段重命名被识别() {
748        let mut d = col("email", "text", true);
749        d.rename_from = Some("mail".into());
750        let desired = tbl("public", "users", vec![col("id", "bigint", false), d]);
751        let actual = tbl(
752            "public",
753            "users",
754            vec![col("id", "bigint", false), col("mail", "text", true)],
755        );
756        let diff = compute_diff(
757            &SchemaModel::from_tables(vec![desired]),
758            &SchemaModel::from_tables(vec![actual]),
759        );
760        let TableDiff::AlterTable { columns, .. } = &diff.tables[0] else {
761            panic!("应为 AlterTable");
762        };
763        assert!(columns.iter().any(|c| matches!(c, ColumnDiff::RenameColumn { old_name, new_name, .. } if old_name == "mail" && new_name == "email")));
764    }
765
766    #[test]
767    fn 类型与可空性变化被识别() {
768        let desired = tbl(
769            "public",
770            "users",
771            vec![
772                col("id", "bigint", false),
773                col("name", "varchar(64)", false),
774            ],
775        );
776        let actual = tbl(
777            "public",
778            "users",
779            vec![col("id", "bigint", false), col("name", "varchar(32)", true)],
780        );
781        let diff = compute_diff(
782            &SchemaModel::from_tables(vec![desired]),
783            &SchemaModel::from_tables(vec![actual]),
784        );
785        let TableDiff::AlterTable { columns, .. } = &diff.tables[0] else {
786            panic!("应为 AlterTable");
787        };
788        assert!(columns.iter().any(
789            |c| matches!(c, ColumnDiff::AlterType { new_type, .. } if new_type == "varchar(64)")
790        ));
791        assert!(
792            columns
793                .iter()
794                .any(|c| matches!(c, ColumnDiff::SetNotNull { .. }))
795        );
796    }
797
798    #[test]
799    fn 主键变化被识别() {
800        let mut d = tbl("public", "users", vec![col("id", "bigint", false)]);
801        d.primary_key = Some(PrimaryKeyModel {
802            name: None,
803            columns: vec!["id".into()],
804        });
805        let mut a = tbl("public", "users", vec![col("id", "bigint", false)]);
806        a.primary_key = Some(PrimaryKeyModel {
807            name: Some("users_pkey".into()),
808            columns: vec!["id".into()],
809        });
810        // 相同主键 → 无差异
811        let diff = compute_diff(
812            &SchemaModel::from_tables(vec![d.clone()]),
813            &SchemaModel::from_tables(vec![a.clone()]),
814        );
815        let TableDiff::AlterTable { primary_key, .. } = &diff.tables[0] else {
816            panic!()
817        };
818        assert!(primary_key.is_none());
819
820        // 不同主键 → 有差异
821        let mut d2 = d.clone();
822        d2.primary_key = Some(PrimaryKeyModel {
823            name: None,
824            columns: vec!["email".into()],
825        });
826        let diff2 = compute_diff(
827            &SchemaModel::from_tables(vec![d2]),
828            &SchemaModel::from_tables(vec![a]),
829        );
830        let TableDiff::AlterTable { primary_key, .. } = &diff2.tables[0] else {
831            panic!()
832        };
833        assert!(primary_key.is_some());
834    }
835
836    #[test]
837    fn 默认值等价判断() {
838        assert!(default_eq("now()", "CURRENT_TIMESTAMP"));
839        assert!(default_eq("now()", "NOW()"));
840        assert!(!default_eq("now()", "'2024-01-01'"));
841    }
842
843    #[test]
844    fn 注释只有显式启用时参与差异() {
845        let mut desired_table = tbl("public", "users", vec![col("id", "bigint", false)]);
846        desired_table.comment = Some("用户表".into());
847        let actual_table = tbl("public", "users", vec![col("id", "bigint", false)]);
848
849        let desired = SchemaModel::from_tables(vec![desired_table]);
850        let diff = compute_diff(&desired, &SchemaModel::from_tables(vec![actual_table]));
851        assert!(matches!(
852            &diff.tables[0],
853            TableDiff::AlterTable {
854                table_comment: Some(_),
855                ..
856            }
857        ));
858    }
859
860    #[test]
861    fn 函数支持创建替换和删除() {
862        let function = |body: &str| FunctionModel {
863            schema: "public".into(),
864            name: "answer".into(),
865            identity_arguments: String::new(),
866            definition_sql: body.into(),
867            comment: None,
868        };
869        let desired = SchemaModel::with_functions(
870            vec![],
871            vec![],
872            vec![function(
873                "CREATE OR REPLACE FUNCTION public.answer() RETURNS integer LANGUAGE sql AS $$ SELECT 42 $$",
874            )],
875        );
876        let actual = SchemaModel::with_functions(
877            vec![],
878            vec![],
879            vec![function(
880                "CREATE OR REPLACE FUNCTION public.answer() RETURNS integer LANGUAGE sql AS $$ SELECT 41 $$",
881            )],
882        );
883        let diff = compute_diff(&desired, &actual);
884        assert!(matches!(diff.functions[0], FunctionDiff::Replace(_)));
885    }
886}