-
Notifications
You must be signed in to change notification settings - Fork 99
/
gormigrate.go
485 lines (414 loc) · 12.2 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
// Package gormigrate is a minimalistic migration helper for Gorm (http://gorm.io)
package gormigrate
import (
"errors"
"fmt"
"reflect"
"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)
}
// 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)
}
func (g *Gormigrate) migrate(migrationID string) 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(); err != nil {
return err
}
return g.commit()
}
}
for _, migration := range g.migrations {
if err := g.runMigration(migration); 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); 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); 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); err != nil {
return err
}
return g.commit()
}
func (g *Gormigrate) rollbackMigration(m *Migration) error {
if m.Rollback == nil {
return ErrRollbackImpossible
}
if err := m.Rollback(g.tx); err != nil {
return err
}
cond := fmt.Sprintf("%s = ?", g.options.IDColumnName)
return g.tx.Table(g.options.TableName).Where(cond, m.ID).Delete(g.model()).Error
}
func (g *Gormigrate) runInitSchema() error {
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) error {
if len(migration.ID) == 0 {
return ErrMissingID
}
migrationRan, err := g.migrationRan(migration)
if err != nil {
return err
}
if !migrationRan {
if err := migration.Migrate(g.tx); err != nil {
return err
}
if err := g.insertMigration(migration.ID); err != nil {
return err
}
}
return nil
}
// model returns pointer to dynamically created gorm migration model struct value
//
// struct defined as {
// ID string `gorm:"primaryKey;column:<Options.IDColumnName>;size:<Options.IDColumnSize>"`
// }
func (g *Gormigrate) model() interface{} {
f := reflect.StructField{
Name: reflect.ValueOf("ID").Interface().(string),
Type: reflect.TypeOf(""),
Tag: reflect.StructTag(fmt.Sprintf(
`gorm:"primaryKey;column:%s;size:%d"`,
g.options.IDColumnName,
g.options.IDColumnSize,
)),
}
structType := reflect.StructOf([]reflect.StructField{f})
structValue := reflect.New(structType).Elem()
return structValue.Addr().Interface()
}
func (g *Gormigrate) createMigrationTableIfNotExists() error {
if g.tx.Migrator().HasTable(g.options.TableName) {
return nil
}
return g.tx.Table(g.options.TableName).AutoMigrate(g.model())
}
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) {
rows, err := g.tx.Table(g.options.TableName).Select(g.options.IDColumnName).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 {
record := g.model()
reflect.ValueOf(record).Elem().FieldByName("ID").SetString(id)
return g.tx.Table(g.options.TableName).Create(record).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()
}
}