forked from mattermost/morph
-
Notifications
You must be signed in to change notification settings - Fork 0
/
morph.go
294 lines (241 loc) · 7.35 KB
/
morph.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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package morph
import (
"context"
"errors"
"fmt"
"log"
"os"
"sort"
"strings"
"time"
"github.com/flywave/morph/models"
"github.com/flywave/morph/drivers"
"github.com/flywave/morph/sources"
ms "github.com/flywave/morph/drivers/mysql"
ps "github.com/flywave/morph/drivers/postgres"
_ "github.com/flywave/morph/sources/embedded"
_ "github.com/flywave/morph/sources/file"
)
var migrationProgressStart = "== %s: migrating ================================================="
var migrationProgressFinished = "== %s: migrated (%s) ========================================"
const maxProgressLogLength = 100
type Morph struct {
config *Config
driver drivers.Driver
source sources.Source
mutex drivers.Locker
}
type Config struct {
Logger Logger
LockTimeout time.Duration
LockKey string
}
type EngineOption func(*Morph)
func WithLogger(logger Logger) EngineOption {
return func(m *Morph) {
m.config.Logger = logger
}
}
func WithLockTimeout(lockTimeout time.Duration) EngineOption {
return func(m *Morph) {
m.config.LockTimeout = lockTimeout
}
}
func SetMigrationTableName(name string) EngineOption {
return func(m *Morph) {
_ = m.driver.SetConfig("MigrationsTable", name)
}
}
func SetSatementTimeoutInSeconds(n int) EngineOption {
return func(m *Morph) {
_ = m.driver.SetConfig("StatementTimeoutInSecs", n)
}
}
// WithLock creates a lock table in the database so that the migrations are
// guaranteed to be executed from a single instance. The key is used for naming
// the mutex.
func WithLock(key string) EngineOption {
return func(m *Morph) {
m.config.LockKey = key
}
}
// New creates a new instance of the migrations engine from an existing db instance and a migrations source.
// If the driver implements the Lockable interface, it will also wait until it has acquired a lock.
func New(ctx context.Context, driver drivers.Driver, source sources.Source, options ...EngineOption) (*Morph, error) {
engine := &Morph{
config: &Config{
Logger: newColorLogger(log.New(os.Stderr, "", log.LstdFlags)), // add default logger
},
source: source,
driver: driver,
}
for _, option := range options {
option(engine)
}
if err := driver.Ping(); err != nil {
return nil, err
}
if impl, ok := driver.(drivers.Lockable); ok && engine.config.LockKey != "" {
var mx drivers.Locker
var err error
switch impl.DriverName() {
case "mysql":
mx, err = ms.NewMutex(engine.config.LockKey, driver, engine.config.Logger)
case "postgres":
mx, err = ps.NewMutex(engine.config.LockKey, driver, engine.config.Logger)
default:
err = errors.New("driver does not support locking")
}
if err != nil {
return nil, err
}
engine.mutex = mx
err = mx.Lock(ctx)
if err != nil {
return nil, err
}
}
return engine, nil
}
// Close closes the underlying database connection of the engine.
func (m *Morph) Close() error {
if m.mutex != nil {
err := m.mutex.Unlock()
if err != nil {
return err
}
}
return m.driver.Close()
}
// ApplyAll applies all pending migrations.
func (m *Morph) ApplyAll() error {
_, err := m.Apply(-1)
return err
}
// Applies limited number of migrations upwards.
func (m *Morph) Apply(limit int) (int, error) {
appliedMigrations, err := m.driver.AppliedMigrations()
if err != nil {
return -1, err
}
pendingMigrations, err := computePendingMigrations(appliedMigrations, m.source.Migrations())
if err != nil {
return -1, err
}
migrations := make([]*models.Migration, 0)
sortedMigrations := sortMigrations(pendingMigrations)
for _, migration := range sortedMigrations {
if migration.Direction != models.Up {
continue
}
migrations = append(migrations, migration)
}
steps := limit
if len(migrations) < steps {
return -1, fmt.Errorf("there are only %d migrations avaliable, but you requested %d", len(migrations), steps)
}
if limit < 0 {
steps = len(migrations)
}
var applied int
for i := 0; i < steps; i++ {
start := time.Now()
migrationName := migrations[i].Name
m.config.Logger.Println(formatProgress(fmt.Sprintf(migrationProgressStart, migrationName)))
if err := m.driver.Apply(migrations[i], true); err != nil {
return applied, err
}
applied++
elapsed := time.Since(start)
m.config.Logger.Println(formatProgress(fmt.Sprintf(migrationProgressFinished, migrationName, fmt.Sprintf("%.4fs", elapsed.Seconds()))))
}
return applied, nil
}
// ApplyDown rollbacks a limited number of migrations
// if limit is given below zero, all down scripts are going to be applied.
func (m *Morph) ApplyDown(limit int) (int, error) {
appliedMigrations, err := m.driver.AppliedMigrations()
if err != nil {
return -1, err
}
sortedMigrations := reverseSortMigrations(appliedMigrations)
downMigrations, err := findDownScripts(sortedMigrations, m.source.Migrations())
if err != nil {
return -1, err
}
steps := limit
if len(sortedMigrations) < steps {
return -1, fmt.Errorf("there are only %d migrations avaliable, but you requested %d", len(sortedMigrations), steps)
}
if limit < 0 {
steps = len(sortedMigrations)
}
var applied int
for i := 0; i < steps; i++ {
start := time.Now()
migrationName := sortedMigrations[i].Name
m.config.Logger.Println(formatProgress(fmt.Sprintf(migrationProgressStart, migrationName)))
down := downMigrations[migrationName]
if err := m.driver.Apply(down, true); err != nil {
return applied, err
}
applied++
elapsed := time.Since(start)
m.config.Logger.Println(formatProgress(fmt.Sprintf(migrationProgressFinished, migrationName, fmt.Sprintf("%.4fs", elapsed.Seconds()))))
}
return applied, nil
}
func reverseSortMigrations(migrations []*models.Migration) []*models.Migration {
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].Version > migrations[j].Version
})
return migrations
}
func sortMigrations(migrations []*models.Migration) []*models.Migration {
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].RawName < migrations[j].RawName
})
return migrations
}
func computePendingMigrations(appliedMigrations []*models.Migration, sourceMigrations []*models.Migration) ([]*models.Migration, error) {
// sourceMigrations has to be greater or equal to databaseMigrations
if len(appliedMigrations) > len(sourceMigrations) {
return nil, errors.New("migration mismatch, there are more migrations applied than those were specified in source")
}
dict := make(map[string]*models.Migration)
for _, appliedMigration := range appliedMigrations {
dict[appliedMigration.Name] = appliedMigration
}
var pendingMigrations []*models.Migration
for _, sourceMigration := range sourceMigrations {
if _, ok := dict[sourceMigration.Name]; !ok {
pendingMigrations = append(pendingMigrations, sourceMigration)
}
}
return pendingMigrations, nil
}
func findDownScripts(appliedMigrations []*models.Migration, sourceMigrations []*models.Migration) (map[string]*models.Migration, error) {
tmp := make(map[string]*models.Migration)
for _, m := range sourceMigrations {
if m.Direction != models.Down {
continue
}
tmp[m.Name] = m
}
for _, m := range appliedMigrations {
_, ok := tmp[m.Name]
if !ok {
return nil, fmt.Errorf("could not find down script for %s", m.Name)
}
}
return tmp, nil
}
func formatProgress(p string) string {
if len(p) < maxProgressLogLength {
return p + strings.Repeat("=", maxProgressLogLength-len(p))
}
if len(p) > maxProgressLogLength {
return p[:maxProgressLogLength]
}
return p
}