2018-04-30 18:42:17 +05:00
|
|
|
package goose
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"sort"
|
2019-10-13 13:55:38 +05:00
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
2018-04-30 18:42:17 +05:00
|
|
|
)
|
|
|
|
|
|
|
|
// Reset rolls back all migrations
|
|
|
|
func Reset(db *sql.DB, dir string) error {
|
|
|
|
migrations, err := CollectMigrations(dir, minVersion, maxVersion)
|
|
|
|
if err != nil {
|
2019-10-13 13:55:38 +05:00
|
|
|
return errors.Wrap(err, "failed to collect migrations")
|
2018-04-30 18:42:17 +05:00
|
|
|
}
|
|
|
|
statuses, err := dbMigrationsStatus(db)
|
|
|
|
if err != nil {
|
2019-10-13 13:55:38 +05:00
|
|
|
return errors.Wrap(err, "failed to get status of migrations")
|
2018-04-30 18:42:17 +05:00
|
|
|
}
|
|
|
|
sort.Sort(sort.Reverse(migrations))
|
|
|
|
|
|
|
|
for _, migration := range migrations {
|
|
|
|
if !statuses[migration.Version] {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err = migration.Down(db); err != nil {
|
2019-10-13 13:55:38 +05:00
|
|
|
return errors.Wrap(err, "failed to db-down")
|
2018-04-30 18:42:17 +05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func dbMigrationsStatus(db *sql.DB) (map[int64]bool, error) {
|
|
|
|
rows, err := GetDialect().dbVersionQuery(db)
|
|
|
|
if err != nil {
|
2019-10-13 13:55:38 +05:00
|
|
|
return map[int64]bool{}, nil
|
2018-04-30 18:42:17 +05:00
|
|
|
}
|
|
|
|
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 {
|
2019-10-13 13:55:38 +05:00
|
|
|
return nil, errors.Wrap(err, "failed to scan row")
|
2018-04-30 18:42:17 +05:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, ok := result[row.VersionID]; ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
result[row.VersionID] = row.IsApplied
|
|
|
|
}
|
|
|
|
|
|
|
|
return result, nil
|
|
|
|
}
|