forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrator.go
209 lines (192 loc) · 5.3 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
package pop
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"text/tabwriter"
"time"
"github.com/pkg/errors"
)
var mrx = regexp.MustCompile("(\\d+)_(.+)\\.(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": Migrations{},
"down": Migrations{},
},
}
}
// 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
}
// Up runs pending "up" migrations and applies them to the database.
func (m Migrator) Up() error {
c := m.Connection
return m.exec(func() error {
mfs := m.Migrations["up"]
sort.Sort(mfs)
for _, mi := range mfs {
exists, err := c.Where("version = ?", mi.Version).Exists("schema_migration")
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 schema_migration (version) values ('%s')", mi.Version))
return errors.Wrapf(err, "problem inserting migration version %s", mi.Version)
})
if err != nil {
return errors.WithStack(err)
}
fmt.Printf("> %s\n", mi.Name)
}
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 {
count, err := c.Count("schema_migration")
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("schema_migration")
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("delete from schema_migration where version = ?", mi.Version).Exec()
return errors.Wrapf(err, "problem deleting migration version %s", mi.Version)
})
if err != nil {
return err
}
fmt.Printf("< %s\n", mi.Name)
}
return nil
})
}
// Reset the database by runing 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
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")
}
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("schema_migration")
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
f, err := os.Create(filepath.Join(m.SchemaPath, "schema.sql"))
if err != nil {
return errors.WithStack(err)
}
err = c.Dialect.DumpSchema(f)
if err != nil {
return errors.WithStack(err)
}
return nil
}
func (m Migrator) exec(fn func() error) error {
now := time.Now()
defer m.DumpMigrationSchema()
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.Now().Sub(timerStart).Seconds()
if diff > 60 {
fmt.Printf("\n%.4f minutes\n", diff/60)
} else {
fmt.Printf("\n%.4f seconds\n", diff)
}
}