Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu authored Dec 5, 2019
2 parents 9827710 + b543a11 commit 9897f80
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 16 deletions.
11 changes: 4 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -528,12 +528,12 @@ func (s *DB) Debug() *DB {
// Transaction start a transaction as a block,
// return error will rollback, otherwise to commit.
func (s *DB) Transaction(fc func(tx *DB) error) (err error) {
panicked := true
tx := s.Begin()
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%s", r)
// Make sure to rollback when panic, Block error or Commit error
if panicked || err != nil {
tx.Rollback()
return
}
}()

Expand All @@ -543,10 +543,7 @@ func (s *DB) Transaction(fc func(tx *DB) error) (err error) {
err = tx.Commit().Error
}

// Makesure rollback when Block error or Commit error
if err != nil {
tx.Rollback()
}
panicked = false
return
}

Expand Down
29 changes: 20 additions & 9 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,15 @@ func TestTransaction(t *testing.T) {
}
}

func assertPanic(t *testing.T, f func()) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
f()
}

func TestTransactionWithBlock(t *testing.T) {
// rollback
err := DB.Transaction(func(tx *gorm.DB) error {
Expand Down Expand Up @@ -511,17 +520,19 @@ func TestTransactionWithBlock(t *testing.T) {
}

// panic will rollback
DB.Transaction(func(tx *gorm.DB) error {
u3 := User{Name: "transcation-3"}
if err := tx.Save(&u3).Error; err != nil {
t.Errorf("No error should raise")
}
assertPanic(t, func() {
DB.Transaction(func(tx *gorm.DB) error {
u3 := User{Name: "transcation-3"}
if err := tx.Save(&u3).Error; err != nil {
t.Errorf("No error should raise")
}

if err := tx.First(&User{}, "name = ?", "transcation-3").Error; err != nil {
t.Errorf("Should find saved record")
}
if err := tx.First(&User{}, "name = ?", "transcation-3").Error; err != nil {
t.Errorf("Should find saved record")
}

panic("force panic")
panic("force panic")
})
})

if err := DB.First(&User{}, "name = ?", "transcation").Error; err == nil {
Expand Down

0 comments on commit 9897f80

Please sign in to comment.