1use serde::{Deserialize, Serialize};
13
14use crate::diff::*;
15use crate::model::*;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
19pub enum DangerLevel {
20 Safe,
22 Caution,
24 Dangerous,
26}
27
28impl DangerLevel {
29 pub fn label(&self) -> &'static str {
31 match self {
32 DangerLevel::Safe => "安全",
33 DangerLevel::Caution => "注意",
34 DangerLevel::Dangerous => "危险",
35 }
36 }
37
38 pub fn is_dangerous(&self) -> bool {
40 matches!(self, DangerLevel::Dangerous)
41 }
42}
43
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub enum MigrationOperation {
47 CreateSchema { name: String },
49 CreateTable { table: TableModel },
51 RenameTable {
53 schema: String,
54 old_name: String,
55 new_name: String,
56 },
57 DropTable { schema: String, name: String },
59 AddColumn {
61 schema: String,
62 table: String,
63 column: ColumnModel,
64 },
65 DropColumn {
67 schema: String,
68 table: String,
69 name: String,
70 },
71 RenameColumn {
73 schema: String,
74 table: String,
75 old_name: String,
76 new_name: String,
77 },
78 AlterColumnType {
80 schema: String,
81 table: String,
82 column: String,
83 old_type: String,
84 new_type: String,
85 },
86 SetNotNull {
88 schema: String,
89 table: String,
90 column: String,
91 },
92 DropNotNull {
94 schema: String,
95 table: String,
96 column: String,
97 },
98 SetDefault {
100 schema: String,
101 table: String,
102 column: String,
103 default_sql: String,
104 },
105 DropDefault {
107 schema: String,
108 table: String,
109 column: String,
110 },
111 AddPrimaryKey {
113 schema: String,
114 table: String,
115 columns: Vec<String>,
116 },
117 DropPrimaryKey {
119 schema: String,
120 table: String,
121 name: String,
122 },
123 AddUnique {
125 schema: String,
126 table: String,
127 name: Option<String>,
128 columns: Vec<String>,
129 },
130 DropUnique {
132 schema: String,
133 table: String,
134 name: Option<String>,
135 },
136 AddForeignKey {
138 schema: String,
139 table: String,
140 fk: ForeignKeyModel,
141 },
142 DropForeignKey {
144 schema: String,
145 table: String,
146 name: Option<String>,
147 },
148 AddIndex {
150 schema: String,
151 table: String,
152 index: IndexModel,
153 },
154 DropIndex {
156 schema: String,
157 table: String,
158 name: String,
159 },
160 SetTableComment {
162 schema: String,
163 table: String,
164 comment: Option<String>,
165 },
166 SetColumnComment {
168 schema: String,
169 table: String,
170 column: String,
171 comment: Option<String>,
172 },
173 CreateFunction { function: FunctionModel },
175 ReplaceFunction { function: FunctionModel },
177 DropFunction { function: FunctionModel },
179 SetFunctionComment {
181 schema: String,
182 name: String,
183 identity_arguments: String,
184 comment: Option<String>,
185 },
186}
187
188impl MigrationOperation {
189 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 AlterColumnType {
219 old_type, new_type, ..
220 } => classify_type_change(old_type, new_type),
221 AddColumn { column, .. } => {
222 if !column.nullable && column.default_sql.is_none() {
224 DangerLevel::Caution
225 } else {
226 DangerLevel::Safe
227 }
228 }
229 }
230 }
231
232 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
390pub 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 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 if old_base == "text" && new_base == "varchar" {
416 return DangerLevel::Dangerous; }
418 if old_base == "varchar" && new_base == "text" {
419 return DangerLevel::Safe; }
421 if old_base == "numeric" && new_base == "numeric" {
423 return compare_numeric(&old_args, &new_args);
424 }
425 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 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
449fn 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
468fn 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 (_, None) => DangerLevel::Safe,
480 (None, Some(_)) => DangerLevel::Dangerous,
481 }
482}
483
484fn 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#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
497pub struct MigrationPlan {
498 pub operations: Vec<MigrationOperation>,
500}
501
502impl MigrationPlan {
503 pub fn is_empty(&self) -> bool {
505 self.operations.is_empty()
506 }
507
508 pub fn danger_count(&self) -> usize {
510 self.operations
511 .iter()
512 .filter(|o| o.danger().is_dangerous())
513 .count()
514 }
515
516 pub fn caution_count(&self) -> usize {
518 self.operations
519 .iter()
520 .filter(|o| o.danger() == DangerLevel::Caution)
521 .count()
522 }
523}
524
525pub fn build_plan(diff: &SchemaDiff) -> MigrationPlan {
535 use MigrationOperation::*;
536
537 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(); let mut p4_tables: Vec<MigrationOperation> = Vec::new(); 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 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 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 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 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 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 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 assert_eq!(classify_type_change("varchar(64)", "text"), Safe);
902 assert_eq!(classify_type_change("text", "varchar(64)"), Dangerous);
903 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 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 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 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 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}