mirror of
https://github.com/fnproject/fn.git
synced 2022-10-28 21:29:17 +03:00
migratex: return more robust errors (#873)
the error itself from up/down & dirty can be improved to show direction and version information to help a user of the package determine where things went wrong, which is useful when a series of migrations are run and the db error itself is not clear about what went wrong exactly.
This commit is contained in:
@@ -21,9 +21,30 @@ var (
|
|||||||
MigrationsTable = "schema_migrations"
|
MigrationsTable = "schema_migrations"
|
||||||
|
|
||||||
ErrLocked = errors.New("database is locked")
|
ErrLocked = errors.New("database is locked")
|
||||||
ErrDirty = errors.New("database is dirty")
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func migrateErr(version int64, up bool, err error) ErrMigration {
|
||||||
|
dir := "up"
|
||||||
|
if !up {
|
||||||
|
dir = "down"
|
||||||
|
}
|
||||||
|
return ErrMigration(fmt.Sprintf("error running migration. version: %v direction: %v err: %v", version, dir, err))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrMigration represents an error running a specific migration in a specific direction
|
||||||
|
type ErrMigration string
|
||||||
|
|
||||||
|
func (e ErrMigration) Error() string { return string(e) }
|
||||||
|
|
||||||
|
func dirtyErr(version int64) ErrDirty {
|
||||||
|
return ErrDirty(fmt.Sprintf("database is dirty. version: %v", version))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrDirty is an error that is returned when a db is dirty.
|
||||||
|
type ErrDirty string
|
||||||
|
|
||||||
|
func (e ErrDirty) Error() string { return string(e) }
|
||||||
|
|
||||||
const (
|
const (
|
||||||
NilVersion = -1
|
NilVersion = -1
|
||||||
)
|
)
|
||||||
@@ -70,7 +91,7 @@ func migrate(ctx context.Context, db *sqlx.DB, migs []Migration, up bool) error
|
|||||||
var err error
|
var err error
|
||||||
curVersion, dirty, err = Version(ctx, tx)
|
curVersion, dirty, err = Version(ctx, tx)
|
||||||
if dirty {
|
if dirty {
|
||||||
return ErrDirty
|
return dirtyErr(curVersion)
|
||||||
}
|
}
|
||||||
return err
|
return err
|
||||||
})
|
})
|
||||||
@@ -173,7 +194,7 @@ func run(ctx context.Context, db *sqlx.DB, m Migration, up bool) error {
|
|||||||
// migration has not already been applied.
|
// migration has not already been applied.
|
||||||
curVersion, dirty, err := Version(ctx, tx)
|
curVersion, dirty, err := Version(ctx, tx)
|
||||||
if dirty {
|
if dirty {
|
||||||
return ErrDirty
|
return dirtyErr(curVersion)
|
||||||
}
|
}
|
||||||
|
|
||||||
// enforce monotonicity
|
// enforce monotonicity
|
||||||
@@ -199,7 +220,7 @@ func run(ctx context.Context, db *sqlx.DB, m Migration, up bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return migrateErr(version, up, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = SetVersion(ctx, tx, version, false)
|
err = SetVersion(ctx, tx, version, false)
|
||||||
|
|||||||
Reference in New Issue
Block a user