forked from robinjoseph08/go-pg-migrations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmigrate.go
155 lines (126 loc) · 3.11 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
package migrations
import (
"fmt"
"sort"
"time"
"github.com/go-pg/pg"
"github.com/go-pg/pg/orm"
)
var migrations []migration
// Register accepts a name, up, down, and options and adds the migration to the
// global migrations slice.
func Register(name string, up, down func(orm.DB) error, opts MigrationOptions) {
migrations = append(migrations, migration{
Name: name,
Up: up,
Down: down,
DisableTransaction: opts.DisableTransaction,
})
}
func migrate(db *pg.DB, directory string) error {
// sort the registered migrations by name (which will sort by the
// timestamp in their names)
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].Name < migrations[j].Name
})
// look at the migrations table to see the already run migrations
completed, err := getCompletedMigrations(db)
if err != nil {
return err
}
// diff the completed migrations from the registered migrations to find
// the migrations we still need to run
uncompleted := filterMigrations(migrations, completed, false)
// if there are no migrations that need to be run, exit early
if len(uncompleted) == 0 {
fmt.Println("Migrations already up to date")
return nil
}
// acquire the migration lock from the migrations_lock table
err = acquireLock(db)
if err != nil {
return err
}
defer releaseLock(db)
// find the last batch number
batch, err := getLastBatchNumber(db)
if err != nil {
return err
}
batch = batch + 1
fmt.Printf("Running batch %d with %d migration(s)...\n", batch, len(uncompleted))
for _, m := range uncompleted {
m.Batch = batch
var err error
if m.DisableTransaction {
err = m.Up(db)
} else {
err = db.RunInTransaction(func(tx *pg.Tx) error {
return m.Up(tx)
})
}
if err != nil {
return fmt.Errorf("%s: %s", m.Name, err)
}
m.CompletedAt = time.Now()
err = db.Insert(&m)
if err != nil {
return fmt.Errorf("%s: %s", m.Name, err)
}
fmt.Printf("Finished running %q\n", m.Name)
}
return nil
}
func getCompletedMigrations(db orm.DB) ([]migration, error) {
var completed []migration
err := db.
Model(&completed).
Order("id").
Select()
if err != nil {
return nil, err
}
return completed, nil
}
func filterMigrations(all, subset []migration, wantCompleted bool) []migration {
subsetMap := map[string]bool{}
for _, c := range subset {
subsetMap[c.Name] = true
}
var d []migration
for _, a := range all {
if subsetMap[a.Name] == wantCompleted {
d = append(d, a)
}
}
return d
}
func acquireLock(db *pg.DB) error {
l := lock{ID: lockID, IsLocked: true}
result, err := db.Model(&l).
Column("is_locked").
WherePK().
Where("is_locked = ?", false).
Update()
if err != nil {
return err
}
if result.RowsAffected() == 0 {
return ErrAlreadyLocked
}
return nil
}
func releaseLock(db orm.DB) error {
l := lock{ID: lockID, IsLocked: false}
return db.Update(&l)
}
func getLastBatchNumber(db orm.DB) (int32, error) {
var res struct{ Batch int32 }
err := db.Model(&migration{}).
ColumnExpr("COALESCE(MAX(batch), 0) AS batch").
Select(&res)
if err != nil {
return 0, err
}
return res.Batch, nil
}