-
Notifications
You must be signed in to change notification settings - Fork 403
/
migrate.go
346 lines (282 loc) · 9.17 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
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
package migratex
import (
"context"
"database/sql"
"errors"
"fmt"
"hash/crc32"
"sort"
"strings"
"github.com/fnproject/fn/api/datastore/sql/dbhelper"
"github.com/jmoiron/sqlx"
"github.com/sirupsen/logrus"
)
var (
// use same migration table name as mattes/migrate, so that we don't have to
// migrate that.
// TODO doesn't have to be a glob
MigrationsTable = "schema_migrations"
ErrLocked = errors.New("database is locked")
)
func migrateErr(version int64, up bool, err error) ErrMigration {
dir := "up"
if !up {
dir = "down"
version++
}
return ErrMigration(fmt.Sprintf("error running migration. version: %v direction: %v err: %v", version, dir, err))
}
// ErrMigration represents an error running a specific migration in a specific direction
type ErrMigration string
func (e ErrMigration) Error() string { return string(e) }
func dirtyErr(version int64) ErrDirty {
return ErrDirty(fmt.Sprintf("database is dirty. version: %v", version))
}
// ErrDirty is an error that is returned when a db is dirty.
type ErrDirty string
func (e ErrDirty) Error() string { return string(e) }
const (
NilVersion = -1
)
type Migration interface {
Up(context.Context, *sqlx.Tx) error
Down(context.Context, *sqlx.Tx) error
Version() int64
}
type sorted []Migration
func (s sorted) Len() int { return len(s) }
func (s sorted) Less(i, j int) bool { return s[i].Version() < s[j].Version() }
func (s sorted) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
var _ Migration = new(MigFields)
// MigFields implements Migration and can be used for convenience.
type MigFields struct {
UpFunc func(context.Context, *sqlx.Tx) error
DownFunc func(context.Context, *sqlx.Tx) error
VersionFunc func() int64
}
func (m MigFields) Up(ctx context.Context, tx *sqlx.Tx) error { return m.UpFunc(ctx, tx) }
func (m MigFields) Down(ctx context.Context, tx *sqlx.Tx) error { return m.DownFunc(ctx, tx) }
func (m MigFields) Version() int64 { return m.VersionFunc() }
// TODO instance must have `multiStatements` set to true ?
func Up(ctx context.Context, tx *sqlx.Tx, migs []Migration) error {
return migrate(ctx, tx, migs, true)
}
func Down(ctx context.Context, tx *sqlx.Tx, migs []Migration) error {
return migrate(ctx, tx, migs, false)
}
func migrate(ctx context.Context, tx *sqlx.Tx, migs []Migration, up bool) error {
curVersion, dirty, err := Version(ctx, tx)
if dirty {
return dirtyErr(curVersion)
}
if err != nil {
return err
}
// TODO we could grab the lock here and hold it over all the migrations,
// in methodology we want each migration to run in its own tx envelope
// so that we can make as much progress as possible if we hit an error.
// not sure it makes much difference either way where we lock.
if up {
sort.Sort(sorted(migs))
} else {
sort.Sort(sort.Reverse(sorted(migs)))
}
for _, m := range migs {
// skip over migrations we have run
mVersion := m.Version()
if (up && curVersion < mVersion) || (!up && curVersion >= mVersion) {
// do each individually, for large migrations it's better to checkpoint
// than to try to do them all in one big go.
// XXX(reed): we could more gracefully handle concurrent databases trying to
// run migrations here by handling error and feeding back the version.
// get something working mode for now...
err := run(ctx, tx, m, up)
if err != nil {
return err
}
}
}
return nil
}
func withLock(ctx context.Context, tx *sqlx.Tx, f func(*sqlx.Tx) error) error {
err := lock(ctx, tx)
if err != nil {
return err
}
err = f(tx)
// NOTE: migrations happen on init and if they fail we should close our session with the db
// which will release the lock, thus, we don't need to futz with the context here to unlock.
errU := unlock(ctx, tx)
if errU != nil {
if err == nil {
err = errU
} else {
err = multiError(err, errU)
}
}
return err
}
var _ error = multiError()
// MultiError holds multiple errors. If you have to handle one of these... I am so sorry.
type MultiError struct {
Errs []error
}
func multiError(errs ...error) MultiError {
compactErrs := make([]error, 0)
for _, e := range errs {
if e != nil {
compactErrs = append(compactErrs, e)
}
}
return MultiError{compactErrs}
}
func (m MultiError) Error() string {
var strs = make([]string, 0)
for _, e := range m.Errs {
strs = append(strs, e.Error())
}
return strings.Join(strs, "\n")
}
func run(ctx context.Context, tx *sqlx.Tx, m Migration, up bool) error {
return withLock(ctx, tx, func(tx *sqlx.Tx) error {
// within the transaction, we need to check the version and ensure this
// migration has not already been applied.
curVersion, dirty, err := Version(ctx, tx)
if dirty {
return dirtyErr(curVersion)
}
// enforce monotonicity
if up && curVersion != NilVersion && m.Version() != curVersion+1 {
return fmt.Errorf("non-contiguous migration attempted up: %v != %v", m.Version(), curVersion+1)
} else if !up && m.Version() != curVersion { // down is always unraveling
return fmt.Errorf("non-contiguous migration attempted down: %v != %v", m.Version(), curVersion)
}
version := m.Version()
if !up {
version = m.Version() - 1
}
// TODO we don't need the dirty bit anymore since we're using transactions?
err = SetVersion(ctx, tx, version, true)
if up {
err = m.Up(ctx, tx)
} else {
err = m.Down(ctx, tx)
}
if err != nil {
return migrateErr(version, up, err)
}
err = SetVersion(ctx, tx, version, false)
return err
})
}
const advisoryLockIdSalt uint = 1486364155
// inspired by rails migrations, see https://goo.gl/8o9bCT
// NOTE that this means if the db server has multiple databases that use this
// library then this can cause contention... it seems a far cry.
func generateAdvisoryLockId(name string) string {
sum := crc32.ChecksumIEEE([]byte(name))
sum = sum * uint32(advisoryLockIdSalt)
return fmt.Sprintf("%v", sum)
}
func lock(ctx context.Context, tx *sqlx.Tx) error {
aid := generateAdvisoryLockId(MigrationsTable)
// pg has special locking & sqlite3 needs no locking
var query string
switch tx.DriverName() {
case "postgres", "pgx", "pq-timeouts", "cloudsqlpostgres":
query = `SELECT pg_try_advisory_lock(?)`
case "mysql", "oci8", "ora", "goracle":
query = "SELECT GET_LOCK(?, -1)"
case "sqlite3":
// sqlite3 doesn't have a lock. as long as migrate isn't called concurrently it'll be ok
return nil
default:
return fmt.Errorf("unsupported database, please add this or fix: %v", tx.DriverName())
}
query = tx.Rebind(query)
var success bool
if err := tx.QueryRowContext(ctx, query, aid).Scan(&success); err != nil {
return err
}
if success {
return nil
}
return ErrLocked
}
func unlock(ctx context.Context, tx *sqlx.Tx) error {
aid := generateAdvisoryLockId(MigrationsTable)
var query string
switch tx.DriverName() {
case "postgres", "pgx", "pq-timeouts", "cloudsqlpostgres":
query = `SELECT pg_advisory_unlock(?)`
case "mysql", "oci8", "ora", "goracle":
query = `SELECT RELEASE_LOCK(?)`
case "sqlite3":
// sqlite3 doesn't have a lock. as long as migrate isn't called concurrently it'll be ok
return nil
default:
return fmt.Errorf("unsupported database, please add this or fix: %v", tx.DriverName())
}
query = tx.Rebind(query)
_, err := tx.ExecContext(ctx, query, aid)
return err
}
func SetVersion(ctx context.Context, tx *sqlx.Tx, version int64, dirty bool) error {
err := ensureVersionTable(ctx, tx)
if err != nil {
logrus.WithError(err).Error("error ensuring version table")
return err
}
// TODO need to handle down migration better
// ideally, we have a record of each up/down migration with a timestamp for auditing,
// this just nukes the whole table which is kinda lame.
/* #nosec */
query := tx.Rebind("DELETE FROM " + MigrationsTable)
if _, err := tx.Exec(query); err != nil {
logrus.WithError(err).Error("error deleting version table")
return err
}
if version >= 0 {
/* #nosec */
query = tx.Rebind(`INSERT INTO ` + MigrationsTable + ` (version, dirty) VALUES (?, ?)`)
if _, err := tx.ExecContext(ctx, query, version, dirty); err != nil {
logrus.WithError(err).Error("error updating version table")
return err
}
}
return nil
}
func Version(ctx context.Context, tx *sqlx.Tx) (version int64, dirty bool, err error) {
helper, ok := dbhelper.GetHelper(tx.DriverName())
if !ok {
return 0, false, fmt.Errorf("no db helper registered for for %s", tx.DriverName())
}
tableExists, err := helper.CheckTableExists(tx, MigrationsTable)
if err != nil {
return 0, false, err
}
if !tableExists {
return NilVersion, false, nil
}
/* #nosec */
query := tx.Rebind(`SELECT version, dirty FROM ` + MigrationsTable + ` LIMIT 1`)
err = tx.QueryRowContext(ctx, query).Scan(&version, &dirty)
switch {
case err == sql.ErrNoRows:
return NilVersion, false, nil
case err != nil:
return 0, false, err
default:
return version, dirty, nil
}
}
func ensureVersionTable(ctx context.Context, tx *sqlx.Tx) error {
// TODO it would sure be nice to have timestamps for auditing
// TODO sqlite3 uses uint64 type? ugha, test.
query := tx.Rebind(fmt.Sprintf(`CREATE TABLE IF NOT EXISTS %v (
version bigint NOT NULL PRIMARY KEY,
dirty boolean NOT NULL
)`, MigrationsTable))
_, err := tx.ExecContext(ctx, query)
return err
}