Repository navigation
Expand file tree
/
Copy pathimigrate.go
More file actions
466 lines (438 loc) · 12 KB
/
Copy pathimigrate.go
File metadata and controls
466 lines (438 loc) · 12 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package imigrate
import (
"bufio"
"database/sql"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
)
// DiscardLogger is a logger that discards all output. Set IMigrator.Logger to
// this value to silence migration output.
var DiscardLogger = log.New(io.Discard, "", log.LstdFlags)
// Executor is the interface to executing SQL.
//
// Exec executes a SQL query returning a sql.Result. Use this for mutation
// queries like CREATE, INSERT, UPDATE, DELETE, etc.
//
// GetVersions returns the timestamped versions that have been migrated thus
// far. Timestamps are stored in Unix time, that is seconds since epoch, stored
// in an int64.
type Executor interface {
Exec(query string, args ...interface{}) (sql.Result, error)
GetVersions(query string, args ...interface{}) ([]int64, error)
}
// Migrator is the interface for running migrations.
//
// Create generates a new migration file prefixed with a unix timestamp.
//
// Up runs pending migrations. Use steps=-1 to run all, or steps=N to run at
// most N. If version is non-zero, only that specific version is migrated.
//
// Down reverses applied migrations. Same steps/version semantics as Up.
//
// Redo runs Down then Up with the same parameters.
//
// Rollback runs Down for the most recent migration(s).
//
// Status prints which migrations have been run and which are pending.
//
// DryRun prints the SQL that Up would execute without running it.
type Migrator interface {
Create(string) error
Up(steps int, version int64) error
Down(steps int, version int64) error
Redo(steps int, version int64) error
Rollback(steps int) error
Status() error
DryRun(steps int, version int64) error
}
// Migration represents a single migration file
type Migration struct {
Version int64
Time time.Time
Name string
Up string
Down string
}
// Valid reads and stores the UP and DOWN SQL queries, and returns true if both
// are found.
func (o *Migration) Valid(file fs.File, upKey, downKey *regexp.Regexp) (bool, error) {
upStart := false
downStart := false
reader := bufio.NewReader(file)
for {
l, err := reader.ReadString('\n')
if !upStart && upKey.MatchString(l) {
upStart = true
} else if upStart && !downStart && downKey.MatchString(l) {
downStart = true
} else if upStart && !downStart {
o.Up += l
} else if downStart {
o.Down += l
}
if err != nil {
if err == io.EOF {
return upStart && downStart, nil
}
return false, fmt.Errorf("error reading migration %s: %w", o.Name, err)
}
}
}
// IMigrator is the default migrator that satisfies the Migrator interface.
type IMigrator struct {
DB Executor
FS fs.FS
Logger *log.Logger // Logger for migration output. Defaults to log.Default().
Dirname string // The directory where migration files are read from via FS.
WriteDirname string // The directory where Create writes new migration files. Falls back to Dirname if empty.
UpKey *regexp.Regexp // The Regexp to detect the up migration SQL.
DownKey *regexp.Regexp // The Regexp to detect the down migration SQL.
TableName string // The table where migration info is stored.
VersionColumn string // The version column in the migrations table.
CreateTableSQL string // The SQL to create the migrations table.
Migrations []Migration
FileVersionRegexp *regexp.Regexp // The Regexp to detect a migration file.
TemplateUp string // The SQL to place in the UP section of a generated file.
TemplateDown string // The SQL to place in the DOWN section of a generated file.
setupDone bool
}
// NewIMigrator returns a default migrator.
func NewIMigrator(db Executor, fsys fs.FS) *IMigrator {
m := &IMigrator{
DB: db,
FS: fsys,
Logger: log.Default(),
Dirname: "migrations",
UpKey: regexp.MustCompile(`^\s*--\s*={2,}\s*UP\s*={2,}`),
DownKey: regexp.MustCompile(`^\s*--\s*={2,}\s*DOWN\s*={2,}`),
TableName: "shmig_version",
VersionColumn: "version",
FileVersionRegexp: regexp.MustCompile(`^\d+`),
TemplateUp: `
BEGIN;
COMMIT;
`,
TemplateDown: `
BEGIN;
COMMIT;`,
}
m.CreateTableSQL = fmt.Sprintf(`
CREATE TABLE IF NOT EXISTS %s (
%s INTEGER PRIMARY KEY,
migrated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
`, m.TableName, m.VersionColumn)
return m
}
func (o *IMigrator) createTable() error {
_, err := o.DB.Exec(o.CreateTableSQL)
return err
}
func (o *IMigrator) getCompletedVersions() ([]int64, error) {
return o.DB.GetVersions(fmt.Sprintf("select %s from %s order by %s", o.VersionColumn, o.TableName, o.VersionColumn))
}
func (o *IMigrator) setup() error {
if o.setupDone {
return nil
}
if err := o.createTable(); err != nil {
return err
}
o.Migrations = nil
entries, err := fs.ReadDir(o.FS, o.Dirname)
if err != nil {
return fmt.Errorf("couldn't read %s: %w", o.Dirname, err)
}
seen := make(map[int64]string)
for _, entry := range entries {
if entry.IsDir() {
continue
}
name := entry.Name()
n := o.FileVersionRegexp.FindString(name)
nn, err := strconv.ParseInt(n, 10, 64)
if err != nil {
continue
}
if prev, ok := seen[nn]; ok {
return fmt.Errorf("duplicate migration version %d: %s and %s", nn, prev, name)
}
seen[nn] = name
fpath := o.Dirname + "/" + name
f, err := o.FS.Open(fpath)
if err != nil {
return fmt.Errorf("couldn't open file %s: %w", fpath, err)
}
migration := Migration{
Version: nn,
Time: time.Unix(nn, 0),
Name: name,
}
valid, err := migration.Valid(f, o.UpKey, o.DownKey)
f.Close()
if err != nil {
return err
}
if valid {
o.Migrations = append(o.Migrations, migration)
}
}
o.setupDone = true
return nil
}
func (o *IMigrator) migrated(m Migration) (bool, error) {
versions, err := o.getCompletedVersions()
if err != nil {
return false, err
}
for _, v := range versions {
if v == m.Version {
return true, nil
}
}
return false, nil
}
// Up runs all migrations that have not been run. If steps is greater than -1,
// it will run that many migrations in ascending order. If version is greater
// than 0, it will migrate up that specific version.
func (o *IMigrator) Up(steps int, version int64) error {
if err := o.setup(); err != nil {
return err
}
if version != 0 {
return o.upVersion(version)
}
o.sortAscending()
completed := 0
for _, m := range o.Migrations {
if completed == steps {
break
}
migrated, err := o.migrated(m)
if err != nil {
return err
}
if !migrated {
if err := o.execUp(m); err != nil {
return err
}
completed++
}
}
return nil
}
func (o *IMigrator) execUp(m Migration) error {
upSQL := strings.TrimSpace(m.Up)
_, err := o.DB.Exec(upSQL)
if err != nil {
return fmt.Errorf("migration err %d: %w", m.Version, err)
}
o.Logger.Printf("Up completed %d\n", m.Version)
_, err = o.DB.Exec(fmt.Sprintf("INSERT INTO %s (%s) VALUES(?)", o.TableName, o.VersionColumn), m.Version)
if err != nil {
return fmt.Errorf("could not record UP migration %d: %w", m.Version, err)
}
return nil
}
func (o *IMigrator) upVersion(version int64) error {
for _, m := range o.Migrations {
if m.Version == version {
migrated, err := o.migrated(m)
if err != nil {
return err
}
if !migrated {
return o.execUp(m)
}
return nil
}
}
return fmt.Errorf("migration version %d not found", version)
}
// Down runs all migrations in descending order.
// If steps is greater than -1, it will step down that many migrations.
// If version is greater than 0, it will only migrate down that specific
// version.
func (o *IMigrator) Down(steps int, version int64) error {
if err := o.setup(); err != nil {
return err
}
if version != 0 {
return o.downVersion(version)
}
o.sortDescending()
completed := 0
for _, m := range o.Migrations {
if completed == steps {
break
}
migrated, err := o.migrated(m)
if err != nil {
return err
}
if migrated {
if err := o.execDown(m); err != nil {
return err
}
completed++
}
}
return nil
}
func (o *IMigrator) execDown(m Migration) error {
dnSQL := strings.TrimSpace(m.Down)
_, err := o.DB.Exec(dnSQL)
if err != nil {
return fmt.Errorf("migration err %d: %w", m.Version, err)
}
o.Logger.Printf("Down completed %d\n", m.Version)
_, err = o.DB.Exec(fmt.Sprintf("DELETE FROM %s WHERE %s = ?", o.TableName, o.VersionColumn), m.Version)
if err != nil {
return fmt.Errorf("could not record DOWN migration %d: %w", m.Version, err)
}
return nil
}
func (o *IMigrator) downVersion(version int64) error {
for _, m := range o.Migrations {
if m.Version == version {
migrated, err := o.migrated(m)
if err != nil {
return err
}
if migrated {
return o.execDown(m)
}
return nil
}
}
return fmt.Errorf("migration version %d not found", version)
}
// Redo runs Down, then Up
func (o *IMigrator) Redo(steps int, version int64) error {
if err := o.Down(steps, version); err != nil {
return err
}
return o.Up(steps, version)
}
// Rollback runs the down SQL for the most recent migration.
// If steps is greater than 1, it will run that many migrations down.
func (o *IMigrator) Rollback(steps int) error {
return o.Down(steps, 0)
}
// Status prints out which migrations have been run and which are pending.
func (o *IMigrator) Status() error {
o.Logger.Println("STATUS")
if err := o.setup(); err != nil {
return err
}
versions, err := o.getCompletedVersions()
if err != nil {
return err
}
completed := make(map[int64]struct{}, len(versions))
for _, v := range versions {
completed[v] = struct{}{}
o.Logger.Println("Migration Completed", v)
}
o.sortAscending()
for _, m := range o.Migrations {
if _, ok := completed[m.Version]; !ok {
o.Logger.Println("Pending", m.Version)
}
}
return nil
}
// DryRun prints the SQL that would be executed by Up without running it.
// It respects the same steps and version parameters as Up.
func (o *IMigrator) DryRun(steps int, version int64) error {
if err := o.setup(); err != nil {
return err
}
o.sortAscending()
completed := 0
for _, m := range o.Migrations {
if completed == steps {
break
}
if version != 0 && m.Version != version {
continue
}
migrated, err := o.migrated(m)
if err != nil {
return err
}
if !migrated {
upSQL := strings.TrimSpace(m.Up)
o.Logger.Printf("-- Migration %d (%s)\n%s\n\n", m.Version, m.Name, upSQL)
completed++
if version != 0 {
break
}
}
}
if completed == 0 {
o.Logger.Println("-- No pending migrations")
}
return nil
}
func (o *IMigrator) sortAscending() {
sort.Slice(o.Migrations, func(i, j int) bool { return o.Migrations[i].Version < o.Migrations[j].Version })
}
func (o *IMigrator) sortDescending() {
sort.Slice(o.Migrations, func(i, j int) bool { return o.Migrations[i].Version > o.Migrations[j].Version })
}
// Create generates a new migration file in WriteDirname (or Dirname if
// WriteDirname is empty). The file is prefixed with the current time as a unix
// timestamp, followed by the provided name. It returns an error if the name is
// empty or contains path separators.
func (o *IMigrator) Create(name string) error {
if name == "" {
return fmt.Errorf("migration name is required")
}
if strings.ContainsAny(name, "/\\") {
return fmt.Errorf("migration name must not contain path separators: %s", name)
}
dir := o.WriteDirname
if dir == "" {
dir = o.Dirname
}
err := os.MkdirAll(dir, 0o755)
if err != nil {
return err
}
now := time.Now()
fname := fmt.Sprintf("%d-%s.sql", now.Unix(), name)
path := filepath.Join(dir, fname)
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
template := fmt.Sprintf(`
-- Migration: %s
-- Created at: %s
-- ==== UP ====
%s
-- ==== DOWN ====
%s
`, name,
now.Format("2006-01-02 15:04:05"),
strings.TrimSpace(o.TemplateUp),
strings.TrimSpace(o.TemplateDown),
)
_, err = f.WriteString(strings.TrimSpace(template))
if err != nil {
return err
}
o.Logger.Println("Created", path)
return nil
}