Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Gracefully recover Go migrations that panic #643

Merged
merged 2 commits into from
Nov 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion provider_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"io/fs"
"runtime/debug"
"sort"
"strconv"
"strings"
Expand Down Expand Up @@ -424,7 +425,13 @@ func runMigration(ctx context.Context, db database.DBTxConn, m *Migration, direc

// runGo is a helper function that runs the given Go functions in the given direction. It must only
// be called after the migration has been initialized.
func runGo(ctx context.Context, db database.DBTxConn, m *Migration, direction bool) error {
func runGo(ctx context.Context, db database.DBTxConn, m *Migration, direction bool) (retErr error) {
defer func() {
if r := recover(); r != nil {
retErr = fmt.Errorf("panic: %v\n%s", r, debug.Stack())
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default Go stack is a bit noisy, wonder if there's an opportunity here to clean this up a bit, i.e., pretty print stack.

}
}()

switch db := db.(type) {
case *sql.Conn:
return fmt.Errorf("go migrations are not supported with *sql.Conn")
Expand Down
28 changes: 28 additions & 0 deletions provider_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,34 @@ func TestSQLiteSharedCache(t *testing.T) {
})
}

func TestGoMigrationPanic(t *testing.T) {
t.Parallel()

ctx := context.Background()
const (
wantErrString = "panic: runtime error: index out of range [7] with length 0"
)
migration := goose.NewGoMigration(
1,
&goose.GoFunc{RunTx: func(ctx context.Context, tx *sql.Tx) error {
var ss []int
_ = ss[7]
return nil
}},
nil,
)
p, err := goose.NewProvider(goose.DialectSQLite3, newDB(t), nil,
goose.WithGoMigrations(migration), // Add a Go migration that panics.
)
check.NoError(t, err)
_, err = p.Up(ctx)
check.HasError(t, err)
check.Contains(t, err.Error(), wantErrString)
var expected *goose.PartialError
check.Bool(t, errors.As(err, &expected), true)
check.Contains(t, expected.Err.Error(), wantErrString)
}

func TestCustomStoreTableExists(t *testing.T) {
t.Parallel()

Expand Down