forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migration_box.go
68 lines (60 loc) · 1.49 KB
/
migration_box.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
package pop
import (
"github.com/gobuffalo/packr"
"github.com/pkg/errors"
)
// MigrationBox is a wrapper around packr.Box and Migrator.
// This will allow you to run migrations from a packed box
// inside of a compiled binary.
type MigrationBox struct {
Migrator
Box packr.Box
}
// NewMigrationBox from a packr.Box and a Connection.
func NewMigrationBox(box packr.Box, c *Connection) (MigrationBox, error) {
fm := MigrationBox{
Migrator: NewMigrator(c),
Box: box,
}
err := fm.findMigrations()
if err != nil {
return fm, errors.WithStack(err)
}
return fm, nil
}
func (fm *MigrationBox) findMigrations() error {
return fm.Box.Walk(func(p string, f packr.File) error {
info, err := f.FileInfo()
if err != nil {
return errors.WithStack(err)
}
matches := mrx.FindAllStringSubmatch(info.Name(), -1)
if matches == nil || len(matches) == 0 {
return nil
}
m := matches[0]
mf := Migration{
Path: p,
Version: m[1],
Name: m[2],
Direction: m[3],
Type: m[4],
Runner: func(mf Migration, tx *Connection) error {
content, err := migrationContent(mf, tx, f)
if err != nil {
return errors.Wrapf(err, "error processing %s", mf.Path)
}
if content == "" {
return nil
}
err = tx.RawQuery(content).Exec()
if err != nil {
return errors.Wrapf(err, "error executing %s, sql: %s", mf.Path, content)
}
return nil
},
}
fm.Migrations[mf.Direction] = append(fm.Migrations[mf.Direction], mf)
return nil
})
}