Skip to main content

sqltrail_core/
plan.rs

1//! 迁移计划:将 [`SchemaDiff`] 转换为有序的迁移操作序列。
2//!
3//! 每个操作都带有危险等级:
4//! - [`DangerLevel::Safe`]:可放心执行;
5//! - [`DangerLevel::Caution`]:可能影响既有数据,需要留意;
6//! - [`DangerLevel::Dangerous`]:默认只生成计划,执行时必须显式确认(`--allow-destructive`)。
7//!
8//! 危险操作清单(与实施计划 4.3 一致):
9//! 删除表、删除字段、缩短 varchar 长度、降低数值精度、
10//! 可空字段改不可空、不兼容类型变化、修改主键或唯一约束。
11
12use serde::{Deserialize, Serialize};
13
14use crate::diff::*;
15use crate::model::*;
16
17/// 危险等级。
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
19pub enum DangerLevel {
20    /// 安全操作
21    Safe,
22    /// 需要注意的操作
23    Caution,
24    /// 危险操作:默认不执行,需要显式确认
25    Dangerous,
26}
27
28impl DangerLevel {
29    /// 中文标签
30    pub fn label(&self) -> &'static str {
31        match self {
32            DangerLevel::Safe => "安全",
33            DangerLevel::Caution => "注意",
34            DangerLevel::Dangerous => "危险",
35        }
36    }
37
38    /// 是否危险操作
39    pub fn is_dangerous(&self) -> bool {
40        matches!(self, DangerLevel::Dangerous)
41    }
42}
43
44/// 单个迁移操作。
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub enum MigrationOperation {
47    /// 创建 schema
48    CreateSchema { name: String },
49    /// 创建表(含主键/唯一/外键,DDL 内联生成)
50    CreateTable { table: TableModel },
51    /// 表重命名
52    RenameTable {
53        schema: String,
54        old_name: String,
55        new_name: String,
56    },
57    /// 删除表(危险)
58    DropTable { schema: String, name: String },
59    /// 新增字段
60    AddColumn {
61        schema: String,
62        table: String,
63        column: ColumnModel,
64    },
65    /// 删除字段(危险)
66    DropColumn {
67        schema: String,
68        table: String,
69        name: String,
70    },
71    /// 字段重命名
72    RenameColumn {
73        schema: String,
74        table: String,
75        old_name: String,
76        new_name: String,
77    },
78    /// 修改字段类型
79    AlterColumnType {
80        schema: String,
81        table: String,
82        column: String,
83        old_type: String,
84        new_type: String,
85    },
86    /// 设置 NOT NULL(危险)
87    SetNotNull {
88        schema: String,
89        table: String,
90        column: String,
91    },
92    /// 取消 NOT NULL(安全)
93    DropNotNull {
94        schema: String,
95        table: String,
96        column: String,
97    },
98    /// 设置默认值
99    SetDefault {
100        schema: String,
101        table: String,
102        column: String,
103        default_sql: String,
104    },
105    /// 删除默认值
106    DropDefault {
107        schema: String,
108        table: String,
109        column: String,
110    },
111    /// 添加主键(危险)
112    AddPrimaryKey {
113        schema: String,
114        table: String,
115        columns: Vec<String>,
116    },
117    /// 删除主键(危险)
118    DropPrimaryKey {
119        schema: String,
120        table: String,
121        name: String,
122    },
123    /// 添加唯一约束
124    AddUnique {
125        schema: String,
126        table: String,
127        name: Option<String>,
128        columns: Vec<String>,
129    },
130    /// 删除唯一约束(危险)
131    DropUnique {
132        schema: String,
133        table: String,
134        name: Option<String>,
135    },
136    /// 添加外键
137    AddForeignKey {
138        schema: String,
139        table: String,
140        fk: ForeignKeyModel,
141    },
142    /// 删除外键
143    DropForeignKey {
144        schema: String,
145        table: String,
146        name: Option<String>,
147    },
148    /// 添加普通索引
149    AddIndex {
150        schema: String,
151        table: String,
152        index: IndexModel,
153    },
154    /// 删除普通索引
155    DropIndex {
156        schema: String,
157        table: String,
158        name: String,
159    },
160    /// 设置或删除表注释
161    SetTableComment {
162        schema: String,
163        table: String,
164        comment: Option<String>,
165    },
166    /// 设置或删除字段注释
167    SetColumnComment {
168        schema: String,
169        table: String,
170        column: String,
171        comment: Option<String>,
172    },
173    /// 创建数据库函数
174    CreateFunction { function: FunctionModel },
175    /// 替换数据库函数定义
176    ReplaceFunction { function: FunctionModel },
177    /// 删除数据库函数
178    DropFunction { function: FunctionModel },
179    /// 设置或删除函数注释
180    SetFunctionComment {
181        schema: String,
182        name: String,
183        identity_arguments: String,
184        comment: Option<String>,
185    },
186}
187
188impl MigrationOperation {
189    /// 操作的危险等级。
190    pub fn danger(&self) -> DangerLevel {
191        use MigrationOperation::*;
192        match self {
193            CreateSchema { .. }
194            | CreateTable { .. }
195            | AddIndex { .. }
196            | SetTableComment { .. }
197            | SetColumnComment { .. }
198            | SetFunctionComment { .. } => DangerLevel::Safe,
199            RenameTable { .. }
200            | RenameColumn { .. }
201            | AddUnique { .. }
202            | DropForeignKey { .. }
203            | DropIndex { .. }
204            | DropNotNull { .. }
205            | SetDefault { .. }
206            | DropDefault { .. }
207            | AddForeignKey { .. }
208            | CreateFunction { .. }
209            | ReplaceFunction { .. } => DangerLevel::Caution,
210            DropTable { .. }
211            | DropColumn { .. }
212            | SetNotNull { .. }
213            | DropPrimaryKey { .. }
214            | AddPrimaryKey { .. }
215            | DropUnique { .. }
216            | DropFunction { .. } => DangerLevel::Dangerous,
217            // 类型变化的具体危险等级由变化方向决定
218            AlterColumnType {
219                old_type, new_type, ..
220            } => classify_type_change(old_type, new_type),
221            AddColumn { column, .. } => {
222                // 新增 NOT NULL 且无默认值的字段,已有数据行会导致执行失败,需要留意
223                if !column.nullable && column.default_sql.is_none() {
224                    DangerLevel::Caution
225                } else {
226                    DangerLevel::Safe
227                }
228            }
229        }
230    }
231
232    /// 操作的人类可读描述(用于 plan 输出)。
233    pub fn describe(&self) -> String {
234        use MigrationOperation::*;
235        match self {
236            CreateSchema { name } => format!("创建 schema \"{name}\""),
237            CreateTable { table } => format!("创建表 {}.{}", table.schema, table.name),
238            RenameTable {
239                schema,
240                old_name,
241                new_name,
242            } => {
243                format!("表重命名 {schema}.{old_name} → {schema}.{new_name}")
244            }
245            DropTable { schema, name } => format!("删除表 {schema}.{name}"),
246            AddColumn {
247                schema,
248                table,
249                column,
250            } => format!("新增字段 {schema}.{table}.{}", column.name),
251            DropColumn {
252                schema,
253                table,
254                name,
255            } => format!("删除字段 {schema}.{table}.{name}"),
256            RenameColumn {
257                schema,
258                table,
259                old_name,
260                new_name,
261            } => {
262                format!("字段重命名 {schema}.{table}.{old_name} → {new_name}")
263            }
264            AlterColumnType {
265                schema,
266                table,
267                column,
268                old_type,
269                new_type,
270            } => {
271                format!("修改字段类型 {schema}.{table}.{column}: {old_type} → {new_type}")
272            }
273            SetNotNull {
274                schema,
275                table,
276                column,
277            } => format!("设置 NOT NULL {schema}.{table}.{column}"),
278            DropNotNull {
279                schema,
280                table,
281                column,
282            } => format!("取消 NOT NULL {schema}.{table}.{column}"),
283            SetDefault {
284                schema,
285                table,
286                column,
287                default_sql,
288            } => {
289                format!("设置默认值 {schema}.{table}.{column} = {default_sql}")
290            }
291            DropDefault {
292                schema,
293                table,
294                column,
295            } => format!("删除默认值 {schema}.{table}.{column}"),
296            AddPrimaryKey {
297                schema,
298                table,
299                columns,
300            } => {
301                format!("添加主键 {schema}.{table} ({})", columns.join(", "))
302            }
303            DropPrimaryKey {
304                schema,
305                table,
306                name,
307            } => format!("删除主键 {schema}.{table} ({name})"),
308            AddUnique {
309                schema,
310                table,
311                columns,
312                ..
313            } => format!("添加唯一约束 {schema}.{table} ({})", columns.join(", ")),
314            DropUnique { schema, table, .. } => format!("删除唯一约束 {schema}.{table}"),
315            AddForeignKey { schema, table, fk } => {
316                format!("添加外键 {schema}.{table} -> {}", fk.ref_table)
317            }
318            DropForeignKey { schema, table, .. } => format!("删除外键 {schema}.{table}"),
319            AddIndex {
320                schema,
321                table,
322                index,
323            } => {
324                let unique = if index.unique {
325                    "唯一索引"
326                } else {
327                    "索引"
328                };
329                format!(
330                    "添加{unique} {schema}.{table} ({})",
331                    index.columns.join(", ")
332                )
333            }
334            DropIndex {
335                schema,
336                table,
337                name,
338            } => format!("删除索引 {schema}.{table}.{name}"),
339            SetTableComment {
340                schema,
341                table,
342                comment,
343            } => format!(
344                "{}表注释 {schema}.{table}",
345                if comment.is_some() {
346                    "设置"
347                } else {
348                    "删除"
349                }
350            ),
351            SetColumnComment {
352                schema,
353                table,
354                column,
355                comment,
356            } => format!(
357                "{}字段注释 {schema}.{table}.{column}",
358                if comment.is_some() {
359                    "设置"
360                } else {
361                    "删除"
362                }
363            ),
364            CreateFunction { function } => {
365                format!("创建函数 {}.{}", function.schema, function.name)
366            }
367            ReplaceFunction { function } => {
368                format!("替换函数 {}.{}", function.schema, function.name)
369            }
370            DropFunction { function } => {
371                format!("删除函数 {}.{}", function.schema, function.name)
372            }
373            SetFunctionComment {
374                schema,
375                name,
376                comment,
377                ..
378            } => format!(
379                "{}函数注释 {schema}.{name}",
380                if comment.is_some() {
381                    "设置"
382                } else {
383                    "删除"
384                }
385            ),
386        }
387    }
388}
389
390/// 判断类型变化是安全、需注意还是危险。
391///
392/// - varchar/char 长度变大安全,变小危险;
393/// - numeric 精度变大安全,变小危险;
394/// - 整数族(smallint→integer→bigint)变宽安全,变窄危险;
395/// - varchar→text 安全,text→varchar 危险;
396/// - 其余视为不兼容类型变化,一律危险。
397pub fn classify_type_change(old: &str, new: &str) -> DangerLevel {
398    let old = crate::diff::normalize_type(old);
399    let new = crate::diff::normalize_type(new);
400    if old == new {
401        return DangerLevel::Safe;
402    }
403
404    let (old_base, old_args) = split_type(&old);
405    let (new_base, new_args) = split_type(&new);
406
407    // 变长字符类型
408    if old_base == "varchar" && new_base == "varchar" {
409        return compare_length(&old_args, &new_args);
410    }
411    if old_base == "char" && new_base == "char" {
412        return compare_length(&old_args, &new_args);
413    }
414    // text 视为无上限 varchar
415    if old_base == "text" && new_base == "varchar" {
416        return DangerLevel::Dangerous; // 收缩
417    }
418    if old_base == "varchar" && new_base == "text" {
419        return DangerLevel::Safe; // 放宽
420    }
421    // 定点数值
422    if old_base == "numeric" && new_base == "numeric" {
423        return compare_numeric(&old_args, &new_args);
424    }
425    // 整数族
426    let rank = |b: &str| match b {
427        "smallint" => Some(1),
428        "integer" => Some(2),
429        "bigint" => Some(3),
430        _ => None,
431    };
432    if let (Some(or), Some(nr)) = (rank(&old_base), rank(&new_base)) {
433        return if nr >= or {
434            DangerLevel::Safe
435        } else {
436            DangerLevel::Dangerous
437        };
438    }
439    // 浮点族
440    if old_base == "real" && new_base == "double precision" {
441        return DangerLevel::Safe;
442    }
443    if old_base == "double precision" && new_base == "real" {
444        return DangerLevel::Dangerous;
445    }
446    DangerLevel::Dangerous
447}
448
449/// 将 `varchar(64)` 拆分为 (`varchar`, [64]),`numeric(10,2)` 拆分为 (`numeric`, [10, 2])。
450fn split_type(t: &str) -> (String, Vec<usize>) {
451    if let Some(pos) = t.find('(') {
452        let base = t[..pos].trim().to_string();
453        let inner = t[pos + 1..].trim_end_matches(')').trim();
454        let args = if inner.is_empty() {
455            vec![]
456        } else {
457            inner
458                .split(',')
459                .filter_map(|s| s.trim().parse().ok())
460                .collect()
461        };
462        (base, args)
463    } else {
464        (t.trim().to_string(), vec![])
465    }
466}
467
468/// varchar(n) → varchar(m):m ≥ n 安全,否则危险。
469fn compare_length(old: &[usize], new: &[usize]) -> DangerLevel {
470    match (old.first(), new.first()) {
471        (Some(&o), Some(&n)) => {
472            if n >= o {
473                DangerLevel::Safe
474            } else {
475                DangerLevel::Dangerous
476            }
477        }
478        // 无长度参数(如 varchar)视为不限长度
479        (_, None) => DangerLevel::Safe,
480        (None, Some(_)) => DangerLevel::Dangerous,
481    }
482}
483
484/// numeric(p, s):精度/标度增大安全,减小危险。
485fn compare_numeric(old: &[usize], new: &[usize]) -> DangerLevel {
486    let o = old.first().copied().unwrap_or(0);
487    let n = new.first().copied().unwrap_or(0);
488    if n >= o {
489        DangerLevel::Safe
490    } else {
491        DangerLevel::Dangerous
492    }
493}
494
495/// 迁移计划:一组有序的迁移操作。
496#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
497pub struct MigrationPlan {
498    /// 有序的操作列表
499    pub operations: Vec<MigrationOperation>,
500}
501
502impl MigrationPlan {
503    /// 是否没有需要执行的变更
504    pub fn is_empty(&self) -> bool {
505        self.operations.is_empty()
506    }
507
508    /// 危险操作数量
509    pub fn danger_count(&self) -> usize {
510        self.operations
511            .iter()
512            .filter(|o| o.danger().is_dangerous())
513            .count()
514    }
515
516    /// 需要注意的操作数量
517    pub fn caution_count(&self) -> usize {
518        self.operations
519            .iter()
520            .filter(|o| o.danger() == DangerLevel::Caution)
521            .count()
522    }
523}
524
525/// 由 [`SchemaDiff`] 构建有序的 [`MigrationPlan`]。
526///
527/// 排序原则(保证 SQL 在 PostgreSQL 中按序执行不报错):
528/// 1. 创建 schema;
529/// 2. 创建新表(外键内联,被引用表先建);
530/// 3. 表重命名;
531/// 4. 全部删除类操作:删外键 → 删索引 → 删唯一约束 → 删主键 → 删字段 → 删表;
532/// 5. 字段修改:重命名字段 → 新增字段 → 改类型 → 改可空性 → 改默认值;
533/// 6. 全部新增类操作:加主键 → 加唯一约束 → 加外键 → 加索引。
534pub fn build_plan(diff: &SchemaDiff) -> MigrationPlan {
535    use MigrationOperation::*;
536
537    // 各阶段桶:P1 建 schema,P2 建表,P3 重命名,P4 删除,P5 字段修改,P6 新增
538    let mut p1: Vec<MigrationOperation> = Vec::new();
539    let mut p2: Vec<MigrationOperation> = Vec::new();
540    let mut p3: Vec<MigrationOperation> = Vec::new();
541    let mut p4_drops: Vec<MigrationOperation> = Vec::new(); // 约束/索引/字段删除
542    let mut p4_tables: Vec<MigrationOperation> = Vec::new(); // 表删除(放最后)
543    let mut p5: Vec<MigrationOperation> = Vec::new();
544    let mut p6: Vec<MigrationOperation> = Vec::new();
545
546    for s in &diff.create_schemas {
547        p1.push(CreateSchema { name: s.clone() });
548    }
549
550    for t in &diff.tables {
551        match t {
552            TableDiff::CreateTable(table) => {
553                // 外键统一在所有表创建完成后添加,避免依赖顺序和循环外键导致
554                // CREATE TABLE 失败。
555                let mut table_without_fks = table.clone();
556                table_without_fks.foreign_keys.clear();
557                p2.push(CreateTable {
558                    table: table_without_fks,
559                });
560                for fk in &table.foreign_keys {
561                    p6.push(AddForeignKey {
562                        schema: table.schema.clone(),
563                        table: table.name.clone(),
564                        fk: fk.clone(),
565                    });
566                }
567                if table.comment.is_some() {
568                    p6.push(SetTableComment {
569                        schema: table.schema.clone(),
570                        table: table.name.clone(),
571                        comment: table.comment.clone(),
572                    });
573                }
574                for column in &table.columns {
575                    if column.comment.is_some() {
576                        p6.push(SetColumnComment {
577                            schema: table.schema.clone(),
578                            table: table.name.clone(),
579                            column: column.name.clone(),
580                            comment: column.comment.clone(),
581                        });
582                    }
583                }
584                // 普通索引不内联在 CREATE TABLE 中,需要单独生成 CREATE INDEX
585                for index in &table.indexes {
586                    p6.push(AddIndex {
587                        schema: table.schema.clone(),
588                        table: table.name.clone(),
589                        index: index.clone(),
590                    });
591                }
592            }
593            TableDiff::RenameTable {
594                schema,
595                old_name,
596                new_name,
597            } => {
598                p3.push(RenameTable {
599                    schema: schema.clone(),
600                    old_name: old_name.clone(),
601                    new_name: new_name.clone(),
602                });
603            }
604            TableDiff::DropTable { schema, name } => {
605                p4_tables.push(DropTable {
606                    schema: schema.clone(),
607                    name: name.clone(),
608                });
609            }
610            TableDiff::AlterTable {
611                schema,
612                name,
613                columns,
614                primary_key,
615                uniques,
616                foreign_keys,
617                indexes,
618                table_comment,
619            } => {
620                // 4a) 删除类操作:外键 → 索引 → 唯一约束 → 主键 → 字段
621                for fk in foreign_keys {
622                    if let ForeignKeyDiff::Drop { name: fk_name, .. } = fk {
623                        p4_drops.push(DropForeignKey {
624                            schema: schema.clone(),
625                            table: name.clone(),
626                            name: fk_name.clone(),
627                        });
628                    }
629                }
630                for ix in indexes {
631                    if let IndexDiff::Drop { index } = ix {
632                        p4_drops.push(DropIndex {
633                            schema: schema.clone(),
634                            table: name.clone(),
635                            name: index
636                                .name
637                                .clone()
638                                .unwrap_or_else(|| format!("{name}_{}", index.columns.join("_"))),
639                        });
640                    }
641                }
642                for u in uniques {
643                    if let ConstraintDiff::Drop { name: u_name, .. } = u {
644                        p4_drops.push(DropUnique {
645                            schema: schema.clone(),
646                            table: name.clone(),
647                            name: u_name.clone(),
648                        });
649                    }
650                }
651                if let Some(pk) = primary_key {
652                    if let Some(actual) = &pk.actual {
653                        p4_drops.push(DropPrimaryKey {
654                            schema: schema.clone(),
655                            table: name.clone(),
656                            name: actual
657                                .name
658                                .clone()
659                                .unwrap_or_else(|| format!("{name}_pkey")),
660                        });
661                    }
662                }
663                for c in columns {
664                    if let ColumnDiff::DropColumn {
665                        schema,
666                        table,
667                        name: col,
668                    } = c
669                    {
670                        p4_drops.push(DropColumn {
671                            schema: schema.clone(),
672                            table: table.clone(),
673                            name: col.clone(),
674                        });
675                    }
676                }
677
678                // 5) 字段修改
679                for c in columns {
680                    match c {
681                        ColumnDiff::RenameColumn {
682                            schema,
683                            table,
684                            old_name,
685                            new_name,
686                        } => {
687                            p5.push(RenameColumn {
688                                schema: schema.clone(),
689                                table: table.clone(),
690                                old_name: old_name.clone(),
691                                new_name: new_name.clone(),
692                            });
693                        }
694                        ColumnDiff::AddColumn { model } => {
695                            p5.push(AddColumn {
696                                schema: schema.clone(),
697                                table: name.clone(),
698                                column: model.clone(),
699                            });
700                            if model.comment.is_some() {
701                                p5.push(SetColumnComment {
702                                    schema: schema.clone(),
703                                    table: name.clone(),
704                                    column: model.name.clone(),
705                                    comment: model.comment.clone(),
706                                });
707                            }
708                        }
709                        ColumnDiff::AlterType {
710                            schema,
711                            table,
712                            column,
713                            old_type,
714                            new_type,
715                        } => {
716                            p5.push(AlterColumnType {
717                                schema: schema.clone(),
718                                table: table.clone(),
719                                column: column.clone(),
720                                old_type: old_type.clone(),
721                                new_type: new_type.clone(),
722                            });
723                        }
724                        ColumnDiff::SetNotNull {
725                            schema,
726                            table,
727                            column,
728                        } => {
729                            p5.push(SetNotNull {
730                                schema: schema.clone(),
731                                table: table.clone(),
732                                column: column.clone(),
733                            });
734                        }
735                        ColumnDiff::DropNotNull {
736                            schema,
737                            table,
738                            column,
739                        } => {
740                            p5.push(DropNotNull {
741                                schema: schema.clone(),
742                                table: table.clone(),
743                                column: column.clone(),
744                            });
745                        }
746                        ColumnDiff::SetDefault {
747                            schema,
748                            table,
749                            column,
750                            default_sql,
751                        } => {
752                            p5.push(SetDefault {
753                                schema: schema.clone(),
754                                table: table.clone(),
755                                column: column.clone(),
756                                default_sql: default_sql.clone(),
757                            });
758                        }
759                        ColumnDiff::DropDefault {
760                            schema,
761                            table,
762                            column,
763                        } => {
764                            p5.push(DropDefault {
765                                schema: schema.clone(),
766                                table: table.clone(),
767                                column: column.clone(),
768                            });
769                        }
770                        ColumnDiff::SetComment {
771                            schema,
772                            table,
773                            column,
774                            comment,
775                        } => {
776                            p5.push(SetColumnComment {
777                                schema: schema.clone(),
778                                table: table.clone(),
779                                column: column.clone(),
780                                comment: comment.clone(),
781                            });
782                        }
783                        _ => {}
784                    }
785                }
786
787                // 6) 新增类操作:主键 → 唯一约束 → 外键 → 索引
788                if let Some(pk) = primary_key {
789                    if let Some(cols) = &pk.desired {
790                        p6.push(AddPrimaryKey {
791                            schema: schema.clone(),
792                            table: name.clone(),
793                            columns: cols.clone(),
794                        });
795                    }
796                }
797                for u in uniques {
798                    if let ConstraintDiff::Add {
799                        name: u_name,
800                        columns,
801                    } = u
802                    {
803                        p6.push(AddUnique {
804                            schema: schema.clone(),
805                            table: name.clone(),
806                            name: u_name.clone(),
807                            columns: columns.clone(),
808                        });
809                    }
810                }
811                for fk in foreign_keys {
812                    if let ForeignKeyDiff::Add { fk: fk_model } = fk {
813                        p6.push(AddForeignKey {
814                            schema: schema.clone(),
815                            table: name.clone(),
816                            fk: fk_model.clone(),
817                        });
818                    }
819                }
820                for ix in indexes {
821                    if let IndexDiff::Add { index } = ix {
822                        p6.push(AddIndex {
823                            schema: schema.clone(),
824                            table: name.clone(),
825                            index: index.clone(),
826                        });
827                    }
828                }
829                if let Some(change) = table_comment {
830                    p6.push(SetTableComment {
831                        schema: schema.clone(),
832                        table: name.clone(),
833                        comment: change.desired.clone(),
834                    });
835                }
836            }
837        }
838    }
839
840    for function in &diff.functions {
841        match function {
842            FunctionDiff::Create(function) => {
843                p6.push(CreateFunction {
844                    function: function.clone(),
845                });
846                if function.comment.is_some() {
847                    p6.push(SetFunctionComment {
848                        schema: function.schema.clone(),
849                        name: function.name.clone(),
850                        identity_arguments: function.identity_arguments.clone(),
851                        comment: function.comment.clone(),
852                    });
853                }
854            }
855            FunctionDiff::Replace(function) => p6.push(ReplaceFunction {
856                function: function.clone(),
857            }),
858            FunctionDiff::Drop(function) => p4_drops.push(DropFunction {
859                function: function.clone(),
860            }),
861            FunctionDiff::SetComment {
862                schema,
863                name,
864                identity_arguments,
865                comment,
866            } => p6.push(SetFunctionComment {
867                schema: schema.clone(),
868                name: name.clone(),
869                identity_arguments: identity_arguments.clone(),
870                comment: comment.clone(),
871            }),
872        }
873    }
874
875    let mut operations = Vec::new();
876    operations.extend(p1);
877    operations.extend(p2);
878    operations.extend(p3);
879    operations.extend(p4_drops);
880    operations.extend(p4_tables);
881    operations.extend(p5);
882    operations.extend(p6);
883
884    MigrationPlan { operations }
885}
886
887#[cfg(test)]
888mod tests {
889    use super::*;
890
891    #[test]
892    fn 类型变化危险分级() {
893        use DangerLevel::*;
894        // varchar 加长安全、缩短危险
895        assert_eq!(classify_type_change("varchar(32)", "varchar(64)"), Safe);
896        assert_eq!(
897            classify_type_change("varchar(64)", "varchar(32)"),
898            Dangerous
899        );
900        // varchar → text 安全、text → varchar 危险
901        assert_eq!(classify_type_change("varchar(64)", "text"), Safe);
902        assert_eq!(classify_type_change("text", "varchar(64)"), Dangerous);
903        // 整数族变宽安全、变窄危险
904        assert_eq!(classify_type_change("smallint", "integer"), Safe);
905        assert_eq!(classify_type_change("integer", "bigint"), Safe);
906        assert_eq!(classify_type_change("bigint", "integer"), Dangerous);
907        // 数值精度
908        assert_eq!(classify_type_change("numeric(8,2)", "numeric(12,2)"), Safe);
909        assert_eq!(
910            classify_type_change("numeric(12,2)", "numeric(8,2)"),
911            Dangerous
912        );
913        // 不兼容变化危险
914        assert_eq!(classify_type_change("integer", "text"), Dangerous);
915        assert_eq!(classify_type_change("bigint", "timestamptz"), Dangerous);
916    }
917
918    #[test]
919    fn 操作危险等级() {
920        use MigrationOperation::*;
921        let drop_table = DropTable {
922            schema: "public".into(),
923            name: "t".into(),
924        };
925        assert_eq!(drop_table.danger(), DangerLevel::Dangerous);
926        let drop_col = DropColumn {
927            schema: "public".into(),
928            table: "t".into(),
929            name: "c".into(),
930        };
931        assert_eq!(drop_col.danger(), DangerLevel::Dangerous);
932        let add_col_nullable = AddColumn {
933            schema: "public".into(),
934            table: "t".into(),
935            column: ColumnModel {
936                name: "c".into(),
937                sql_type: "text".into(),
938                nullable: true,
939                primary_key: false,
940                rename_from: None,
941                default_sql: None,
942                comment: None,
943            },
944        };
945        assert_eq!(add_col_nullable.danger(), DangerLevel::Safe);
946    }
947
948    #[test]
949    fn 计划排序保证删除在前新增在后() {
950        // 构造一个同时包含「新增表」「新增字段」「删除字段」「删除表」的差异
951        let mut new_tbl = TableModel {
952            schema: "public".into(),
953            name: "users".into(),
954            rename_from: None,
955            comment: None,
956            columns: vec![ColumnModel {
957                name: "id".into(),
958                sql_type: "bigserial".into(),
959                nullable: false,
960                primary_key: true,
961                rename_from: None,
962                default_sql: None,
963                comment: None,
964            }],
965            primary_key: None,
966            unique_constraints: vec![],
967            foreign_keys: vec![],
968            indexes: vec![],
969        };
970        new_tbl.primary_key = Some(PrimaryKeyModel {
971            name: None,
972            columns: vec!["id".into()],
973        });
974
975        let old_tbl = TableModel {
976            schema: "public".into(),
977            name: "legacy".into(),
978            rename_from: None,
979            comment: None,
980            columns: vec![ColumnModel {
981                name: "id".into(),
982                sql_type: "bigserial".into(),
983                nullable: false,
984                primary_key: true,
985                rename_from: None,
986                default_sql: None,
987                comment: None,
988            }],
989            primary_key: None,
990            unique_constraints: vec![],
991            foreign_keys: vec![],
992            indexes: vec![],
993        };
994
995        let desired = SchemaModel::from_tables(vec![new_tbl.clone()]);
996        let actual = SchemaModel::from_tables(vec![old_tbl.clone()]);
997        let diff = compute_diff(&desired, &actual);
998        let plan = build_plan(&diff);
999
1000        let names: Vec<&str> = plan
1001            .operations
1002            .iter()
1003            .map(|o| match o {
1004                MigrationOperation::CreateTable { .. } => "create",
1005                MigrationOperation::DropTable { .. } => "drop",
1006                _ => "other",
1007            })
1008            .collect();
1009        // 先 create 后 drop
1010        let first_create = names.iter().position(|n| *n == "create").unwrap();
1011        let last_drop = names.iter().rposition(|n| *n == "drop").unwrap();
1012        assert!(first_create < last_drop, "排序应为:新增表在前,删除表在后");
1013    }
1014
1015    #[test]
1016    fn 新表外键在全部建表后添加() {
1017        let child = TableModel {
1018            schema: "public".into(),
1019            name: "children".into(),
1020            rename_from: None,
1021            comment: None,
1022            columns: vec![ColumnModel {
1023                name: "parent_id".into(),
1024                sql_type: "bigint".into(),
1025                nullable: false,
1026                primary_key: false,
1027                rename_from: None,
1028                default_sql: None,
1029                comment: None,
1030            }],
1031            primary_key: None,
1032            unique_constraints: vec![],
1033            foreign_keys: vec![ForeignKeyModel {
1034                name: None,
1035                columns: vec!["parent_id".into()],
1036                ref_table: "public.parents".into(),
1037                ref_columns: vec!["id".into()],
1038                on_delete: None,
1039                on_update: None,
1040            }],
1041            indexes: vec![],
1042        };
1043        let mut parent = child.clone();
1044        parent.name = "parents".into();
1045        parent.columns[0].name = "id".into();
1046        parent.foreign_keys.clear();
1047
1048        let plan = build_plan(&compute_diff(
1049            &SchemaModel::from_tables(vec![child, parent]),
1050            &SchemaModel::default(),
1051        ));
1052        let create_count = plan
1053            .operations
1054            .iter()
1055            .take_while(|operation| matches!(operation, MigrationOperation::CreateTable { .. }))
1056            .count();
1057        assert_eq!(create_count, 2);
1058        assert!(matches!(
1059            plan.operations.last(),
1060            Some(MigrationOperation::AddForeignKey { .. })
1061        ));
1062        for operation in &plan.operations[..create_count] {
1063            let MigrationOperation::CreateTable { table } = operation else {
1064                unreachable!()
1065            };
1066            assert!(table.foreign_keys.is_empty());
1067        }
1068    }
1069}