-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrate.go
303 lines (238 loc) · 6.34 KB
/
migrate.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
295
296
297
298
299
300
301
302
303
package migo
import (
"errors"
"fmt"
"sort"
"time"
)
// Migrate is entry point struct that can trigger
// database updating or downgrading
type Migrate struct {
migrations []Migration
c Connection
loaders []MigrationLoader
migrationsLoaded bool
}
// NewMigrate creates new struct that can start migration.
// `c` is a connection to database, you can use gorm connection.
// `loaders` is migrations loaders, it can be `sql` or `go` migrations loader
func NewMigrate(c Connection, loaders ...MigrationLoader) *Migrate {
return &Migrate{
c: c,
loaders: loaders,
}
}
// SetConncetion sets database connection that will be used for migration
func (m *Migrate) SetConncetion(c Connection) {
m.c = c
}
// Add adds migrations to the pool of pending migrations
func (m *Migrate) Add(migration Migration) error {
m.migrations = append(m.migrations, migration)
return nil
}
// UpToLatest loads all needed migrations,
// filters migrations that already applied,
// and starts migration process.
func (m *Migrate) UpToLatest() error {
err := m.loadMigrations()
if err != nil {
return errors.New("can't load migrations " + err.Error())
}
verStrs, err := m.c.LoadVersions()
if err != nil {
return err
}
appliedVers, err := StringsToVersions(verStrs)
if err != nil {
return err
}
lastVer := GreatestVersion(appliedVers)
m.ensureThatMigrationsNotLost(lastVer, appliedVers)
migrationsToApply := m.migrationsAfter(lastVer)
fmt.Printf("Going to apply %d migration(s)...\n", len(migrationsToApply))
for _, migration := range migrationsToApply {
fmt.Printf("Applying '%s' migration... \n", migration.Version())
start := time.Now()
migration.SetConnection(m.c)
err := migration.Up()
if err != nil {
return err
}
err = m.c.SetVersion(migration.Version().String())
if err != nil {
return err
}
fmt.Printf("Applied '%s'! Duration: %v.\n\n", migration.Version(), time.Since(start))
}
fmt.Println("Database up to date!")
m.migrations = []Migration{}
return nil
}
// DownWithSteps runs migrations to downgrade database version.
// `steps` is number of latest migrations that needs to be unapplied.
func (m *Migrate) DownWithSteps(steps int) error {
err := m.loadMigrations()
if err != nil {
return errors.New("can't load migrations " + err.Error())
}
verStrs, err := m.c.LoadVersions()
if err != nil {
return err
}
appliedVers, err := StringsToVersions(verStrs)
if err != nil {
return err
}
lastVer := GreatestVersion(appliedVers)
migrationsToApply := m.migrationsBefore(lastVer)
migrationsToApplyCount := steps
if steps > len(migrationsToApply) {
migrationsToApplyCount = len(migrationsToApply)
}
fmt.Printf("Going to discard %d migration(s)...\n", len(migrationsToApply))
for i := 0; i < migrationsToApplyCount; i++ {
migration := migrationsToApply[i]
fmt.Printf("Discarding '%s' migration... \n", migration.Version())
migration.SetConnection(m.c)
err := migration.Down()
if err != nil {
return err
}
err = m.c.SetVersion(migration.Version().String())
if err != nil {
return err
}
fmt.Printf("Discarded '%s'!\n\n", migration.Version())
}
return nil
}
func (m *Migrate) loadMigrations() error {
if m.migrationsLoaded {
return nil
}
for _, loader := range m.loaders {
migrations, err := loader.Load()
if err != nil {
return err
}
for _, migration := range migrations {
err = m.Add(migration)
if err != nil {
return err
}
}
}
m.migrationsLoaded = true
return nil
}
func (m *Migrate) migrationsAfter(v *Version) []Migration {
ms := m.sort(m.migrations, true)
for i := range ms {
if m.migrations[i].Version().GreaterThan(v) {
return m.migrations[i:]
}
}
return []Migration{}
}
func (m *Migrate) migrationsBefore(v *Version) []Migration {
ms := m.sort(m.migrations, false)
for i := range ms {
otherV := m.migrations[i].Version()
if v.GreaterThanOrEqual(&otherV) {
return m.migrations[i:]
}
}
return []Migration{}
}
func (m *Migrate) sort(ms []Migration, asc bool) []Migration {
sort.SliceStable(ms, func(i, j int) bool {
left := m.migrations[i].Version()
right := m.migrations[j].Version()
if asc {
return right.GreaterThan(&left)
}
return left.GreaterThan(&right)
})
return ms
}
func (m *Migrate) ensureThatMigrationsNotLost(lastVersion *Version, appliedVersions []Version) {
migsBefore := m.migrationsBefore(lastVersion)
for _, mig := range migsBefore {
found := false
for _, v := range appliedVersions {
if v.String() == mig.Version().String() {
found = true
break
}
}
if !found {
panic(fmt.Sprintf("version '%s' not found in applied migrations", mig.Version()))
}
}
}
func (m *Migrate) lostMigrations(lastVersion *Version, appliedVersions []Version) []Migration {
migsBefore := m.migrationsBefore(lastVersion)
lost := []Migration{}
for _, mig := range migsBefore {
found := false
for _, v := range appliedVersions {
if v.String() == mig.Version().String() {
found = true
break
}
}
if !found {
lost = append(lost, mig)
}
}
lost = m.sort(lost, true)
return lost
}
func (m *Migrate) ApplyLostAndPanic() error {
err := m.applyLost(5 * time.Second)
if err != nil {
return err
}
panic("remove ApplyLostAndPanic code")
}
func (m *Migrate) ApplyLostIfAny() error {
return m.applyLost(0)
}
func (m *Migrate) applyLost(delayBetweenMigrations time.Duration) error {
err := m.loadMigrations()
if err != nil {
return errors.New("can't load migrations " + err.Error())
}
verStrs, err := m.c.LoadVersions()
if err != nil {
return err
}
appliedVers, err := StringsToVersions(verStrs)
if err != nil {
return err
}
lastVer := GreatestVersion(appliedVers)
migrationsToApply := m.lostMigrations(lastVer, appliedVers)
fmt.Printf("Found %d lost migration(s)...\n", len(migrationsToApply))
for _, migration := range migrationsToApply {
fmt.Printf("Applying '%s' migration... \n", migration.Version())
if delayBetweenMigrations > 0 {
time.Sleep(delayBetweenMigrations)
}
start := time.Now()
migration.SetConnection(m.c)
err := migration.Up()
if err != nil {
return err
}
err = m.c.SetVersion(migration.Version().String())
if err != nil {
return err
}
fmt.Printf("Applied '%s'! Duration: %v.\n\n", migration.Version(), time.Since(start))
}
fmt.Println("Lost migrations applied!")
m.migrations = []Migration{}
return nil
}