forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migration_file.go
76 lines (63 loc) · 1.35 KB
/
migration_file.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
package pop
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"path"
"github.com/markbates/pop/fizz"
)
type migrationFile struct {
Path string
FileName string
Version string
Name string
Direction string
FileType string
}
type migrationFiles []migrationFile
func (mfs migrationFiles) Len() int {
return len(mfs)
}
func (mfs migrationFiles) Less(i, j int) bool {
return mfs[i].Version < mfs[j].Version
}
func (mfs migrationFiles) Swap(i, j int) {
mfs[i], mfs[j] = mfs[j], mfs[i]
}
func (m migrationFile) Content(c *Connection) (string, error) {
b, err := ioutil.ReadFile(m.Path)
if err != nil {
return "", nil
}
content := string(b)
ext := path.Ext(m.FileName)
t := template.Must(template.New("sql").Parse(content))
var bb bytes.Buffer
err = t.Execute(&bb, c.Dialect.Details())
if err != nil {
return "", err
}
content = bb.String()
if ext == ".fizz" {
content, err = fizz.AString(content, c.Dialect.FizzTranslator())
if err != nil {
return "", err
}
}
return content, nil
}
func (m migrationFile) Execute(c *Connection) error {
content, err := m.Content(c)
if err != nil {
return fmt.Errorf("Error processing %s: %s", m.FileName, err)
}
if content == "" {
return nil
}
err = c.RawQuery(content).Exec()
if err != nil {
return fmt.Errorf("Error executing %s: %s", m.FileName, err)
}
return nil
}