-
Notifications
You must be signed in to change notification settings - Fork 258
/
db.go
622 lines (517 loc) · 14 KB
/
db.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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
package dbmate
import (
"database/sql"
"errors"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"time"
"github.com/amacneil/dbmate/v2/pkg/dbutil"
)
// Error codes
var (
ErrNoMigrationFiles = errors.New("no migration files found")
ErrInvalidURL = errors.New("invalid url, have you set your --url flag or DATABASE_URL environment variable?")
ErrNoRollback = errors.New("can't rollback: no migrations have been applied")
ErrCantConnect = errors.New("unable to connect to database")
ErrUnsupportedDriver = errors.New("unsupported driver")
ErrNoMigrationName = errors.New("please specify a name for the new migration")
ErrMigrationAlreadyExist = errors.New("file already exists")
ErrMigrationDirNotFound = errors.New("could not find migrations directory")
ErrMigrationNotFound = errors.New("can't find migration file")
ErrCreateDirectory = errors.New("unable to create directory")
)
// migrationFileRegexp pattern for valid migration files
var migrationFileRegexp = regexp.MustCompile(`^(\d+).*\.sql$`)
// DB allows dbmate actions to be performed on a specified database
type DB struct {
// AutoDumpSchema generates schema.sql after each action
AutoDumpSchema bool
// DatabaseURL is the database connection string
DatabaseURL *url.URL
// FS specifies the filesystem, or nil for OS filesystem
FS fs.FS
// Log is the interface to write stdout
Log io.Writer
// MigrationsDir specifies the directory or directories to find migration files
MigrationsDir []string
// MigrationsTableName specifies the database table to record migrations in
MigrationsTableName string
// SchemaFile specifies the location for schema.sql file
SchemaFile string
// Fail if migrations would be applied out of order
Strict bool
// Verbose prints the result of each statement execution
Verbose bool
// WaitBefore will wait for database to become available before running any actions
WaitBefore bool
// WaitInterval specifies length of time between connection attempts
WaitInterval time.Duration
// WaitTimeout specifies maximum time for connection attempts
WaitTimeout time.Duration
}
// StatusResult represents an available migration status
type StatusResult struct {
Filename string
Applied bool
}
// New initializes a new dbmate database
func New(databaseURL *url.URL) *DB {
return &DB{
AutoDumpSchema: true,
DatabaseURL: databaseURL,
FS: nil,
Log: os.Stdout,
MigrationsDir: []string{"./db/migrations"},
MigrationsTableName: "schema_migrations",
SchemaFile: "./db/schema.sql",
Strict: false,
Verbose: false,
WaitBefore: false,
WaitInterval: time.Second,
WaitTimeout: 60 * time.Second,
}
}
// Driver initializes the appropriate database driver
func (db *DB) Driver() (Driver, error) {
if db.DatabaseURL == nil || db.DatabaseURL.Scheme == "" {
return nil, ErrInvalidURL
}
driverFunc := drivers[db.DatabaseURL.Scheme]
if driverFunc == nil {
return nil, fmt.Errorf("%w: %s", ErrUnsupportedDriver, db.DatabaseURL.Scheme)
}
config := DriverConfig{
DatabaseURL: db.DatabaseURL,
Log: db.Log,
MigrationsTableName: db.MigrationsTableName,
}
drv := driverFunc(config)
if db.WaitBefore {
if err := db.wait(drv); err != nil {
return nil, err
}
}
return drv, nil
}
func (db *DB) wait(drv Driver) error {
// attempt connection to database server
err := drv.Ping()
if err == nil {
// connection successful
return nil
}
fmt.Fprint(db.Log, "Waiting for database")
for i := 0 * time.Second; i < db.WaitTimeout; i += db.WaitInterval {
fmt.Fprint(db.Log, ".")
time.Sleep(db.WaitInterval)
// attempt connection to database server
err = drv.Ping()
if err == nil {
// connection successful
fmt.Fprint(db.Log, "\n")
return nil
}
}
// if we find outselves here, we could not connect within the timeout
fmt.Fprint(db.Log, "\n")
return fmt.Errorf("%w: %s", ErrCantConnect, err)
}
// Wait blocks until the database server is available. It does not verify that
// the specified database exists, only that the host is ready to accept connections.
func (db *DB) Wait() error {
drv, err := db.Driver()
if err != nil {
return err
}
// if db.WaitBefore is true, wait() will get called twice, no harm
return db.wait(drv)
}
// CreateAndMigrate creates the database (if necessary) and runs migrations
func (db *DB) CreateAndMigrate() error {
drv, err := db.Driver()
if err != nil {
return err
}
// create database if it does not already exist
// skip this step if we cannot determine status
// (e.g. user does not have list database permission)
exists, err := drv.DatabaseExists()
if err == nil && !exists {
if err := drv.CreateDatabase(); err != nil {
return err
}
}
// migrate
return db.Migrate()
}
// Create creates the current database
func (db *DB) Create() error {
drv, err := db.Driver()
if err != nil {
return err
}
return drv.CreateDatabase()
}
// Drop drops the current database (if it exists)
func (db *DB) Drop() error {
drv, err := db.Driver()
if err != nil {
return err
}
return drv.DropDatabase()
}
// DumpSchema writes the current database schema to a file
func (db *DB) DumpSchema() error {
drv, err := db.Driver()
if err != nil {
return err
}
sqlDB, err := db.openDatabaseForMigration(drv)
if err != nil {
return err
}
defer dbutil.MustClose(sqlDB)
schema, err := drv.DumpSchema(sqlDB)
if err != nil {
return err
}
fmt.Fprintf(db.Log, "Writing: %s\n", db.SchemaFile)
// ensure schema directory exists
if err = ensureDir(filepath.Dir(db.SchemaFile)); err != nil {
return err
}
// write schema to file
return os.WriteFile(db.SchemaFile, schema, 0o644)
}
// LoadSchema loads schema file to the current database
func (db *DB) LoadSchema() error {
drv, err := db.Driver()
if err != nil {
return err
}
sqlDB, err := drv.Open()
if err != nil {
return err
}
defer dbutil.MustClose(sqlDB)
_, err = os.Stat(db.SchemaFile)
if err != nil {
return err
}
fmt.Fprintf(db.Log, "Reading: %s\n", db.SchemaFile)
bytes, err := os.ReadFile(db.SchemaFile)
if err != nil {
return err
}
result, err := sqlDB.Exec(string(bytes))
if err != nil {
return err
} else if db.Verbose {
db.printVerbose(result)
}
return nil
}
// ensureDir creates a directory if it does not already exist
func ensureDir(dir string) error {
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("%w `%s`", ErrCreateDirectory, dir)
}
return nil
}
const migrationTemplate = "-- migrate:up\n\n\n-- migrate:down\n\n"
// NewMigration creates a new migration file
func (db *DB) NewMigration(name string) error {
// new migration name
timestamp := time.Now().UTC().Format("20060102150405")
if name == "" {
return ErrNoMigrationName
}
name = fmt.Sprintf("%s_%s.sql", timestamp, name)
// create migrations dir if missing
if err := ensureDir(db.MigrationsDir[0]); err != nil {
return err
}
// check file does not already exist
path := filepath.Join(db.MigrationsDir[0], name)
fmt.Fprintf(db.Log, "Creating migration: %s\n", path)
if _, err := os.Stat(path); !os.IsNotExist(err) {
return ErrMigrationAlreadyExist
}
// write new migration
file, err := os.Create(path)
if err != nil {
return err
}
defer dbutil.MustClose(file)
_, err = file.WriteString(migrationTemplate)
return err
}
func doTransaction(sqlDB *sql.DB, txFunc func(dbutil.Transaction) error) error {
tx, err := sqlDB.Begin()
if err != nil {
return err
}
if err := txFunc(tx); err != nil {
if err1 := tx.Rollback(); err1 != nil {
return err1
}
return err
}
return tx.Commit()
}
func (db *DB) openDatabaseForMigration(drv Driver) (*sql.DB, error) {
sqlDB, err := drv.Open()
if err != nil {
return nil, err
}
if err := drv.CreateMigrationsTable(sqlDB); err != nil {
dbutil.MustClose(sqlDB)
return nil, err
}
return sqlDB, nil
}
// Migrate migrates database to the latest version
func (db *DB) Migrate() error {
drv, err := db.Driver()
if err != nil {
return err
}
migrations, err := db.FindMigrations()
if err != nil {
return err
}
if len(migrations) == 0 {
return ErrNoMigrationFiles
}
highestAppliedMigrationVersion := ""
pendingMigrations := []Migration{}
for _, migration := range migrations {
if migration.Applied {
if db.Strict && highestAppliedMigrationVersion <= migration.Version {
highestAppliedMigrationVersion = migration.Version
}
} else {
pendingMigrations = append(pendingMigrations, migration)
}
}
if len(pendingMigrations) > 0 && db.Strict && pendingMigrations[0].Version <= highestAppliedMigrationVersion {
return fmt.Errorf(
"migration `%s` is out of order with already applied migrations, the version number has to be higher than the applied migration `%s` in --strict mode",
pendingMigrations[0].Version,
highestAppliedMigrationVersion,
)
}
sqlDB, err := db.openDatabaseForMigration(drv)
if err != nil {
return err
}
defer dbutil.MustClose(sqlDB)
for _, migration := range pendingMigrations {
fmt.Fprintf(db.Log, "Applying: %s\n", migration.FileName)
start := time.Now()
parsed, err := migration.Parse()
if err != nil {
return err
}
execMigration := func(tx dbutil.Transaction) error {
// run actual migration
result, err := tx.Exec(parsed.Up)
if err != nil {
return drv.QueryError(parsed.Up, err)
} else if db.Verbose {
db.printVerbose(result)
}
// record migration
return drv.InsertMigration(tx, migration.Version)
}
if parsed.UpOptions.Transaction() {
// begin transaction
err = doTransaction(sqlDB, execMigration)
} else {
// run outside of transaction
err = execMigration(sqlDB)
}
elapsed := time.Since(start)
fmt.Fprintf(db.Log, "Applied: %s in %s\n", migration.FileName, elapsed)
if err != nil {
return err
}
}
// automatically update schema file, silence errors
if db.AutoDumpSchema {
_ = db.DumpSchema()
}
return nil
}
func (db *DB) printVerbose(result sql.Result) {
lastInsertID, err := result.LastInsertId()
if err == nil {
fmt.Fprintf(db.Log, "Last insert ID: %d\n", lastInsertID)
}
rowsAffected, err := result.RowsAffected()
if err == nil {
fmt.Fprintf(db.Log, "Rows affected: %d\n", rowsAffected)
}
}
func (db *DB) readMigrationsDir(dir string) ([]fs.DirEntry, error) {
path := path.Clean(dir)
// We use nil instead of os.DirFS() because DirFS cannot support both relative and absolute
// directory paths - it must be anchored at either "." or "/", which we do not know in advance.
// See: https://github.com/amacneil/dbmate/issues/403
if db.FS == nil {
return os.ReadDir(path)
}
return fs.ReadDir(db.FS, path)
}
// FindMigrations lists all available migrations
func (db *DB) FindMigrations() ([]Migration, error) {
drv, err := db.Driver()
if err != nil {
return nil, err
}
sqlDB, err := drv.Open()
if err != nil {
return nil, err
}
defer dbutil.MustClose(sqlDB)
// find applied migrations
appliedMigrations := map[string]bool{}
migrationsTableExists, err := drv.MigrationsTableExists(sqlDB)
if err != nil {
return nil, err
}
if migrationsTableExists {
appliedMigrations, err = drv.SelectMigrations(sqlDB, -1)
if err != nil {
return nil, err
}
}
migrations := []Migration{}
for _, dir := range db.MigrationsDir {
// find filesystem migrations
files, err := db.readMigrationsDir(dir)
if err != nil {
return nil, fmt.Errorf("%w `%s`", ErrMigrationDirNotFound, dir)
}
for _, file := range files {
if file.IsDir() {
continue
}
matches := migrationFileRegexp.FindStringSubmatch(file.Name())
if len(matches) < 2 {
continue
}
migration := Migration{
Applied: false,
FileName: matches[0],
FilePath: path.Join(dir, matches[0]),
FS: db.FS,
Version: matches[1],
}
if ok := appliedMigrations[migration.Version]; ok {
migration.Applied = true
}
migrations = append(migrations, migration)
}
}
sort.Slice(
migrations, func(i, j int) bool {
return migrations[i].FileName < migrations[j].FileName
},
)
return migrations, nil
}
// Rollback rolls back the most recent migration
func (db *DB) Rollback() error {
drv, err := db.Driver()
if err != nil {
return err
}
sqlDB, err := db.openDatabaseForMigration(drv)
if err != nil {
return err
}
defer dbutil.MustClose(sqlDB)
// find last applied migration
var latest *Migration
migrations, err := db.FindMigrations()
if err != nil {
return err
}
for i, migration := range migrations {
if migration.Applied {
latest = &migrations[i]
}
}
if latest == nil {
return ErrNoRollback
}
fmt.Fprintf(db.Log, "Rolling back: %s\n", latest.FileName)
start := time.Now()
parsed, err := latest.Parse()
if err != nil {
return err
}
execMigration := func(tx dbutil.Transaction) error {
// rollback migration
result, err := tx.Exec(parsed.Down)
if err != nil {
return drv.QueryError(parsed.Down, err)
} else if db.Verbose {
db.printVerbose(result)
}
// remove migration record
return drv.DeleteMigration(tx, latest.Version)
}
if parsed.DownOptions.Transaction() {
// begin transaction
err = doTransaction(sqlDB, execMigration)
} else {
// run outside of transaction
err = execMigration(sqlDB)
}
elapsed := time.Since(start)
fmt.Fprintf(db.Log, "Rolled back: %s in %s\n", latest.FileName, elapsed)
if err != nil {
return err
}
// automatically update schema file, silence errors
if db.AutoDumpSchema {
_ = db.DumpSchema()
}
return nil
}
// Status shows the status of all migrations
func (db *DB) Status(quiet bool) (int, error) {
results, err := db.FindMigrations()
if err != nil {
return -1, err
}
var totalApplied int
var line string
for _, res := range results {
if res.Applied {
line = fmt.Sprintf("[X] %s", res.FileName)
totalApplied++
} else {
line = fmt.Sprintf("[ ] %s", res.FileName)
}
if !quiet {
fmt.Fprintln(db.Log, line)
}
}
totalPending := len(results) - totalApplied
if !quiet {
fmt.Fprintln(db.Log)
fmt.Fprintf(db.Log, "Applied: %d\n", totalApplied)
fmt.Fprintf(db.Log, "Pending: %d\n", totalPending)
}
return totalPending, nil
}