forked from go-gormigrate/gormigrate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gormigrate.go
554 lines (471 loc) · 13.7 KB
/
gormigrate.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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
package gormigrate
import (
"errors"
"fmt"
"gorm.io/gorm"
)
const (
initSchemaMigrationID = "SCHEMA_INIT"
)
// MigrateFunc is the func signature for migrating.
type MigrateFunc func(*gorm.DB) error
// RollbackFunc is the func signature for rollbacking.
type RollbackFunc func(*gorm.DB) error
// InitSchemaFunc is the func signature for initializing the schema.
type InitSchemaFunc func(*gorm.DB) error
// Options define options for all migrations.
type Options struct {
// TableName is the migration table.
TableName string
// IDColumnName is the name of column where the migration id will be stored.
IDColumnName string
// IDColumnSize is the length of the migration id column
IDColumnSize int
// UseTransaction makes Gormigrate execute migrations inside a single transaction.
// Keep in mind that not all databases support DDL commands inside transactions.
UseTransaction bool
// ValidateUnknownMigrations will cause migrate to fail if there's unknown migration
// IDs in the database
ValidateUnknownMigrations bool
}
// Migration represents a database migration (a modification to be made on the database).
type Migration struct {
// ID is the migration identifier. Usually a timestamp like "201601021504".
ID string
// Migrate is a function that will br executed while running this migration.
Migrate MigrateFunc
// Rollback will be executed on rollback. Can be nil.
Rollback RollbackFunc
}
// Gormigrate represents a collection of all migrations of a database schema.
type Gormigrate struct {
db *gorm.DB
tx *gorm.DB
options *Options
migrations []*Migration
initSchema InitSchemaFunc
}
// ReservedIDError is returned when a migration is using a reserved ID
type ReservedIDError struct {
ID string
}
func (e *ReservedIDError) Error() string {
return fmt.Sprintf(`gormigrate: Reserved migration ID: "%s"`, e.ID)
}
// DuplicatedIDError is returned when more than one migration have the same ID
type DuplicatedIDError struct {
ID string
}
func (e *DuplicatedIDError) Error() string {
return fmt.Sprintf(`gormigrate: Duplicated migration ID: "%s"`, e.ID)
}
var (
// DefaultOptions can be used if you don't want to think about options.
DefaultOptions = &Options{
TableName: "migrations",
IDColumnName: "id",
IDColumnSize: 255,
UseTransaction: false,
ValidateUnknownMigrations: false,
}
// ErrRollbackImpossible is returned when trying to rollback a migration
// that has no rollback function.
ErrRollbackImpossible = errors.New("gormigrate: It's impossible to rollback this migration")
// ErrNoMigrationDefined is returned when no migration is defined.
ErrNoMigrationDefined = errors.New("gormigrate: No migration defined")
// ErrMissingID is returned when the ID od migration is equal to ""
ErrMissingID = errors.New("gormigrate: Missing ID in migration")
// ErrNoRunMigration is returned when any run migration was found while
// running RollbackLast
ErrNoRunMigration = errors.New("gormigrate: Could not find last run migration")
// ErrMigrationIDDoesNotExist is returned when migrating or rolling back to a migration ID that
// does not exist in the list of migrations
ErrMigrationIDDoesNotExist = errors.New("gormigrate: Tried to migrate to an ID that doesn't exist")
// ErrUnknownPastMigration is returned if a migration exists in the DB that doesn't exist in the code
ErrUnknownPastMigration = errors.New("gormigrate: Found migration in DB that does not exist in code")
)
// New returns a new Gormigrate.
func New(db *gorm.DB, options *Options, migrations []*Migration) *Gormigrate {
if options.TableName == "" {
options.TableName = DefaultOptions.TableName
}
if options.IDColumnName == "" {
options.IDColumnName = DefaultOptions.IDColumnName
}
if options.IDColumnSize == 0 {
options.IDColumnSize = DefaultOptions.IDColumnSize
}
return &Gormigrate{
db: db,
options: options,
migrations: migrations,
}
}
// InitSchema sets a function that is run if no migration is found.
// The idea is preventing to run all migrations when a new clean database
// is being migrating. In this function you should create all tables and
// foreign key necessary to your application.
func (g *Gormigrate) InitSchema(initSchema InitSchemaFunc) {
g.initSchema = initSchema
}
// Migrate executes all migrations that did not run yet.
func (g *Gormigrate) Migrate() error {
if !g.hasMigrations() {
return ErrNoMigrationDefined
}
var targetMigrationID string
if len(g.migrations) > 0 {
targetMigrationID = g.migrations[len(g.migrations)-1].ID
}
return g.migrate(targetMigrationID, false)
}
// FakeMigrate flags all migrations that did not run yet as migrated.
func (g *Gormigrate) FakeMigrate() error {
if !g.hasMigrations() {
return ErrNoMigrationDefined
}
var targetMigrationID string
if len(g.migrations) > 0 {
targetMigrationID = g.migrations[len(g.migrations)-1].ID
}
return g.migrate(targetMigrationID, true)
}
// MigrateTo executes all migrations that did not run yet up to the migration that matches `migrationID`.
func (g *Gormigrate) MigrateTo(migrationID string) error {
if err := g.checkIDExist(migrationID); err != nil {
return err
}
return g.migrate(migrationID, false)
}
// FakeMigrateTo flags all migrations that did not run yet up to the migration that matches `migrationID` as migrated.
func (g *Gormigrate) FakeMigrateTo(migrationID string) error {
if err := g.checkIDExist(migrationID); err != nil {
return err
}
return g.migrate(migrationID, true)
}
func (g *Gormigrate) migrate(migrationID string, fake bool) error {
if !g.hasMigrations() {
return ErrNoMigrationDefined
}
if err := g.checkReservedID(); err != nil {
return err
}
if err := g.checkDuplicatedID(); err != nil {
return err
}
g.begin()
defer g.rollback()
if err := g.createMigrationTableIfNotExists(); err != nil {
return err
}
if g.options.ValidateUnknownMigrations {
unknownMigrations, err := g.unknownMigrationsHaveHappened()
if err != nil {
return err
}
if unknownMigrations {
return ErrUnknownPastMigration
}
}
if g.initSchema != nil {
canInitializeSchema, err := g.canInitializeSchema()
if err != nil {
return err
}
if canInitializeSchema {
if err := g.runInitSchema(fake); err != nil {
return err
}
return g.commit()
}
}
for _, migration := range g.migrations {
if err := g.runMigration(migration, fake); err != nil {
return err
}
if migrationID != "" && migration.ID == migrationID {
break
}
}
return g.commit()
}
// There are migrations to apply if either there's a defined
// initSchema function or if the list of migrations is not empty.
func (g *Gormigrate) hasMigrations() bool {
return g.initSchema != nil || len(g.migrations) > 0
}
// Check whether any migration is using a reserved ID.
// For now there's only have one reserved ID, but there may be more in the future.
func (g *Gormigrate) checkReservedID() error {
for _, m := range g.migrations {
if m.ID == initSchemaMigrationID {
return &ReservedIDError{ID: m.ID}
}
}
return nil
}
func (g *Gormigrate) checkDuplicatedID() error {
lookup := make(map[string]struct{}, len(g.migrations))
for _, m := range g.migrations {
if _, ok := lookup[m.ID]; ok {
return &DuplicatedIDError{ID: m.ID}
}
lookup[m.ID] = struct{}{}
}
return nil
}
func (g *Gormigrate) checkIDExist(migrationID string) error {
for _, migrate := range g.migrations {
if migrate.ID == migrationID {
return nil
}
}
return ErrMigrationIDDoesNotExist
}
// RollbackLast undo the last migration
func (g *Gormigrate) RollbackLast() error {
if len(g.migrations) == 0 {
return ErrNoMigrationDefined
}
g.begin()
defer g.rollback()
lastRunMigration, err := g.getLastRunMigration()
if err != nil {
return err
}
if err := g.rollbackMigration(lastRunMigration, false); err != nil {
return err
}
return g.commit()
}
// FakeRollbackLast deletes migration record of the last migration
func (g *Gormigrate) FakeRollbackLast() error {
if len(g.migrations) == 0 {
return ErrNoMigrationDefined
}
g.begin()
defer g.rollback()
lastRunMigration, err := g.getLastRunMigration()
if err != nil {
return err
}
if err := g.rollbackMigration(lastRunMigration, true); err != nil {
return err
}
return g.commit()
}
// RollbackTo undoes migrations up to the given migration that matches the `migrationID`.
// Migration with the matching `migrationID` is not rolled back.
func (g *Gormigrate) RollbackTo(migrationID string) error {
if len(g.migrations) == 0 {
return ErrNoMigrationDefined
}
if err := g.checkIDExist(migrationID); err != nil {
return err
}
g.begin()
defer g.rollback()
for i := len(g.migrations) - 1; i >= 0; i-- {
migration := g.migrations[i]
if migration.ID == migrationID {
break
}
migrationRan, err := g.migrationRan(migration)
if err != nil {
return err
}
if migrationRan {
if err := g.rollbackMigration(migration, false); err != nil {
return err
}
}
}
return g.commit()
}
// FakeRollbackTo deletes migration records up to the given migration that matches the `migrationID`.
// Migration with the matching `migrationID` is not rolled back.
func (g *Gormigrate) FakeRollbackTo(migrationID string) error {
if len(g.migrations) == 0 {
return ErrNoMigrationDefined
}
if err := g.checkIDExist(migrationID); err != nil {
return err
}
g.begin()
defer g.rollback()
for i := len(g.migrations) - 1; i >= 0; i-- {
migration := g.migrations[i]
if migration.ID == migrationID {
break
}
migrationRan, err := g.migrationRan(migration)
if err != nil {
return err
}
if migrationRan {
if err := g.rollbackMigration(migration, true); err != nil {
return err
}
}
}
return g.commit()
}
func (g *Gormigrate) getLastRunMigration() (*Migration, error) {
for i := len(g.migrations) - 1; i >= 0; i-- {
migration := g.migrations[i]
migrationRan, err := g.migrationRan(migration)
if err != nil {
return nil, err
}
if migrationRan {
return migration, nil
}
}
return nil, ErrNoRunMigration
}
// RollbackMigration undo a migration.
func (g *Gormigrate) RollbackMigration(m *Migration) error {
g.begin()
defer g.rollback()
if err := g.rollbackMigration(m, false); err != nil {
return err
}
return g.commit()
}
// FakeRollbackMigration deletes migration record of a migration.
func (g *Gormigrate) FakeRollbackMigration(m *Migration) error {
g.begin()
defer g.rollback()
if err := g.rollbackMigration(m, true); err != nil {
return err
}
return g.commit()
}
func (g *Gormigrate) rollbackMigration(m *Migration, fake bool) error {
if m.Rollback == nil {
return ErrRollbackImpossible
}
if !fake {
if err := m.Rollback(g.tx); err != nil {
return err
}
}
sql := fmt.Sprintf("DELETE FROM %s WHERE %s = ?", g.options.TableName, g.options.IDColumnName)
return g.tx.Exec(sql, m.ID).Error
}
func (g *Gormigrate) runInitSchema(fake bool) error {
if !fake {
if err := g.initSchema(g.tx); err != nil {
return err
}
}
if err := g.insertMigration(initSchemaMigrationID); err != nil {
return err
}
for _, migration := range g.migrations {
if err := g.insertMigration(migration.ID); err != nil {
return err
}
}
return nil
}
func (g *Gormigrate) runMigration(migration *Migration, fake bool) error {
if len(migration.ID) == 0 {
return ErrMissingID
}
migrationRan, err := g.migrationRan(migration)
if err != nil {
return err
}
if !migrationRan {
if !fake {
if err := migration.Migrate(g.tx); err != nil {
return err
}
}
if err := g.insertMigration(migration.ID); err != nil {
return err
}
}
return nil
}
func (g *Gormigrate) createMigrationTableIfNotExists() error {
if g.tx.Migrator().HasTable(g.options.TableName) {
return nil
}
sql := fmt.Sprintf("CREATE TABLE %s (%s VARCHAR(%d) PRIMARY KEY)", g.options.TableName, g.options.IDColumnName, g.options.IDColumnSize)
return g.tx.Exec(sql).Error
}
func (g *Gormigrate) migrationRan(m *Migration) (bool, error) {
var count int64
err := g.tx.
Table(g.options.TableName).
Where(fmt.Sprintf("%s = ?", g.options.IDColumnName), m.ID).
Count(&count).
Error
return count > 0, err
}
// The schema can be initialised only if it hasn't been initialised yet
// and no other migration has been applied already.
func (g *Gormigrate) canInitializeSchema() (bool, error) {
migrationRan, err := g.migrationRan(&Migration{ID: initSchemaMigrationID})
if err != nil {
return false, err
}
if migrationRan {
return false, nil
}
// If the ID doesn't exist, we also want the list of migrations to be empty
var count int64
err = g.tx.
Table(g.options.TableName).
Count(&count).
Error
return count == 0, err
}
func (g *Gormigrate) unknownMigrationsHaveHappened() (bool, error) {
sql := fmt.Sprintf("SELECT %s FROM %s", g.options.IDColumnName, g.options.TableName)
rows, err := g.tx.Raw(sql).Rows()
if err != nil {
return false, err
}
defer rows.Close()
validIDSet := make(map[string]struct{}, len(g.migrations)+1)
validIDSet[initSchemaMigrationID] = struct{}{}
for _, migration := range g.migrations {
validIDSet[migration.ID] = struct{}{}
}
for rows.Next() {
var pastMigrationID string
if err := rows.Scan(&pastMigrationID); err != nil {
return false, err
}
if _, ok := validIDSet[pastMigrationID]; !ok {
return true, nil
}
}
return false, nil
}
func (g *Gormigrate) insertMigration(id string) error {
sql := fmt.Sprintf("INSERT INTO %s (%s) VALUES (?)", g.options.TableName, g.options.IDColumnName)
return g.tx.Exec(sql, id).Error
}
func (g *Gormigrate) begin() {
if g.options.UseTransaction {
g.tx = g.db.Begin()
} else {
g.tx = g.db
}
}
func (g *Gormigrate) commit() error {
if g.options.UseTransaction {
return g.tx.Commit().Error
}
return nil
}
func (g *Gormigrate) rollback() {
if g.options.UseTransaction {
g.tx.Rollback()
}
}