-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
119 lines (93 loc) · 2.47 KB
/
migrate.go
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
package sqlmigrator
import (
"fmt"
"slices"
)
type migrator struct {
DBRepo DBRepo
}
func NewMigrator(dbRepo DBRepo) *migrator {
return &migrator{
DBRepo: dbRepo,
}
}
func (m *migrator) MigrateUp(ctx *Context, num int) ([]*MigrationFileEntry, error) {
appliedMigrations := []*MigrationFileEntry{}
migrationToApply := LoadUnappliedMigrations(ctx)
if len(migrationToApply) == 0 {
fmt.Println("no migrations to apply")
return appliedMigrations, nil
}
num = min(num, len(migrationToApply))
if num > 0 {
migrationToApply = migrationToApply[:num]
}
for _, migration := range migrationToApply {
if ctx.DryRun {
displayMigration(migration)
continue
}
upFileContent, _ := migration.LoadFileContent()
err := m.DBRepo.Exec(upFileContent)
if err != nil {
return appliedMigrations, err
}
migration.Committed = true
appliedMigrations = append(appliedMigrations, migration)
// commit to db migration table
dbEntry := &MigrationDBEntry{
Number: migration.Number,
Name: migration.Name,
Direction: "up",
}
err = m.DBRepo.PushHistory(dbEntry)
if err != nil {
return appliedMigrations, err
}
}
return appliedMigrations, nil
}
func (m *migrator) MigrateDown(ctx *Context, num int) ([]*MigrationFileEntry, error) {
rolledBackMigrations := []*MigrationFileEntry{}
migrationToApply := LoadAppliedMigrations(ctx)
if len(migrationToApply) == 0 {
fmt.Println("no migrations to rollback")
return rolledBackMigrations, nil
}
slices.Reverse(migrationToApply)
num = min(num, len(migrationToApply))
if num > 0 {
migrationToApply = migrationToApply[:num]
}
for _, migration := range migrationToApply {
if ctx.DryRun {
displayMigration(migration)
continue
}
_, downFileContent := migration.LoadFileContent()
err := m.DBRepo.Exec(downFileContent)
if err != nil {
return rolledBackMigrations, err
}
migration.Committed = false
rolledBackMigrations = append(rolledBackMigrations, migration)
// commit to db migration table
dbEntry := &MigrationDBEntry{
Number: migration.Number,
Name: migration.Name,
Direction: "down",
}
err = m.DBRepo.PushHistory(dbEntry)
if err != nil {
return rolledBackMigrations, err
}
}
return rolledBackMigrations, nil
}
func (m *migrator) MigrationHistory(ctx *Context) ([]*MigrationDBEntry, error) {
return m.DBRepo.LoadHistory()
}
func displayMigration(migration *MigrationFileEntry) {
fileName := migration.EntryString()
fmt.Println("up\t:", fileName)
}