| 111 | } |
| 112 | |
| 113 | func TestMigrate_ordering(t *testing.T) { |
| 114 | db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) |
| 115 | if err != nil { |
| 116 | t.Fatalf("failed to open database: %v", err) |
| 117 | } |
| 118 | |
| 119 | // Create table before migrations |
| 120 | if err := db.Exec("CREATE TABLE log (value INTEGER)").Error; err != nil { |
| 121 | t.Fatalf("failed to create table: %v", err) |
| 122 | } |
| 123 | |
| 124 | // Create migrations with unsorted filesystem |
| 125 | migrationsFs := unsortedFS{ |
| 126 | MapFS: fstest.MapFS{ |
| 127 | "010-tenth.sql": &fstest.MapFile{ |
| 128 | Data: []byte("INSERT INTO log (value) VALUES (3);"), |
| 129 | }, |
| 130 | "001-first.sql": &fstest.MapFile{ |
| 131 | Data: []byte("INSERT INTO log (value) VALUES (1);"), |
| 132 | }, |
| 133 | "002-second.sql": &fstest.MapFile{ |
| 134 | Data: []byte("INSERT INTO log (value) VALUES (2);"), |
| 135 | }, |
| 136 | }, |
| 137 | } |
| 138 | |
| 139 | // Run migrations |
| 140 | if err := migrate(db, migrationsFs); err != nil { |
| 141 | t.Fatalf("migration failed: %v", err) |
| 142 | } |
| 143 | |
| 144 | // Verify migrations ran in correct order (1, 2, 3) |
| 145 | var values []int |
| 146 | if err := db.Raw("SELECT value FROM log ORDER BY rowid").Scan(&values).Error; err != nil { |
| 147 | t.Fatalf("failed to query log: %v", err) |
| 148 | } |
| 149 | |
| 150 | expected := []int{1, 2, 3} |
| 151 | if len(values) != len(expected) { |
| 152 | t.Fatalf("expected %d rows, got %d", len(expected), len(values)) |
| 153 | } |
| 154 | |
| 155 | for i, v := range values { |
| 156 | if v != expected[i] { |
| 157 | t.Errorf("row %d: expected value %d, got %d", i, expected[i], v) |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | func TestMigrate_duplicateVersion(t *testing.T) { |
| 163 | db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) |