-
Notifications
You must be signed in to change notification settings - Fork 0
/
yam.go
85 lines (73 loc) · 1.57 KB
/
yam.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
package yam
// Migrate runs migrations after validating that they have not been run
func Migrate(m Migrator, migrations migrationSlice, offset int64) error {
if m != nil {
if err := m.setup(); err != nil {
return err
}
}
for _, migration := range migrations.first(offset) {
var skip bool
if m != nil {
migrated, err := m.checkVersion(migration.Version)
if err != nil {
return err
}
skip = !migrated
}
if migration.Up != nil && !skip {
if err := migration.Up(); err != nil {
return err
}
if m != nil {
if err := m.writeVersion(migration.Version); err != nil {
return err
}
}
}
}
if m != nil {
if err := m.teardown(); err != nil {
return err
}
}
return nil
}
// Rollback runs migrations after validating that they have not been run
func Rollback(m Migrator, migrations migrationSlice, offset int64) error {
if m != nil {
if err := m.setup(); err != nil {
return err
}
}
rollbacks := make(migrationSlice, len(migrations))
for i := 0; i < len(migrations); i++ {
rollbacks[i] = migrations[len(migrations)-i-1]
}
for _, rollback := range rollbacks.first(offset) {
var skip bool
if m != nil {
migrated, err := m.checkVersion(rollback.Version)
if err != nil {
return err
}
skip = migrated
}
if rollback.Down != nil && !skip {
if err := rollback.Down(); err != nil {
return err
}
if m != nil {
if err := m.deleteVersion(rollback.Version); err != nil {
return err
}
}
}
}
if m != nil {
if err := m.teardown(); err != nil {
return err
}
}
return nil
}