-
Notifications
You must be signed in to change notification settings - Fork 86
/
migration.go
84 lines (74 loc) · 1.88 KB
/
migration.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
package repo
import (
"fmt"
"github.com/rs/zerolog/log"
)
type MigrationManager struct {
migrations map[int]Migration
}
// NewMigrationManager creates a new migration manager.
func NewMigrationManager(migrations ...Migration) (*MigrationManager, error) {
manager := &MigrationManager{
migrations: make(map[int]Migration),
}
for _, migration := range migrations {
if err := manager.Add(migration); err != nil {
return nil, err
}
}
return manager, nil
}
// Add adds a migration to the manager.
func (m *MigrationManager) Add(migration Migration) error {
if _, ok := m.migrations[migration.FromVersion]; ok {
return fmt.Errorf("migration from version %d already exists", migration.FromVersion)
}
m.migrations[migration.FromVersion] = migration
return nil
}
// Migrate runs the migrations on the given repo.
func (m *MigrationManager) Migrate(repo FsRepo) error {
currentVersion, err := repo.readVersion()
if err != nil {
return err
}
for {
migration, ok := m.migrations[currentVersion]
if !ok {
break
}
log.Info().Msgf("Migrating repo from version %d to %d", migration.FromVersion, migration.ToVersion)
if err := migration.Migrate(repo); err != nil {
return err
}
currentVersion = migration.ToVersion
err = repo.writeVersion(currentVersion)
if err != nil {
return err
}
}
return nil
}
type MigrationFn = func(FsRepo) error
type Migration struct {
FromVersion int
ToVersion int
Migrations []MigrationFn
}
// NewMigration creates a new migration.
func NewMigration(fromVersion, toVersion int, migrations ...MigrationFn) Migration {
return Migration{
FromVersion: fromVersion,
ToVersion: toVersion,
Migrations: migrations,
}
}
// Migrate runs the migrations on the given repo.
func (m Migration) Migrate(repo FsRepo) error {
for _, migration := range m.Migrations {
if err := migration(repo); err != nil {
return err
}
}
return nil
}