forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_migrator.go
108 lines (95 loc) · 2.32 KB
/
file_migrator.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
package pop
import (
"bytes"
"io"
"io/ioutil"
"os"
"path/filepath"
"text/template"
"github.com/markbates/pop/fizz"
"github.com/pkg/errors"
)
// FileMigrator is a migrator for SQL and Fizz
// files on disk at a specified path.
type FileMigrator struct {
Migrator
Path string
}
// NewFileMigrator for a path and a Connection
func NewFileMigrator(path string, c *Connection) (FileMigrator, error) {
fm := FileMigrator{
Migrator: NewMigrator(c),
Path: path,
}
fm.SchemaPath = path
err := fm.findMigrations()
if err != nil {
return fm, errors.WithStack(err)
}
return fm, nil
}
func (fm *FileMigrator) findMigrations() error {
dir := fm.Path
if fi, err := os.Stat(dir); err != nil || !fi.IsDir() {
// directory doesn't exist
return nil
}
filepath.Walk(dir, func(p string, info os.FileInfo, err error) error {
if !info.IsDir() {
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 {
f, err := os.Open(p)
if err != nil {
return errors.WithStack(err)
}
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
})
return nil
}
func migrationContent(mf Migration, c *Connection, r io.Reader) (string, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return "", nil
}
content := string(b)
t := template.Must(template.New("sql").Parse(content))
var bb bytes.Buffer
err = t.Execute(&bb, c.Dialect.Details())
if err != nil {
return "", errors.Wrapf(err, "could not execute migration template %s", mf.Path)
}
content = bb.String()
if mf.Type == "fizz" {
content, err = fizz.AString(content, c.Dialect.FizzTranslator())
if err != nil {
return "", errors.Wrapf(err, "could not fizz the migration %s", mf.Path)
}
}
return content, nil
}