fix(bug): database migration does not rollback schema version on hook failure (#5908)

* add tests

* correct expect schema version

* use conventional named return

* add rollback test and more description in godoc

* refactor to use commit at the end and defer rollback

* add comment

* lint
This commit is contained in:
Sorawis Nilparuk (Bo) authored and GitHub committed 2025-07-09 10:11:30 -04:00
1 parent 8b8fb28228
commit d32245a33e
5 files changed
+67 -38

No files matched your search

@@ -202,7 +202,7 @@ func (p *Postgres) CommitRun(ctx context.Context) error {
return nil
}
// RollbackRun rolls back a transaction.
// RollbackRun rolls back a transaction. If no transaction is active, it will return nil.
func (p *Postgres) RollbackRun(ctx context.Context) error {
const op = "postgres.(Postgres).RollbackRun"
defer func() {
@@ -46,6 +46,38 @@ create table foo (
assert.Equal(t, v, 1001)
}
func TestRun_Rollback(t *testing.T) {
ctx := context.Background()
p, _, _ := setup(ctx, t)
statements := bytes.NewReader([]byte(`
create table foo (
id bigint primary key,
bar text
);
`))
err := p.StartRun(ctx)
require.NoError(t, err)
err = p.EnsureVersionTable(ctx)
require.NoError(t, err)
err = p.EnsureMigrationLogTable(ctx)
require.NoError(t, err)
err = p.Run(ctx, statements, 1001, "oss")
require.NoError(t, err)
err = p.RollbackRun(ctx)
require.NoError(t, err)
v, i, err := p.CurrentState(ctx, "oss")
require.NoError(t, err)
assert.False(t, i)
assert.Equal(t, -1, v)
}
func TestRun_NoTxn(t *testing.T) {
ctx := context.Background()
p, _, _ := setup(ctx, t)