-
Notifications
You must be signed in to change notification settings - Fork 19
/
migrator.go
213 lines (184 loc) · 5.08 KB
/
migrator.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
package migrator
import (
"database/sql"
"errors"
"fmt"
"log"
"os"
)
const defaultTableName = "migrations"
// Migrator is the migrator implementation
type Migrator struct {
tableName string
logger Logger
migrations []interface{}
}
// Option sets options such migrations or table name.
type Option func(*Migrator)
// TableName creates an option to allow overriding the default table name
func TableName(tableName string) Option {
return func(m *Migrator) {
m.tableName = tableName
}
}
// Logger interface
type Logger interface {
Printf(string, ...interface{})
}
// LoggerFunc is a bridge between Logger and any third party logger
type LoggerFunc func(string, ...interface{})
// Printf implements Logger interface
func (f LoggerFunc) Printf(msg string, args ...interface{}) {
f(msg, args...)
}
// WithLogger creates an option to allow overriding the stdout logging
func WithLogger(logger Logger) Option {
return func(m *Migrator) {
m.logger = logger
}
}
// Migrations creates an option with provided migrations
func Migrations(migrations ...interface{}) Option {
return func(m *Migrator) {
m.migrations = migrations
}
}
// New creates a new migrator instance
func New(opts ...Option) (*Migrator, error) {
m := &Migrator{
logger: log.New(os.Stdout, "migrator: ", 0),
tableName: defaultTableName,
}
for _, opt := range opts {
opt(m)
}
if len(m.migrations) == 0 {
return nil, errors.New("migrator: migrations must be provided")
}
for _, m := range m.migrations {
switch m.(type) {
case *Migration:
case *MigrationNoTx:
default:
return nil, errors.New("migrator: invalid migration type")
}
}
return m, nil
}
// Migrate applies all available migrations
func (m *Migrator) Migrate(db *sql.DB) error {
// create migrations table if doesn't exist
_, err := db.Exec(fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
id INT8 NOT NULL,
version VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
`, m.tableName))
if err != nil {
return err
}
// count applied migrations
count, err := countApplied(db, m.tableName)
if err != nil {
return err
}
if count > len(m.migrations) {
return errors.New("migrator: applied migration number on db cannot be greater than the defined migration list")
}
// plan migrations
for idx, migration := range m.migrations[count:len(m.migrations)] {
insertVersion := fmt.Sprintf("INSERT INTO %s (id, version) VALUES (%d, '%s')", m.tableName, idx+count, migration.(fmt.Stringer).String())
switch mig := migration.(type) {
case *Migration:
if err := migrate(db, m.logger, insertVersion, mig); err != nil {
return fmt.Errorf("migrator: error while running migrations: %v", err)
}
case *MigrationNoTx:
if err := migrateNoTx(db, m.logger, insertVersion, mig); err != nil {
return fmt.Errorf("migrator: error while running migrations: %v", err)
}
}
}
return nil
}
// Pending returns all pending (not yet applied) migrations
func (m *Migrator) Pending(db *sql.DB) ([]interface{}, error) {
count, err := countApplied(db, m.tableName)
if err != nil {
return nil, err
}
return m.migrations[count:len(m.migrations)], nil
}
func countApplied(db *sql.DB, tableName string) (int, error) {
// count applied migrations
var count int
rows, err := db.Query(fmt.Sprintf("SELECT count(*) FROM %s", tableName))
if err != nil {
return 0, err
}
defer func() {
_ = rows.Close()
}()
for rows.Next() {
if err := rows.Scan(&count); err != nil {
return 0, err
}
}
if err := rows.Err(); err != nil {
return 0, err
}
return count, nil
}
// Migration represents a single migration
type Migration struct {
Name string
Func func(*sql.Tx) error
}
// String returns a string representation of the migration
func (m *Migration) String() string {
return m.Name
}
// MigrationNoTx represents a single not transactional migration
type MigrationNoTx struct {
Name string
Func func(*sql.DB) error
}
func (m *MigrationNoTx) String() string {
return m.Name
}
func migrate(db *sql.DB, logger Logger, insertVersion string, migration *Migration) error {
tx, err := db.Begin()
if err != nil {
return err
}
defer func() {
if err != nil {
if errRb := tx.Rollback(); errRb != nil {
err = fmt.Errorf("error rolling back: %s\n%s", errRb, err)
}
return
}
err = tx.Commit()
}()
logger.Printf("applying migration named '%s'...", migration.Name)
if err = migration.Func(tx); err != nil {
return fmt.Errorf("error executing golang migration: %s", err)
}
if _, err = tx.Exec(insertVersion); err != nil {
return fmt.Errorf("error updating migration versions: %s", err)
}
logger.Printf("applied migration named '%s'", migration.Name)
return err
}
func migrateNoTx(db *sql.DB, logger Logger, insertVersion string, migration *MigrationNoTx) error {
logger.Printf("applying no tx migration named '%s'...", migration.Name)
if err := migration.Func(db); err != nil {
return fmt.Errorf("error executing golang migration: %s", err)
}
if _, err := db.Exec(insertVersion); err != nil {
return fmt.Errorf("error updating migration versions: %s", err)
}
logger.Printf("applied no tx migration named '%s'", migration.Name)
return nil
}