-
Notifications
You must be signed in to change notification settings - Fork 525
/
reset.go
64 lines (56 loc) · 1.51 KB
/
reset.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
package goose
import (
"context"
"database/sql"
"fmt"
"sort"
)
// Reset rolls back all migrations
func Reset(db *sql.DB, dir string, opts ...OptionsFunc) error {
ctx := context.Background()
return ResetContext(ctx, db, dir, opts...)
}
// ResetContext rolls back all migrations
func ResetContext(ctx context.Context, db *sql.DB, dir string, opts ...OptionsFunc) error {
option := &options{}
for _, f := range opts {
f(option)
}
migrations, err := CollectMigrations(dir, minVersion, maxVersion)
if err != nil {
return fmt.Errorf("failed to collect migrations: %w", err)
}
if option.noVersioning {
return DownToContext(ctx, db, dir, minVersion, opts...)
}
statuses, err := dbMigrationsStatus(ctx, db)
if err != nil {
return fmt.Errorf("failed to get status of migrations: %w", err)
}
sort.Sort(sort.Reverse(migrations))
for _, migration := range migrations {
if !statuses[migration.Version] {
continue
}
if err = migration.DownContext(ctx, db); err != nil {
return fmt.Errorf("failed to db-down: %w", err)
}
}
return nil
}
func dbMigrationsStatus(ctx context.Context, db *sql.DB) (map[int64]bool, error) {
dbMigrations, err := store.ListMigrations(ctx, db, TableName())
if err != nil {
return nil, err
}
// The most recent record for each migration specifies
// whether it has been applied or rolled back.
results := make(map[int64]bool)
for _, m := range dbMigrations {
if _, ok := results[m.VersionID]; ok {
continue
}
results[m.VersionID] = m.IsApplied
}
return results, nil
}