-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigration.go
76 lines (63 loc) · 1.27 KB
/
migration.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
package migration
import (
"os"
"text/template"
"github.com/jinzhu/gorm"
)
type performFn func(*gorm.DB) error
type Migration struct {
DisableDDL bool `gorm:"-"`
Perform performFn `gorm:"-"`
Version string `gorm:"size:255;PRIMARY_KEY;NOT NULL"`
}
var (
Dir = "./migrations"
internalMigrations migrations
)
func Add(m *Migration) {
internalMigrations = append(internalMigrations, m)
}
func CreateDefault(name string) {
Create(Dir, name)
}
func Create(dir, name string) {
m := &migrationTemplate{dir: dir, name: name}
m.createDir()
tmpl, err := template.New("migration").Parse(migrationTemplateStr)
if err != nil {
panic(err)
}
f, err := os.Create(m.file())
if err != nil {
panic(err)
}
defer f.Close()
err = tmpl.Execute(f, *m)
if err != nil {
panic(err)
}
}
func IsComplete(db *gorm.DB) bool {
return internalMigrations.IsComplete(db)
}
func Migrate(db *gorm.DB) error {
db.AutoMigrate(&Migration{})
return internalMigrations.Migrate(db)
}
func (m Migration) Migrate(db *gorm.DB) {
var tx *gorm.DB
if m.DisableDDL {
tx = db
} else {
tx = db.Begin()
defer tx.Commit()
}
if err := m.Perform(tx); err != nil {
tx.Rollback()
panic(err)
}
if err := tx.Create(&m).Error; err != nil {
tx.Rollback()
panic(err)
}
}