-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmigrations.go
368 lines (317 loc) · 11.6 KB
/
migrations.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
// Package migrate provides functionality for applying database migrations.
package migrate
import (
"database/sql"
"embed"
"fmt"
"path/filepath"
"sort"
"strings"
"time"
"github.com/acronis/go-appkit/log"
migrate "github.com/rubenv/sql-migrate"
"github.com/acronis/go-dbkit"
)
// MigrationsTableName contains the name of table in a database that stores applied migrations.
const MigrationsTableName = "migrations"
// MigrationsDirection defines possible values for direction of database migrations.
type MigrationsDirection string
// Directions of database migrations.
const (
MigrationsDirectionUp MigrationsDirection = "up"
MigrationsDirectionDown MigrationsDirection = "down"
)
// MigrationsNoLimit contains a special value that will not limit the number of migrations to apply.
const MigrationsNoLimit = 0
// Migration is an interface for all database migrations.
// Migration may implement RawMigrator interface for full control.
// Migration may implement TxDisabler interface to control transactions.
type Migration interface {
ID() string
UpSQL() []string
DownSQL() []string
UpFn() func(tx *sql.Tx) error // Not supported yet.
DownFn() func(tx *sql.Tx) error // Not supported yet.
}
// RawMigrator is an interface that allows to overwrite default generate mechanism for full control on migrations.
// Uses sql-migrate migration structure.
type RawMigrator interface {
RawMigration(m Migration) (*migrate.Migration, error)
}
// TxDisabler is an interface for Migration for controlling transaction
type TxDisabler interface {
DisableTx() bool
}
// NullMigration represents an empty basic migration that may be embedded in regular migrations
// in order to write less code for satisfying the Migration interface.
type NullMigration struct {
Dialect dbkit.Dialect
}
// ID is a stub that returns empty migration identifier.
func (m *NullMigration) ID() string {
return ""
}
// UpSQL is a stub that returns an empty slice of SQL statements that implied to be executed during applying the migration.
func (m *NullMigration) UpSQL() []string {
return nil
}
// DownSQL is a stub that returns an empty slice of SQL statements that implied to be executed during rolling back the migration.
func (m *NullMigration) DownSQL() []string {
return nil
}
// UpFn is a stub that returns an empty function that implied to be called during applying the migration.
func (m *NullMigration) UpFn() func(tx *sql.Tx) error {
return nil
}
// DownFn is a stub that returns an empty function that implied to be called during rolling back the migration.
func (m *NullMigration) DownFn() func(tx *sql.Tx) error {
return nil
}
// CustomMigration represents simplified but customizable migration
type CustomMigration struct {
id string
upSQL []string
downSQL []string
upFn func(tx *sql.Tx) error
downFn func(tx *sql.Tx) error
}
// NewCustomMigration creates simplified but customizable migration.
func NewCustomMigration(id string, upSQL, downSQL []string, upFn, downFn func(tx *sql.Tx) error) *CustomMigration {
return &CustomMigration{id: id, upSQL: upSQL, downSQL: downSQL, upFn: upFn, downFn: downFn}
}
// ID returns migration identifier.
func (m *CustomMigration) ID() string {
return m.id
}
// UpSQL returns a slice of SQL statements that will be executed during applying the migration.
func (m *CustomMigration) UpSQL() []string {
return m.upSQL
}
// DownSQL returns a slice of SQL statements that will be executed during rolling back the migration.
func (m *CustomMigration) DownSQL() []string {
return m.downSQL
}
// UpFn returns a function that will be called during applying the migration
func (m *CustomMigration) UpFn() func(tx *sql.Tx) error {
return m.upFn
}
// DownFn returns a function that will be called during rolling back the migration
func (m *CustomMigration) DownFn() func(tx *sql.Tx) error {
return m.downFn
}
// MigrationsManager is an object for running migrations.
type MigrationsManager struct {
db *sql.DB
Dialect dbkit.Dialect
migSet migrate.MigrationSet
logger log.FieldLogger
}
// MigrationsManagerOpts holds the Migration Manager options to be used in NewMigrationsManagerWithOpts
type MigrationsManagerOpts struct {
TableName string
}
// NewMigrationsManager creates a new MigrationsManager.
func NewMigrationsManager(dbConn *sql.DB, dialect dbkit.Dialect, logger log.FieldLogger) (*MigrationsManager, error) {
migSet := migrate.MigrationSet{TableName: MigrationsTableName}
return &MigrationsManager{dbConn, normalizeDialect(dialect), migSet, logger}, nil
}
// NewMigrationsManagerWithOpts creates a new MigrationsManager with custom options
func NewMigrationsManagerWithOpts(
dbConn *sql.DB,
dialect dbkit.Dialect,
logger log.FieldLogger,
opts MigrationsManagerOpts,
) (*MigrationsManager, error) {
tableName := opts.TableName
if tableName == "" {
tableName = MigrationsTableName
}
migSet := migrate.MigrationSet{TableName: tableName}
return &MigrationsManager{dbConn, normalizeDialect(dialect), migSet, logger}, nil
}
// TODO: normalizeDialect sets standard lib/pq driver for pgx dialect because pgx isn't supported by sql-migrate yet.
func normalizeDialect(dialect dbkit.Dialect) dbkit.Dialect {
if dialect == dbkit.DialectPgx {
return dbkit.DialectPostgres
}
return dialect
}
// Run runs all passed migrations.
func (mm *MigrationsManager) Run(migrations []Migration, direction MigrationsDirection) error {
return mm.RunLimit(migrations, direction, MigrationsNoLimit)
}
// convertMigration converts migration to internal sql-migrate format.
// If migration implements RawMigrator interface, then RawMigration function is used.
// If migration implements TxDisabler interface, then it may be not in transaction.
func convertMigration(m Migration) (*migrate.Migration, error) {
if migrator, ok := m.(RawMigrator); ok {
raw, err := migrator.RawMigration(m)
if err != nil {
return nil, fmt.Errorf("preparing migration %s failed with error: %w", m.ID(), err)
}
if raw != nil {
return raw, nil
}
}
if len(m.UpSQL()) == 0 { // Check will be removed when UpFn() will be supported.
return nil, fmt.Errorf("migration %s should implement UpSQL", m.ID())
}
if (m.UpFn() == nil && len(m.UpSQL()) == 0) || (m.UpFn() != nil && len(m.UpSQL()) != 0) {
// Will be actual when UpFn() will be supported.
return nil, fmt.Errorf("migration %s should implement either UpFn or UpSQL", m.ID())
}
if m.DownFn() != nil && len(m.DownSQL()) != 0 {
// Will be actual when DownFn() will be supported.
return nil, fmt.Errorf("migration %s should implement either DownFn or DownSQL", m.ID())
}
disableTx := false
if disableTransactor, ok := m.(TxDisabler); ok {
disableTx = disableTransactor.DisableTx()
}
return &migrate.Migration{
Id: m.ID(),
Up: m.UpSQL(),
Down: m.DownSQL(),
DisableTransactionUp: disableTx,
DisableTransactionDown: disableTx,
}, nil
}
// RunLimit runs at most `limit` migrations. Pass 0 (or MigrationsNoLimit const) for no limit (or use Run).
func (mm *MigrationsManager) RunLimit(migrations []Migration, direction MigrationsDirection, limit int) error {
convertedMigrationList := make([]*migrate.Migration, 0, len(migrations))
for i, m := range migrations {
if m.ID() == "" {
return fmt.Errorf("migration #%d has empty ID", i+1)
}
convertedMigration, err := convertMigration(m)
if err != nil {
return err
}
convertedMigrationList = append(convertedMigrationList, convertedMigration)
}
source := &migrate.MemoryMigrationSource{Migrations: convertedMigrationList}
var dir migrate.MigrationDirection
switch direction {
case MigrationsDirectionUp:
dir = migrate.Up
case MigrationsDirectionDown:
dir = migrate.Down
default:
return fmt.Errorf("unknown direction %q", dir)
}
n, err := mm.migSet.ExecMax(mm.db, string(mm.Dialect), source, dir, limit)
logger := mm.logger.With(log.String("direction", string(direction)), log.Int("applied", n))
if err != nil {
logger.Error("db migration failed", log.Error(err))
return err
}
logger.Info("db migration up succeeded")
return nil
}
// Status returns the current migration status.
func (mm *MigrationsManager) Status() (MigrationStatus, error) {
var migStatus MigrationStatus
appliedMigRecords, err := mm.migSet.GetMigrationRecords(mm.db, string(mm.Dialect))
if err != nil {
return migStatus, fmt.Errorf("get applied migrations: %w", err)
}
migStatus.AppliedMigrations = make([]AppliedMigration, 0, len(appliedMigRecords))
for _, migRec := range appliedMigRecords {
migStatus.AppliedMigrations = append(migStatus.AppliedMigrations, AppliedMigration{ID: migRec.Id, AppliedAt: migRec.AppliedAt})
}
return migStatus, nil
}
// AppliedMigration represent a single already applied migration.
type AppliedMigration struct {
ID string
AppliedAt time.Time
}
// MigrationStatus is the migration status.
type MigrationStatus struct {
AppliedMigrations []AppliedMigration
}
// LastAppliedMigration returns last applied migration if it exists.
func (ms *MigrationStatus) LastAppliedMigration() (appliedMig AppliedMigration, exist bool) {
if len(ms.AppliedMigrations) == 0 {
return AppliedMigration{}, false
}
return ms.AppliedMigrations[len(ms.AppliedMigrations)-1], true
}
// LoadAllEmbedFSMigrations loads all migrations from the embed.FS directory.
func LoadAllEmbedFSMigrations(fs embed.FS, dirName string) ([]Migration, error) {
files, err := fs.ReadDir(dirName)
if err != nil {
return nil, fmt.Errorf("read migrations directory %s: %w", dirName, err)
}
migrationsMap := make(map[string][2]string)
for _, file := range files {
if file.IsDir() {
continue
}
var migrationID string
var nameIdx int
switch {
case strings.HasSuffix(file.Name(), ".up.sql"):
migrationID = strings.TrimSuffix(file.Name(), ".up.sql")
nameIdx = 0
case strings.HasSuffix(file.Name(), ".down.sql"):
migrationID = strings.TrimSuffix(file.Name(), ".down.sql")
nameIdx = 1
default:
return nil, fmt.Errorf("migration file should have .up.sql or .down.sql suffix, got %s", file.Name())
}
names := migrationsMap[migrationID]
names[nameIdx] = file.Name()
migrationsMap[migrationID] = names
}
migrations := make([]Migration, 0, len(migrationsMap))
for migrationID, names := range migrationsMap {
if names[0] == "" {
return nil, fmt.Errorf("%s migration up file is missing", migrationID)
}
if names[1] == "" {
return nil, fmt.Errorf("%s migration down file is missing", migrationID)
}
var upSQL []byte
if upSQL, err = fs.ReadFile(filepath.Join(dirName, names[0])); err != nil {
return nil, err
}
var downSQL []byte
if downSQL, err = fs.ReadFile(filepath.Join(dirName, names[1])); err != nil {
return nil, err
}
migrations = append(migrations, &CustomMigration{
id: migrationID,
upSQL: []string{string(upSQL)},
downSQL: []string{string(downSQL)},
})
}
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].ID() < migrations[j].ID()
})
return migrations, nil
}
// LoadEmbedFSMigrations loads migrations with specified IDs from the embed.FS directory.
func LoadEmbedFSMigrations(fs embed.FS, dirName string, migrationIDs []string) ([]Migration, error) {
migrations := make([]Migration, 0, len(migrationIDs))
for _, migrationID := range migrationIDs {
upSQL, err := fs.ReadFile(filepath.Join(dirName, fmt.Sprintf("%s.up.sql", migrationID)))
if err != nil {
return nil, err
}
downSQL, err := fs.ReadFile(filepath.Join(dirName, fmt.Sprintf("%s.down.sql", migrationID)))
if err != nil {
return nil, err
}
migrations = append(migrations, &CustomMigration{
id: migrationID,
upSQL: []string{string(upSQL)},
downSQL: []string{string(downSQL)},
})
}
return migrations, nil
}