/
registry.go
59 lines (47 loc) · 1.43 KB
/
registry.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
package rockhopper
import (
"fmt"
"runtime"
"strings"
log "github.com/sirupsen/logrus"
)
type RegistryKey struct {
Package string
Version int64
}
// registeredGoMigrations stores the global registered migrations
// applications may register their compiledd migration scrips into this map
var registeredGoMigrations = map[RegistryKey]*Migration{}
// AddMigration registers a migration to the global map
func AddMigration(up, down TransactionHandler) {
pc, filename, _, _ := runtime.Caller(1)
funcName := runtime.FuncForPC(pc).Name()
lastSlash := strings.LastIndexByte(funcName, '/')
if lastSlash < 0 {
lastSlash = 0
}
lastDot := strings.LastIndexByte(funcName[lastSlash:], '.') + lastSlash
packageName := funcName[:lastDot]
AddNamedMigration(packageName, filename, up, down)
}
// AddNamedMigration registers a migration to the global map with a given name
func AddNamedMigration(packageName, filename string, up, down TransactionHandler) {
v, err := FileNumericComponent(filename)
if err != nil {
log.Panic(err)
}
migration := &Migration{
Package: packageName,
Registered: true,
Version: v,
UpFn: up,
DownFn: down,
Source: filename,
UseTx: true,
}
key := RegistryKey{Package: packageName, Version: v}
if existing, ok := registeredGoMigrations[key]; ok {
panic(fmt.Sprintf("failed to add migration %q: version conflicts with %q", filename, existing.Source))
}
registeredGoMigrations[key] = migration
}