forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrator.go
260 lines (243 loc) · 6.8 KB
/
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
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package pop
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"text/tabwriter"
"time"
"github.com/gobuffalo/pop/logging"
"github.com/pkg/errors"
)
var mrx = regexp.MustCompile(`^(\d+)_([^.]+)(\.[a-z0-9]+)?\.(up|down)\.(sql|fizz)$`)
// NewMigrator returns a new "blank" migrator. It is recommended
// to use something like MigrationBox or FileMigrator. A "blank"
// Migrator should only be used as the basis for a new type of
// migration system.
func NewMigrator(c *Connection) Migrator {
return Migrator{
Connection: c,
Migrations: map[string]Migrations{
"up": {},
"down": {},
},
}
}
// Migrator forms the basis of all migrations systems.
// It does the actual heavy lifting of running migrations.
// When building a new migration system, you should embed this
// type into your migrator.
type Migrator struct {
Connection *Connection
SchemaPath string
Migrations map[string]Migrations
}
// UpLogOnly insert pending "up" migrations logs only, without applying the patch.
// It's used when loading the schema dump, instead of the migrations.
func (m Migrator) UpLogOnly() error {
c := m.Connection
return m.exec(func() error {
mtn := c.MigrationTableName()
mfs := m.Migrations["up"]
sort.Sort(mfs)
return c.Transaction(func(tx *Connection) error {
for _, mi := range mfs {
if mi.DBType != "all" && mi.DBType != c.Dialect.Name() {
// Skip migration for non-matching dialect
continue
}
exists, err := c.Where("version = ?", mi.Version).Exists(mtn)
if err != nil {
return errors.Wrapf(err, "problem checking for migration version %s", mi.Version)
}
if exists {
continue
}
_, err = tx.Store.Exec(fmt.Sprintf("insert into %s (version) values ('%s')", mtn, mi.Version))
if err != nil {
return errors.Wrapf(err, "problem inserting migration version %s", mi.Version)
}
}
return nil
})
})
}
// Up runs pending "up" migrations and applies them to the database.
func (m Migrator) Up() error {
c := m.Connection
return m.exec(func() error {
mtn := c.MigrationTableName()
mfs := m.Migrations["up"]
sort.Sort(mfs)
applied := 0
for _, mi := range mfs {
if mi.DBType != "all" && mi.DBType != c.Dialect.Name() {
// Skip migration for non-matching dialect
continue
}
exists, err := c.Where("version = ?", mi.Version).Exists(mtn)
if err != nil {
return errors.Wrapf(err, "problem checking for migration version %s", mi.Version)
}
if exists {
continue
}
err = c.Transaction(func(tx *Connection) error {
err := mi.Run(tx)
if err != nil {
return err
}
_, err = tx.Store.Exec(fmt.Sprintf("insert into %s (version) values ('%s')", mtn, mi.Version))
return errors.Wrapf(err, "problem inserting migration version %s", mi.Version)
})
if err != nil {
return errors.WithStack(err)
}
log(logging.Info, "> %s", mi.Name)
applied++
}
if applied == 0 {
log(logging.Info, "Migrations already up to date, nothing to apply")
}
return nil
})
}
// Down runs pending "down" migrations and rolls back the
// database by the specified number of steps.
func (m Migrator) Down(step int) error {
c := m.Connection
return m.exec(func() error {
mtn := c.MigrationTableName()
count, err := c.Count(mtn)
if err != nil {
return errors.Wrap(err, "migration down: unable count existing migration")
}
mfs := m.Migrations["down"]
sort.Sort(sort.Reverse(mfs))
// skip all runned migration
if len(mfs) > count {
mfs = mfs[len(mfs)-count:]
}
// run only required steps
if step > 0 && len(mfs) >= step {
mfs = mfs[:step]
}
for _, mi := range mfs {
exists, err := c.Where("version = ?", mi.Version).Exists(mtn)
if err != nil || !exists {
return errors.Wrapf(err, "problem checking for migration version %s", mi.Version)
}
err = c.Transaction(func(tx *Connection) error {
err := mi.Run(tx)
if err != nil {
return err
}
err = tx.RawQuery(fmt.Sprintf("delete from %s where version = ?", mtn), mi.Version).Exec()
return errors.Wrapf(err, "problem deleting migration version %s", mi.Version)
})
if err != nil {
return err
}
log(logging.Info, "< %s", mi.Name)
}
return nil
})
}
// Reset the database by running the down migrations followed by the up migrations.
func (m Migrator) Reset() error {
err := m.Down(-1)
if err != nil {
return errors.WithStack(err)
}
return m.Up()
}
// CreateSchemaMigrations sets up a table to track migrations. This is an idempotent
// operation.
func (m Migrator) CreateSchemaMigrations() error {
c := m.Connection
mtn := c.MigrationTableName()
err := c.Open()
if err != nil {
return errors.Wrap(err, "could not open connection")
}
_, err = c.Store.Exec(fmt.Sprintf("select * from %s", mtn))
if err == nil {
return nil
}
return c.Transaction(func(tx *Connection) error {
schemaMigrations := newSchemaMigrations(mtn)
smSQL, err := c.Dialect.FizzTranslator().CreateTable(schemaMigrations)
if err != nil {
return errors.Wrap(err, "could not build SQL for schema migration table")
}
err = tx.RawQuery(smSQL).Exec()
if err != nil {
return errors.WithStack(errors.Wrap(err, smSQL))
}
return nil
})
}
// Status prints out the status of applied/pending migrations.
func (m Migrator) Status() error {
err := m.CreateSchemaMigrations()
if err != nil {
return errors.WithStack(err)
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', tabwriter.TabIndent)
fmt.Fprintln(w, "Version\tName\tStatus\t")
for _, mf := range m.Migrations["up"] {
exists, err := m.Connection.Where("version = ?", mf.Version).Exists(m.Connection.MigrationTableName())
if err != nil {
return errors.Wrapf(err, "problem with migration")
}
state := "Pending"
if exists {
state = "Applied"
}
fmt.Fprintf(w, "%s\t%s\t%s\t\n", mf.Version, mf.Name, state)
}
return w.Flush()
}
// DumpMigrationSchema will generate a file of the current database schema
// based on the value of Migrator.SchemaPath
func (m Migrator) DumpMigrationSchema() error {
if m.SchemaPath == "" {
return nil
}
c := m.Connection
schema := filepath.Join(m.SchemaPath, "schema.sql")
f, err := os.Create(schema)
if err != nil {
return errors.WithStack(err)
}
err = c.Dialect.DumpSchema(f)
if err != nil {
os.RemoveAll(schema)
return errors.WithStack(err)
}
return nil
}
func (m Migrator) exec(fn func() error) error {
now := time.Now()
defer func() {
err := m.DumpMigrationSchema()
if err != nil {
log(logging.Warn, "Migrator: unable to dump schema: %v", err)
}
}()
defer printTimer(now)
err := m.CreateSchemaMigrations()
if err != nil {
return errors.Wrap(err, "Migrator: problem creating schema migrations")
}
return fn()
}
func printTimer(timerStart time.Time) {
diff := time.Since(timerStart).Seconds()
if diff > 60 {
log(logging.Info, "%.4f minutes", diff/60)
} else {
log(logging.Info, "%.4f seconds", diff)
}
}