forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigration.go
More file actions
201 lines (180 loc) · 5.08 KB
/
migration.go
File metadata and controls
201 lines (180 loc) · 5.08 KB
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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", 0, 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
}, -1)
}
func (c *Connection) MigrateDown(path string, step int) error {
now := time.Now()
defer printTimer(now)
err := c.createSchemaMigrations()
if err != nil {
return errors.Wrap(err, "migration down: problem creating schema migrations")
}
//increase skip by
count, err := c.Count("schema_migration")
if err != nil {
return errors.Wrap(err, "migration down: unable count existing migration")
}
return findMigrations(path, "down", count, func(m migrationFile) error {
exists, err := c.Where("version = ?", m.Version).Exists("schema_migration")
if err != nil || !exists {
fmt.Errorf("migration missing: %s", m.Version)
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
}, step)
}
func (c *Connection) MigrateReset(path string) error {
err := c.MigrateDown(path, -1)
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, runned int, fn func(migrationFile) error, step int) 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))
// skip all runned migration
mfs = mfs[len(mfs)-runned:]
// run only required steps
if step > 0 && len(mfs) >= step {
mfs = mfs[:step]
}
} 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)
}
}