forked from pressly/goose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reset.go
68 lines (55 loc) · 1.41 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
65
66
67
68
package goose
import (
"database/sql"
"sort"
"github.com/pkg/errors"
)
// Reset rolls back all migrations
func Reset(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 errors.Wrap(err, "failed to collect migrations")
}
if option.noVersioning {
return DownTo(db, dir, minVersion, opts...)
}
statuses, err := dbMigrationsStatus(db)
if err != nil {
return errors.Wrap(err, "failed to get status of migrations")
}
sort.Sort(sort.Reverse(migrations))
for _, migration := range migrations {
if !statuses[migration.Version] {
continue
}
if err = migration.Down(db); err != nil {
return errors.Wrap(err, "failed to db-down")
}
}
return nil
}
func dbMigrationsStatus(db *sql.DB) (map[int64]bool, error) {
rows, err := GetDialect().dbVersionQuery(db)
if err != nil {
return map[int64]bool{}, nil
}
defer rows.Close()
// The most recent record for each migration specifies
// whether it has been applied or rolled back.
result := make(map[int64]bool)
for rows.Next() {
var row MigrationRecord
if err = rows.Scan(&row.VersionID, &row.IsApplied); err != nil {
return nil, errors.Wrap(err, "failed to scan row")
}
if _, ok := result[row.VersionID]; ok {
continue
}
result[row.VersionID] = row.IsApplied
}
return result, nil
}