-
Notifications
You must be signed in to change notification settings - Fork 256
/
db.go
606 lines (494 loc) 路 12.5 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
package dbmate
import (
"database/sql"
"errors"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"time"
"github.com/amacneil/dbmate/pkg/dbutil"
)
// DefaultMigrationsDir specifies default directory to find migration files
const DefaultMigrationsDir = "./db/migrations"
// DefaultMigrationsTableName specifies default database tables to record migraitons in
const DefaultMigrationsTableName = "schema_migrations"
// DefaultSchemaFile specifies default location for schema.sql
const DefaultSchemaFile = "./db/schema.sql"
// DefaultWaitInterval specifies length of time between connection attempts
const DefaultWaitInterval = time.Second
// DefaultWaitTimeout specifies maximum time for connection attempts
const DefaultWaitTimeout = 60 * time.Second
// DB allows dbmate actions to be performed on a specified database
type DB struct {
AutoDumpSchema bool
DatabaseURL *url.URL
MigrationsDir string
MigrationsTableName string
SchemaFile string
Verbose bool
WaitBefore bool
WaitInterval time.Duration
WaitTimeout time.Duration
Log io.Writer
}
// migrationFileRegexp pattern for valid migration files
var migrationFileRegexp = regexp.MustCompile(`^\d.*\.sql$`)
// 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,
MigrationsDir: DefaultMigrationsDir,
MigrationsTableName: DefaultMigrationsTableName,
SchemaFile: DefaultSchemaFile,
WaitBefore: false,
WaitInterval: DefaultWaitInterval,
WaitTimeout: DefaultWaitTimeout,
Log: os.Stdout,
}
}
// GetDriver initializes the appropriate database driver
func (db *DB) GetDriver() (Driver, error) {
if db.DatabaseURL == nil || db.DatabaseURL.Scheme == "" {
return nil, errors.New("invalid url, have you set your --url flag or DATABASE_URL environment variable?")
}
driverFunc := drivers[db.DatabaseURL.Scheme]
if driverFunc == nil {
return nil, fmt.Errorf("unsupported driver: %s", db.DatabaseURL.Scheme)
}
config := DriverConfig{
DatabaseURL: db.DatabaseURL,
MigrationsTableName: db.MigrationsTableName,
Log: db.Log,
}
return driverFunc(config), nil
}
// 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.GetDriver()
if err != nil {
return err
}
return db.wait(drv)
}
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("unable to connect to database: %s", err)
}
// CreateAndMigrate creates the database (if necessary) and runs migrations
func (db *DB) CreateAndMigrate() error {
drv, err := db.GetDriver()
if err != nil {
return err
}
if db.WaitBefore {
err := db.wait(drv)
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(drv)
}
// Create creates the current database
func (db *DB) Create() error {
drv, err := db.GetDriver()
if err != nil {
return err
}
if db.WaitBefore {
err := db.wait(drv)
if err != nil {
return err
}
}
return drv.CreateDatabase()
}
// Drop drops the current database (if it exists)
func (db *DB) Drop() error {
drv, err := db.GetDriver()
if err != nil {
return err
}
if db.WaitBefore {
err := db.wait(drv)
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.GetDriver()
if err != nil {
return err
}
return db.dumpSchema(drv)
}
func (db *DB) dumpSchema(drv Driver) error {
if db.WaitBefore {
err := db.wait(drv)
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 ioutil.WriteFile(db.SchemaFile, schema, 0644)
}
// ensureDir creates a directory if it does not already exist
func ensureDir(dir string) error {
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("unable to create directory `%s`", 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 fmt.Errorf("please specify a name for the new migration")
}
name = fmt.Sprintf("%s_%s.sql", timestamp, name)
// create migrations dir if missing
if err := ensureDir(db.MigrationsDir); err != nil {
return err
}
// check file does not already exist
path := filepath.Join(db.MigrationsDir, name)
fmt.Fprintf(db.Log, "Creating migration: %s\n", path)
if _, err := os.Stat(path); !os.IsNotExist(err) {
return fmt.Errorf("file already exists")
}
// 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.GetDriver()
if err != nil {
return err
}
return db.migrate(drv)
}
func (db *DB) migrate(drv Driver) error {
files, err := findMigrationFiles(db.MigrationsDir, migrationFileRegexp)
if err != nil {
return err
}
if len(files) == 0 {
return fmt.Errorf("no migration files found")
}
if db.WaitBefore {
err := db.wait(drv)
if err != nil {
return err
}
}
sqlDB, err := db.openDatabaseForMigration(drv)
if err != nil {
return err
}
defer dbutil.MustClose(sqlDB)
applied, err := drv.SelectMigrations(sqlDB, -1)
if err != nil {
return err
}
for _, filename := range files {
ver := migrationVersion(filename)
if ok := applied[ver]; ok {
// migration already applied
continue
}
fmt.Fprintf(db.Log, "Applying: %s\n", filename)
up, _, err := parseMigration(filepath.Join(db.MigrationsDir, filename))
if err != nil {
return err
}
execMigration := func(tx dbutil.Transaction) error {
// run actual migration
result, err := tx.Exec(up.Contents)
if err != nil {
return err
} else if db.Verbose {
db.printVerbose(result)
}
// record migration
return drv.InsertMigration(tx, ver)
}
if up.Options.Transaction() {
// begin transaction
err = doTransaction(sqlDB, execMigration)
} else {
// run outside of transaction
err = execMigration(sqlDB)
}
if err != nil {
return err
}
}
// automatically update schema file, silence errors
if db.AutoDumpSchema {
_ = db.dumpSchema(drv)
}
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 findMigrationFiles(dir string, re *regexp.Regexp) ([]string, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("could not find migrations directory `%s`", dir)
}
matches := []string{}
for _, file := range files {
if file.IsDir() {
continue
}
name := file.Name()
if !re.MatchString(name) {
continue
}
matches = append(matches, name)
}
sort.Strings(matches)
return matches, nil
}
func findMigrationFile(dir string, ver string) (string, error) {
if ver == "" {
panic("migration version is required")
}
ver = regexp.QuoteMeta(ver)
re := regexp.MustCompile(fmt.Sprintf(`^%s.*\.sql$`, ver))
files, err := findMigrationFiles(dir, re)
if err != nil {
return "", err
}
if len(files) == 0 {
return "", fmt.Errorf("can't find migration file: %s*.sql", ver)
}
return files[0], nil
}
func migrationVersion(filename string) string {
return regexp.MustCompile(`^\d+`).FindString(filename)
}
// Rollback rolls back the most recent migration
func (db *DB) Rollback() error {
drv, err := db.GetDriver()
if err != nil {
return err
}
if db.WaitBefore {
err := db.wait(drv)
if err != nil {
return err
}
}
sqlDB, err := db.openDatabaseForMigration(drv)
if err != nil {
return err
}
defer dbutil.MustClose(sqlDB)
applied, err := drv.SelectMigrations(sqlDB, 1)
if err != nil {
return err
}
// grab most recent applied migration (applied has len=1)
latest := ""
for ver := range applied {
latest = ver
}
if latest == "" {
return fmt.Errorf("can't rollback: no migrations have been applied")
}
filename, err := findMigrationFile(db.MigrationsDir, latest)
if err != nil {
return err
}
fmt.Fprintf(db.Log, "Rolling back: %s\n", filename)
_, down, err := parseMigration(filepath.Join(db.MigrationsDir, filename))
if err != nil {
return err
}
execMigration := func(tx dbutil.Transaction) error {
// rollback migration
result, err := tx.Exec(down.Contents)
if err != nil {
return err
} else if db.Verbose {
db.printVerbose(result)
}
// remove migration record
return drv.DeleteMigration(tx, latest)
}
if down.Options.Transaction() {
// begin transaction
err = doTransaction(sqlDB, execMigration)
} else {
// run outside of transaction
err = execMigration(sqlDB)
}
if err != nil {
return err
}
// automatically update schema file, silence errors
if db.AutoDumpSchema {
_ = db.dumpSchema(drv)
}
return nil
}
// Status shows the status of all migrations
func (db *DB) Status(quiet bool) (int, error) {
drv, err := db.GetDriver()
if err != nil {
return -1, err
}
results, err := db.CheckMigrationsStatus(drv)
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
}
// CheckMigrationsStatus returns the status of all available mgirations
func (db *DB) CheckMigrationsStatus(drv Driver) ([]StatusResult, error) {
files, err := findMigrationFiles(db.MigrationsDir, migrationFileRegexp)
if err != nil {
return nil, err
}
if len(files) == 0 {
return nil, fmt.Errorf("no migration files found")
}
sqlDB, err := db.openDatabaseForMigration(drv)
if err != nil {
return nil, err
}
defer dbutil.MustClose(sqlDB)
applied, err := drv.SelectMigrations(sqlDB, -1)
if err != nil {
return nil, err
}
var results []StatusResult
for _, filename := range files {
ver := migrationVersion(filename)
res := StatusResult{Filename: filename}
if ok := applied[ver]; ok {
res.Applied = true
} else {
res.Applied = false
}
results = append(results, res)
}
return results, nil
}