forked from gsamokovarov/gloat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
executor.go
76 lines (61 loc) · 1.66 KB
/
executor.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 gloat
import (
"fmt"
)
// IrreversibleError is the error return when we're trying to reverse a
// migration that has a blank down SQL content.
type IrreversibleError struct {
Version int64
}
// Error implements the error interface.
func (err IrreversibleError) Error() string {
return fmt.Sprintf("cannot reverse migration %d", err.Version)
}
// Executor is a type that executes migrations up and down.
type Executor interface {
Up(*Migration, Store) error
Down(*Migration, Store) error
}
// SQLExecutor is a type that executes migrations in a database.
type SQLExecutor struct {
db SQLTransactor
}
// Up applies a migration.
func (e *SQLExecutor) Up(migration *Migration, store Store) error {
return e.exec(migration.Options.Transaction, func(tx SQLExecer) error {
if _, err := tx.Exec(string(migration.UpSQL)); err != nil {
return err
}
return store.Insert(migration, tx)
})
}
// Down reverses a migrations.
func (e *SQLExecutor) Down(migration *Migration, store Store) error {
if !migration.Reversible() {
return IrreversibleError{migration.Version}
}
return e.exec(migration.Options.Transaction, func(tx SQLExecer) error {
if _, err := tx.Exec(string(migration.DownSQL)); err != nil {
return err
}
return store.Remove(migration, tx)
})
}
func (e *SQLExecutor) exec(transaction bool, action func(SQLExecer) error) error {
if !transaction {
return action(e.db)
}
tx, err := e.db.Begin()
if err != nil {
return err
}
if err := action(tx); err != nil {
defer tx.Rollback()
return err
}
return tx.Commit()
}
// NewSQLExecutor creates an SQLExecutor.
func NewSQLExecutor(db SQLTransactor) Executor {
return &SQLExecutor{db: db}
}