forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migration.go
187 lines (168 loc) · 4.67 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package pop
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"time"
"github.com/markbates/pop/fizz"
_ "github.com/mattn/go-sqlite3"
"github.com/pkg/errors"
)
var mrx = regexp.MustCompile("(\\d+)_(.+)\\.(up|down)\\.(sql|fizz)")
func init() {
MapTableName("schema_migrations", "schema_migration")
MapTableName("schema_migration", "schema_migration")
}
var schemaMigrations = fizz.Table{
Name: "schema_migration",
Columns: []fizz.Column{
{Name: "version", ColType: "string"},
},
Indexes: []fizz.Index{
{Name: "version_idx", Columns: []string{"version"}, Unique: true},
},
}
func MigrationCreate(path, name, ext string, up, down []byte) error {
n := time.Now().UTC()
s := n.Format("20060102150405")
err := os.MkdirAll(path, 0766)
if err != nil {
return errors.Wrapf(err, "couldn't create migrations path %s", path)
}
upf := filepath.Join(path, (fmt.Sprintf("%s_%s.up.%s", s, name, ext)))
err = ioutil.WriteFile(upf, up, 0666)
if err != nil {
return errors.Wrapf(err, "couldn't write up migration %s", upf)
}
fmt.Printf("> %s\n", upf)
downf := filepath.Join(path, (fmt.Sprintf("%s_%s.down.%s", s, name, ext)))
err = ioutil.WriteFile(downf, down, 0666)
if err != nil {
return errors.Wrapf(err, "couldn't write up migration %s", downf)
}
fmt.Printf("> %s\n", downf)
return nil
}
func (c *Connection) MigrateUp(path string) error {
now := time.Now()
defer printTimer(now)
err := c.createSchemaMigrations()
if err != nil {
return errors.Wrap(err, "migration up: problem creating schema migrations")
}
return findMigrations(path, "up", func(m migrationFile) error {
exists, err := c.Where("version = ?", m.Version).Exists("schema_migration")
if err != nil || exists {
return errors.Wrapf(err, "problem checking for migration version %s", m.Version)
}
err = c.Transaction(func(tx *Connection) error {
err := m.Execute(tx)
if err != nil {
return err
}
_, err = tx.Store.Exec(fmt.Sprintf("insert into schema_migration (version) values ('%s')", m.Version))
return errors.Wrapf(err, "problem inserting migration version %s", m.Version)
})
if err == nil {
fmt.Printf("> %s\n", m.FileName)
}
return err
})
}
func (c *Connection) MigrateDown(path string) error {
now := time.Now()
defer printTimer(now)
err := c.createSchemaMigrations()
if err != nil {
return errors.Wrap(err, "migration down: problem creating schema migrations")
}
return findMigrations(path, "down", func(m migrationFile) error {
exists, err := c.Where("version = ?", m.Version).Exists("schema_migration")
if err != nil || !exists {
return errors.Wrapf(err, "problem checking for migration version %s", m.Version)
}
err = c.Transaction(func(tx *Connection) error {
err := m.Execute(tx)
if err != nil {
return err
}
err = tx.RawQuery("delete from schema_migration where version = ?", m.Version).Exec()
return errors.Wrapf(err, "problem deleting migration version %s", m.Version)
})
if err == nil {
fmt.Printf("< %s\n", m.FileName)
}
return err
})
}
func (c *Connection) MigrateReset(path string) error {
err := c.MigrateDown(path)
if err != nil {
return err
}
return c.MigrateUp(path)
}
func (c *Connection) createSchemaMigrations() error {
err := c.Open()
if err != nil {
return errors.Wrap(err, "could not open connection")
}
_, err = c.Store.Exec("select * from schema_migration")
if err == nil {
return nil
}
return c.Transaction(func(tx *Connection) error {
smSQL, err := c.Dialect.FizzTranslator().CreateTable(schemaMigrations)
if err != nil {
return errors.Wrap(err, "could not build SQL for schema migration table")
}
return errors.Wrap(tx.RawQuery(smSQL).Exec(), "could not create schema migration table")
})
}
func findMigrations(dir string, direction string, fn func(migrationFile) error) error {
mfs := migrationFiles{}
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 := migrationFile{
Path: p,
FileName: m[0],
Version: m[1],
Name: m[2],
Direction: m[3],
FileType: m[4],
}
if mf.Direction == direction {
mfs = append(mfs, mf)
}
}
return nil
})
if direction == "down" {
sort.Sort(sort.Reverse(mfs))
} else {
sort.Sort(mfs)
}
for _, mf := range mfs {
err := fn(mf)
if err != nil {
return errors.Wrap(err, "error from called function")
}
}
return nil
}
func printTimer(timerStart time.Time) {
diff := time.Now().Sub(timerStart).Seconds()
if diff > 60 {
fmt.Printf("\n%.4f minutes\n", diff/60)
} else {
fmt.Printf("\n%.4f seconds\n", diff)
}
}