Skip to content

Commit

Permalink
Fix return failed to begin transaction error when failed to start a t…
Browse files Browse the repository at this point in the history
…ransaction
  • Loading branch information
jinzhu committed Jan 7, 2022
1 parent 0df42e9 commit eae7362
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
24 changes: 12 additions & 12 deletions finisher_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -534,9 +534,7 @@ func (db *DB) Connection(fc func(tx *DB) error) (err error) {

defer conn.Close()
tx.Statement.ConnPool = conn
err = fc(tx)

return
return fc(tx)
}

// Transaction start a transaction as a block, return error will rollback, otherwise to commit.
Expand All @@ -547,6 +545,10 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
// nested transaction
if !db.DisableNestedTransaction {
err = db.SavePoint(fmt.Sprintf("sp%p", fc)).Error
if err != nil {
return
}

defer func() {
// Make sure to rollback when panic, Block error or Commit error
if panicked || err != nil {
Expand All @@ -555,11 +557,12 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
}()
}

if err == nil {
err = fc(db.Session(&Session{}))
}
err = fc(db.Session(&Session{}))
} else {
tx := db.Begin(opts...)
if tx.Error != nil {
return tx.Error
}

defer func() {
// Make sure to rollback when panic, Block error or Commit error
Expand All @@ -568,12 +571,9 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
}
}()

if err = tx.Error; err == nil {
err = fc(tx)
}

if err == nil {
err = tx.Commit().Error
if err = fc(tx); err == nil {
panicked = false
return tx.Commit().Error
}
}

Expand Down
5 changes: 2 additions & 3 deletions tests/connection_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package tests_test

import (
"fmt"
"testing"

"gorm.io/driver/mysql"
"gorm.io/gorm"
"testing"
)

func TestWithSingleConnection(t *testing.T) {

var expectedName = "test"
var actualName string

Expand All @@ -35,7 +35,6 @@ func TestWithSingleConnection(t *testing.T) {
if actualName != expectedName {
t.Errorf("WithSingleConnection() method should get correct value, expect: %v, got %v", expectedName, actualName)
}

}

func getSetSQL(driverName string) (string, string) {
Expand Down

0 comments on commit eae7362

Please sign in to comment.