Skip to content

Commit

Permalink
feat: recover and rollback on panic during transaction (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
keroxp authored May 10, 2020
1 parent 8b5dcb0 commit 677aeaf
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
12 changes: 11 additions & 1 deletion tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package exql
import (
"context"
"database/sql"
"fmt"
)

type Tx interface {
Expand Down Expand Up @@ -51,7 +52,16 @@ func transaction(db *sql.DB, ctx context.Context, opts *sql.TxOptions, callback
return err
}
tx := &tx{tx: sqlTx, s: NewSaver(sqlTx), m: NewMapper()}
txErr := callback(tx)
var p interface{}
txErr := func() error {
defer func() {
p = recover()
}()
return callback(tx)
}()
if p != nil {
txErr = fmt.Errorf("recovered: %s", p)
}
if txErr != nil {
if err := sqlTx.Rollback(); err != nil {
return err
Expand Down
17 changes: 17 additions & 0 deletions tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,23 @@ func TestTx_Transaction(t *testing.T) {
err = db.Map(rows, &dest)
assert.Error(t, err, ErrRecordNotFound.Error())
})
t.Run("should rollback if panic happened during transaction", func(t *testing.T) {
var user *model.Users
err := transaction(db.DB(), context.Background(), nil, func(tx Tx) error {
user = &model.Users{
FirstName: null.String{},
LastName: null.String{},
}
_, err := tx.Insert(user)
assert.Nil(t, err)
panic("panic")
})
assert.EqualError(t, err, "recovered: panic")
rows, err := db.DB().Query(`select * from users where id = ?`, user.Id)
assert.Nil(t, err)
var dest model.Users
assert.Equal(t, db.Map(rows, &dest), ErrRecordNotFound)
})
}
func TestTx_Map(t *testing.T) {
db := testDb()
Expand Down

0 comments on commit 677aeaf

Please sign in to comment.