-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathdiff.rs
More file actions
3419 lines (3096 loc) · 123 KB
/
diff.rs
File metadata and controls
3419 lines (3096 loc) · 123 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, BTreeSet, HashSet, VecDeque};
use vespertide_core::{MigrationAction, MigrationPlan, TableConstraint, TableDef};
use crate::error::PlannerError;
/// Topologically sort tables based on foreign key dependencies.
/// Returns tables in order where tables with no FK dependencies come first,
/// and tables that reference other tables come after their referenced tables.
fn topological_sort_tables<'a>(tables: &[&'a TableDef]) -> Result<Vec<&'a TableDef>, PlannerError> {
if tables.is_empty() {
return Ok(vec![]);
}
// Build a map of table names for quick lookup
let table_names: HashSet<&str> = tables.iter().map(|t| t.name.as_str()).collect();
// Build adjacency list: for each table, list the tables it depends on (via FK)
// Use BTreeMap for consistent ordering
// Use BTreeSet to avoid duplicate dependencies (e.g., multiple FKs referencing the same table)
let mut dependencies: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
for table in tables {
let mut deps_set: BTreeSet<&str> = BTreeSet::new();
for constraint in &table.constraints {
if let TableConstraint::ForeignKey { ref_table, .. } = constraint {
// Only consider dependencies within the set of tables being created
if table_names.contains(ref_table.as_str()) && ref_table != &table.name {
deps_set.insert(ref_table.as_str());
}
}
}
dependencies.insert(table.name.as_str(), deps_set.into_iter().collect());
}
// Kahn's algorithm for topological sort
// Calculate in-degrees (number of tables that depend on each table)
// Use BTreeMap for consistent ordering
let mut in_degree: BTreeMap<&str, usize> = BTreeMap::new();
for table in tables {
in_degree.entry(table.name.as_str()).or_insert(0);
}
// For each dependency, increment the in-degree of the dependent table
for (table_name, deps) in &dependencies {
for _dep in deps {
// The table has dependencies, so those referenced tables must come first
// We actually want the reverse: tables with dependencies have higher in-degree
}
// Actually, we need to track: if A depends on B, then A has in-degree from B
// So A cannot be processed until B is processed
*in_degree.entry(table_name).or_insert(0) += deps.len();
}
// Start with tables that have no dependencies
// BTreeMap iteration is already sorted by key
let mut queue: VecDeque<&str> = in_degree
.iter()
.filter(|(_, deg)| **deg == 0)
.map(|(name, _)| *name)
.collect();
let mut result: Vec<&TableDef> = Vec::new();
let table_map: BTreeMap<&str, &TableDef> =
tables.iter().map(|t| (t.name.as_str(), *t)).collect();
while let Some(table_name) = queue.pop_front() {
if let Some(&table) = table_map.get(table_name) {
result.push(table);
}
// Collect tables that become ready (in-degree becomes 0)
// Use BTreeSet for consistent ordering
let mut ready_tables: BTreeSet<&str> = BTreeSet::new();
for (dependent, deps) in &dependencies {
if deps.contains(&table_name)
&& let Some(degree) = in_degree.get_mut(dependent)
{
*degree -= 1;
if *degree == 0 {
ready_tables.insert(dependent);
}
}
}
for t in ready_tables {
queue.push_back(t);
}
}
// Check for cycles
if result.len() != tables.len() {
let remaining: Vec<&str> = tables
.iter()
.map(|t| t.name.as_str())
.filter(|name| !result.iter().any(|t| t.name.as_str() == *name))
.collect();
return Err(PlannerError::TableValidation(format!(
"Circular foreign key dependency detected among tables: {:?}",
remaining
)));
}
Ok(result)
}
/// Sort DeleteTable actions so that tables with FK references are deleted first.
/// This is the reverse of creation order - use topological sort then reverse.
/// Helper function to extract table name from DeleteTable action
/// Safety: should only be called on DeleteTable actions
fn extract_delete_table_name(action: &MigrationAction) -> &str {
match action {
MigrationAction::DeleteTable { table } => table.as_str(),
_ => panic!("Expected DeleteTable action"),
}
}
fn sort_delete_tables(actions: &mut [MigrationAction], all_tables: &BTreeMap<&str, &TableDef>) {
// Collect DeleteTable actions and their indices
let delete_indices: Vec<usize> = actions
.iter()
.enumerate()
.filter_map(|(i, a)| {
if matches!(a, MigrationAction::DeleteTable { .. }) {
Some(i)
} else {
None
}
})
.collect();
if delete_indices.len() <= 1 {
return;
}
// Extract table names being deleted
// Use BTreeSet for consistent ordering
let delete_table_names: BTreeSet<&str> = delete_indices
.iter()
.map(|&i| extract_delete_table_name(&actions[i]))
.collect();
// Build dependency graph for tables being deleted
// dependencies[A] = [B] means A has FK referencing B
// Use BTreeMap for consistent ordering
// Use BTreeSet to avoid duplicate dependencies (e.g., multiple FKs referencing the same table)
let mut dependencies: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
for &table_name in &delete_table_names {
let mut deps_set: BTreeSet<&str> = BTreeSet::new();
if let Some(table_def) = all_tables.get(table_name) {
for constraint in &table_def.constraints {
if let TableConstraint::ForeignKey { ref_table, .. } = constraint
&& delete_table_names.contains(ref_table.as_str())
&& ref_table != table_name
{
deps_set.insert(ref_table.as_str());
}
}
}
dependencies.insert(table_name, deps_set.into_iter().collect());
}
// Use Kahn's algorithm for topological sort
// in_degree[A] = number of tables A depends on
// Use BTreeMap for consistent ordering
let mut in_degree: BTreeMap<&str, usize> = BTreeMap::new();
for &table_name in &delete_table_names {
in_degree.insert(
table_name,
dependencies.get(table_name).map_or(0, |d| d.len()),
);
}
// Start with tables that have no dependencies (can be deleted last in creation order)
// BTreeMap iteration is already sorted
let mut queue: VecDeque<&str> = in_degree
.iter()
.filter(|(_, deg)| **deg == 0)
.map(|(name, _)| *name)
.collect();
let mut sorted_tables: Vec<&str> = Vec::new();
while let Some(table_name) = queue.pop_front() {
sorted_tables.push(table_name);
// For each table that has this one as a dependency, decrement its in-degree
// Use BTreeSet for consistent ordering of newly ready tables
let mut ready_tables: BTreeSet<&str> = BTreeSet::new();
for (&dependent, deps) in &dependencies {
if deps.contains(&table_name)
&& let Some(degree) = in_degree.get_mut(dependent)
{
*degree -= 1;
if *degree == 0 {
ready_tables.insert(dependent);
}
}
}
for t in ready_tables {
queue.push_back(t);
}
}
// Reverse to get deletion order (tables with dependencies should be deleted first)
sorted_tables.reverse();
// Reorder the DeleteTable actions according to sorted order
let mut delete_actions: Vec<MigrationAction> =
delete_indices.iter().map(|&i| actions[i].clone()).collect();
delete_actions.sort_by(|a, b| {
let a_name = extract_delete_table_name(a);
let b_name = extract_delete_table_name(b);
let a_pos = sorted_tables.iter().position(|&t| t == a_name).unwrap_or(0);
let b_pos = sorted_tables.iter().position(|&t| t == b_name).unwrap_or(0);
a_pos.cmp(&b_pos)
});
// Put them back
for (i, idx) in delete_indices.iter().enumerate() {
actions[*idx] = delete_actions[i].clone();
}
}
/// Diff two schema snapshots into a migration plan.
/// Schemas are normalized for comparison purposes, but the original (non-normalized)
/// tables are used in migration actions to preserve inline constraint definitions.
pub fn diff_schemas(from: &[TableDef], to: &[TableDef]) -> Result<MigrationPlan, PlannerError> {
let mut actions: Vec<MigrationAction> = Vec::new();
// Normalize both schemas for comparison (to ensure inline and table-level constraints are treated equally)
let from_normalized: Vec<TableDef> = from
.iter()
.map(|t| {
t.normalize().map_err(|e| {
PlannerError::TableValidation(format!(
"Failed to normalize table '{}': {}",
t.name, e
))
})
})
.collect::<Result<Vec<_>, _>>()?;
let to_normalized: Vec<TableDef> = to
.iter()
.map(|t| {
t.normalize().map_err(|e| {
PlannerError::TableValidation(format!(
"Failed to normalize table '{}': {}",
t.name, e
))
})
})
.collect::<Result<Vec<_>, _>>()?;
// Use BTreeMap for consistent ordering
// Normalized versions for comparison
let from_map: BTreeMap<_, _> = from_normalized
.iter()
.map(|t| (t.name.as_str(), t))
.collect();
let to_map: BTreeMap<_, _> = to_normalized.iter().map(|t| (t.name.as_str(), t)).collect();
// Original (non-normalized) versions for migration storage
let to_original_map: BTreeMap<_, _> = to.iter().map(|t| (t.name.as_str(), t)).collect();
// Drop tables that disappeared.
for name in from_map.keys() {
if !to_map.contains_key(name) {
actions.push(MigrationAction::DeleteTable {
table: name.to_string(),
});
}
}
// Update existing tables and their indexes/columns.
for (name, to_tbl) in &to_map {
if let Some(from_tbl) = from_map.get(name) {
// Columns - use BTreeMap for consistent ordering
let from_cols: BTreeMap<_, _> = from_tbl
.columns
.iter()
.map(|c| (c.name.as_str(), c))
.collect();
let to_cols: BTreeMap<_, _> = to_tbl
.columns
.iter()
.map(|c| (c.name.as_str(), c))
.collect();
// Deleted columns - collect the set of columns being deleted for this table
let deleted_columns: BTreeSet<&str> = from_cols
.keys()
.filter(|col| !to_cols.contains_key(*col))
.copied()
.collect();
for col in &deleted_columns {
actions.push(MigrationAction::DeleteColumn {
table: name.to_string(),
column: col.to_string(),
});
}
// Modified columns - type changes
for (col, to_def) in &to_cols {
if let Some(from_def) = from_cols.get(col)
&& from_def.r#type.requires_migration(&to_def.r#type)
{
actions.push(MigrationAction::ModifyColumnType {
table: name.to_string(),
column: col.to_string(),
new_type: to_def.r#type.clone(),
});
}
}
// Modified columns - nullable changes
for (col, to_def) in &to_cols {
if let Some(from_def) = from_cols.get(col)
&& from_def.nullable != to_def.nullable
{
actions.push(MigrationAction::ModifyColumnNullable {
table: name.to_string(),
column: col.to_string(),
nullable: to_def.nullable,
fill_with: None,
});
}
}
// Modified columns - default value changes
for (col, to_def) in &to_cols {
if let Some(from_def) = from_cols.get(col) {
let from_default = from_def.default.as_ref().map(|d| d.to_sql());
let to_default = to_def.default.as_ref().map(|d| d.to_sql());
if from_default != to_default {
actions.push(MigrationAction::ModifyColumnDefault {
table: name.to_string(),
column: col.to_string(),
new_default: to_default,
});
}
}
}
// Modified columns - comment changes
for (col, to_def) in &to_cols {
if let Some(from_def) = from_cols.get(col)
&& from_def.comment != to_def.comment
{
actions.push(MigrationAction::ModifyColumnComment {
table: name.to_string(),
column: col.to_string(),
new_comment: to_def.comment.clone(),
});
}
}
// Added columns
// Note: Inline foreign keys are already converted to TableConstraint::ForeignKey
// by normalize(), so they will be handled in the constraint diff below.
for (col, def) in &to_cols {
if !from_cols.contains_key(col) {
actions.push(MigrationAction::AddColumn {
table: name.to_string(),
column: Box::new((*def).clone()),
fill_with: None,
});
}
}
// Constraints - compare and detect additions/removals (includes indexes)
// Skip RemoveConstraint for constraints where ALL columns are being deleted
// (the constraint will be automatically dropped when the column is dropped)
for from_constraint in &from_tbl.constraints {
if !to_tbl.constraints.contains(from_constraint) {
// Get the columns referenced by this constraint
let constraint_columns = from_constraint.columns();
// Skip if ALL columns of the constraint are being deleted
let all_columns_deleted = !constraint_columns.is_empty()
&& constraint_columns
.iter()
.all(|col| deleted_columns.contains(col.as_str()));
if !all_columns_deleted {
actions.push(MigrationAction::RemoveConstraint {
table: name.to_string(),
constraint: from_constraint.clone(),
});
}
}
}
for to_constraint in &to_tbl.constraints {
if !from_tbl.constraints.contains(to_constraint) {
actions.push(MigrationAction::AddConstraint {
table: name.to_string(),
constraint: to_constraint.clone(),
});
}
}
}
}
// Create new tables (and their indexes).
// Use original (non-normalized) tables to preserve inline constraint definitions.
// Collect new tables first, then topologically sort them by FK dependencies.
let new_tables: Vec<&TableDef> = to_map
.iter()
.filter(|(name, _)| !from_map.contains_key(*name))
.map(|(_, tbl)| *tbl)
.collect();
let sorted_new_tables = topological_sort_tables(&new_tables)?;
for tbl in sorted_new_tables {
// Get the original (non-normalized) table to preserve inline constraints
let original_tbl = to_original_map.get(tbl.name.as_str()).unwrap();
actions.push(MigrationAction::CreateTable {
table: original_tbl.name.clone(),
columns: original_tbl.columns.clone(),
constraints: original_tbl.constraints.clone(),
});
}
// Sort DeleteTable actions so tables with FK dependencies are deleted first
sort_delete_tables(&mut actions, &from_map);
Ok(MigrationPlan {
comment: None,
created_at: None,
version: 0,
actions,
})
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
use vespertide_core::{
ColumnDef, ColumnType, MigrationAction, SimpleColumnType,
schema::{primary_key::PrimaryKeySyntax, str_or_bool::StrOrBoolOrArray},
};
fn col(name: &str, ty: ColumnType) -> ColumnDef {
ColumnDef {
name: name.to_string(),
r#type: ty,
nullable: true,
default: None,
comment: None,
primary_key: None,
unique: None,
index: None,
foreign_key: None,
}
}
fn table(
name: &str,
columns: Vec<ColumnDef>,
constraints: Vec<vespertide_core::TableConstraint>,
) -> TableDef {
TableDef {
name: name.to_string(),
description: None,
columns,
constraints,
}
}
fn idx(name: &str, columns: Vec<&str>) -> TableConstraint {
TableConstraint::Index {
name: Some(name.to_string()),
columns: columns.into_iter().map(|s| s.to_string()).collect(),
}
}
#[rstest]
#[case::add_column_and_index(
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![],
)],
vec![table(
"users",
vec![
col("id", ColumnType::Simple(SimpleColumnType::Integer)),
col("name", ColumnType::Simple(SimpleColumnType::Text)),
],
vec![idx("ix_users__name", vec!["name"])],
)],
vec![
MigrationAction::AddColumn {
table: "users".into(),
column: Box::new(col("name", ColumnType::Simple(SimpleColumnType::Text))),
fill_with: None,
},
MigrationAction::AddConstraint {
table: "users".into(),
constraint: idx("ix_users__name", vec!["name"]),
},
]
)]
#[case::drop_table(
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![],
)],
vec![],
vec![MigrationAction::DeleteTable {
table: "users".into()
}]
)]
#[case::add_table_with_index(
vec![],
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![idx("idx_users_id", vec!["id"])],
)],
vec![
MigrationAction::CreateTable {
table: "users".into(),
columns: vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
constraints: vec![idx("idx_users_id", vec!["id"])],
},
]
)]
#[case::delete_column(
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer)), col("name", ColumnType::Simple(SimpleColumnType::Text))],
vec![],
)],
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![],
)],
vec![MigrationAction::DeleteColumn {
table: "users".into(),
column: "name".into(),
}]
)]
#[case::modify_column_type(
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![],
)],
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Text))],
vec![],
)],
vec![MigrationAction::ModifyColumnType {
table: "users".into(),
column: "id".into(),
new_type: ColumnType::Simple(SimpleColumnType::Text),
}]
)]
#[case::remove_index(
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![idx("idx_users_id", vec!["id"])],
)],
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![],
)],
vec![MigrationAction::RemoveConstraint {
table: "users".into(),
constraint: idx("idx_users_id", vec!["id"]),
}]
)]
#[case::add_index_existing_table(
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![],
)],
vec![table(
"users",
vec![col("id", ColumnType::Simple(SimpleColumnType::Integer))],
vec![idx("idx_users_id", vec!["id"])],
)],
vec![MigrationAction::AddConstraint {
table: "users".into(),
constraint: idx("idx_users_id", vec!["id"]),
}]
)]
fn diff_schemas_detects_additions(
#[case] from_schema: Vec<TableDef>,
#[case] to_schema: Vec<TableDef>,
#[case] expected_actions: Vec<MigrationAction>,
) {
let plan = diff_schemas(&from_schema, &to_schema).unwrap();
assert_eq!(plan.actions, expected_actions);
}
// Tests for integer enum handling
mod integer_enum {
use super::*;
use vespertide_core::{ComplexColumnType, EnumValues, NumValue};
#[test]
fn integer_enum_values_changed_no_migration() {
// Integer enum values changed - should NOT generate ModifyColumnType
let from = vec![table(
"orders",
vec![col(
"status",
ColumnType::Complex(ComplexColumnType::Enum {
name: "order_status".into(),
values: EnumValues::Integer(vec![
NumValue {
name: "Pending".into(),
value: 0,
},
NumValue {
name: "Shipped".into(),
value: 1,
},
]),
}),
)],
vec![],
)];
let to = vec![table(
"orders",
vec![col(
"status",
ColumnType::Complex(ComplexColumnType::Enum {
name: "order_status".into(),
values: EnumValues::Integer(vec![
NumValue {
name: "Pending".into(),
value: 0,
},
NumValue {
name: "Shipped".into(),
value: 1,
},
NumValue {
name: "Delivered".into(),
value: 2,
},
NumValue {
name: "Cancelled".into(),
value: 100,
},
]),
}),
)],
vec![],
)];
let plan = diff_schemas(&from, &to).unwrap();
assert!(
plan.actions.is_empty(),
"Expected no actions, got: {:?}",
plan.actions
);
}
#[test]
fn string_enum_values_changed_requires_migration() {
// String enum values changed - SHOULD generate ModifyColumnType
let from = vec![table(
"orders",
vec![col(
"status",
ColumnType::Complex(ComplexColumnType::Enum {
name: "order_status".into(),
values: EnumValues::String(vec!["pending".into(), "shipped".into()]),
}),
)],
vec![],
)];
let to = vec![table(
"orders",
vec![col(
"status",
ColumnType::Complex(ComplexColumnType::Enum {
name: "order_status".into(),
values: EnumValues::String(vec![
"pending".into(),
"shipped".into(),
"delivered".into(),
]),
}),
)],
vec![],
)];
let plan = diff_schemas(&from, &to).unwrap();
assert_eq!(plan.actions.len(), 1);
assert!(matches!(
&plan.actions[0],
MigrationAction::ModifyColumnType { table, column, .. }
if table == "orders" && column == "status"
));
}
}
// Tests for inline column constraints normalization
mod inline_constraints {
use super::*;
use vespertide_core::schema::foreign_key::ForeignKeyDef;
use vespertide_core::schema::foreign_key::ForeignKeySyntax;
use vespertide_core::schema::primary_key::PrimaryKeySyntax;
use vespertide_core::{StrOrBoolOrArray, TableConstraint};
fn col_with_pk(name: &str, ty: ColumnType) -> ColumnDef {
ColumnDef {
name: name.to_string(),
r#type: ty,
nullable: false,
default: None,
comment: None,
primary_key: Some(PrimaryKeySyntax::Bool(true)),
unique: None,
index: None,
foreign_key: None,
}
}
fn col_with_unique(name: &str, ty: ColumnType) -> ColumnDef {
ColumnDef {
name: name.to_string(),
r#type: ty,
nullable: true,
default: None,
comment: None,
primary_key: None,
unique: Some(StrOrBoolOrArray::Bool(true)),
index: None,
foreign_key: None,
}
}
fn col_with_index(name: &str, ty: ColumnType) -> ColumnDef {
ColumnDef {
name: name.to_string(),
r#type: ty,
nullable: true,
default: None,
comment: None,
primary_key: None,
unique: None,
index: Some(StrOrBoolOrArray::Bool(true)),
foreign_key: None,
}
}
fn col_with_fk(name: &str, ty: ColumnType, ref_table: &str, ref_col: &str) -> ColumnDef {
ColumnDef {
name: name.to_string(),
r#type: ty,
nullable: true,
default: None,
comment: None,
primary_key: None,
unique: None,
index: None,
foreign_key: Some(ForeignKeySyntax::Object(ForeignKeyDef {
ref_table: ref_table.to_string(),
ref_columns: vec![ref_col.to_string()],
on_delete: None,
on_update: None,
})),
}
}
#[test]
fn create_table_with_inline_pk() {
let plan = diff_schemas(
&[],
&[table(
"users",
vec![
col_with_pk("id", ColumnType::Simple(SimpleColumnType::Integer)),
col("name", ColumnType::Simple(SimpleColumnType::Text)),
],
vec![],
)],
)
.unwrap();
// Inline PK should be preserved in column definition
assert_eq!(plan.actions.len(), 1);
if let MigrationAction::CreateTable {
columns,
constraints,
..
} = &plan.actions[0]
{
// Constraints should be empty (inline PK not moved here)
assert_eq!(constraints.len(), 0);
// Check that the column has inline PK
let id_col = columns.iter().find(|c| c.name == "id").unwrap();
assert!(id_col.primary_key.is_some());
} else {
panic!("Expected CreateTable action");
}
}
#[test]
fn create_table_with_inline_unique() {
let plan = diff_schemas(
&[],
&[table(
"users",
vec![
col("id", ColumnType::Simple(SimpleColumnType::Integer)),
col_with_unique("email", ColumnType::Simple(SimpleColumnType::Text)),
],
vec![],
)],
)
.unwrap();
// Inline unique should be preserved in column definition
assert_eq!(plan.actions.len(), 1);
if let MigrationAction::CreateTable {
columns,
constraints,
..
} = &plan.actions[0]
{
// Constraints should be empty (inline unique not moved here)
assert_eq!(constraints.len(), 0);
// Check that the column has inline unique
let email_col = columns.iter().find(|c| c.name == "email").unwrap();
assert!(matches!(
email_col.unique,
Some(StrOrBoolOrArray::Bool(true))
));
} else {
panic!("Expected CreateTable action");
}
}
#[test]
fn create_table_with_inline_index() {
let plan = diff_schemas(
&[],
&[table(
"users",
vec![
col("id", ColumnType::Simple(SimpleColumnType::Integer)),
col_with_index("name", ColumnType::Simple(SimpleColumnType::Text)),
],
vec![],
)],
)
.unwrap();
// Inline index should be preserved in column definition, not moved to constraints
assert_eq!(plan.actions.len(), 1);
if let MigrationAction::CreateTable {
columns,
constraints,
..
} = &plan.actions[0]
{
// Constraints should be empty (inline index not moved here)
assert_eq!(constraints.len(), 0);
// Check that the column has inline index
let name_col = columns.iter().find(|c| c.name == "name").unwrap();
assert!(matches!(name_col.index, Some(StrOrBoolOrArray::Bool(true))));
} else {
panic!("Expected CreateTable action");
}
}
#[test]
fn create_table_with_inline_fk() {
let plan = diff_schemas(
&[],
&[table(
"posts",
vec![
col("id", ColumnType::Simple(SimpleColumnType::Integer)),
col_with_fk(
"user_id",
ColumnType::Simple(SimpleColumnType::Integer),
"users",
"id",
),
],
vec![],
)],
)
.unwrap();
// Inline FK should be preserved in column definition
assert_eq!(plan.actions.len(), 1);
if let MigrationAction::CreateTable {
columns,
constraints,
..
} = &plan.actions[0]
{
// Constraints should be empty (inline FK not moved here)
assert_eq!(constraints.len(), 0);
// Check that the column has inline FK
let user_id_col = columns.iter().find(|c| c.name == "user_id").unwrap();
assert!(user_id_col.foreign_key.is_some());
} else {
panic!("Expected CreateTable action");
}
}
#[test]
fn add_index_via_inline_constraint() {
// Existing table without index -> table with inline index
// Inline index (Bool(true)) is normalized to a named table-level constraint
let plan = diff_schemas(
&[table(
"users",
vec![
col("id", ColumnType::Simple(SimpleColumnType::Integer)),
col("name", ColumnType::Simple(SimpleColumnType::Text)),
],
vec![],
)],
&[table(
"users",
vec![
col("id", ColumnType::Simple(SimpleColumnType::Integer)),
col_with_index("name", ColumnType::Simple(SimpleColumnType::Text)),
],
vec![],
)],
)
.unwrap();
// Should generate AddConstraint with name: None (auto-generated indexes)
assert_eq!(plan.actions.len(), 1);
if let MigrationAction::AddConstraint { table, constraint } = &plan.actions[0] {
assert_eq!(table, "users");
if let TableConstraint::Index { name, columns } = constraint {
assert_eq!(name, &None); // Auto-generated indexes use None
assert_eq!(columns, &vec!["name".to_string()]);
} else {
panic!("Expected Index constraint, got {:?}", constraint);
}
} else {
panic!("Expected AddConstraint action, got {:?}", plan.actions[0]);
}
}
#[test]
fn create_table_with_all_inline_constraints() {
let mut id_col = col("id", ColumnType::Simple(SimpleColumnType::Integer));
id_col.primary_key = Some(PrimaryKeySyntax::Bool(true));
id_col.nullable = false;
let mut email_col = col("email", ColumnType::Simple(SimpleColumnType::Text));
email_col.unique = Some(StrOrBoolOrArray::Bool(true));
let mut name_col = col("name", ColumnType::Simple(SimpleColumnType::Text));
name_col.index = Some(StrOrBoolOrArray::Bool(true));
let mut org_id_col = col("org_id", ColumnType::Simple(SimpleColumnType::Integer));
org_id_col.foreign_key = Some(ForeignKeySyntax::Object(ForeignKeyDef {
ref_table: "orgs".into(),
ref_columns: vec!["id".into()],
on_delete: None,
on_update: None,
}));
let plan = diff_schemas(
&[],
&[table(
"users",
vec![id_col, email_col, name_col, org_id_col],
vec![],
)],
)
.unwrap();
// All inline constraints should be preserved in column definitions
assert_eq!(plan.actions.len(), 1);
if let MigrationAction::CreateTable {
columns,
constraints,
..
} = &plan.actions[0]
{
// Constraints should be empty (all inline)