Fix return failed to begin transaction error when failed to start a transaction

This commit is contained in:
Jinzhu 2022-01-07 10:04:35 +08:00
parent 0df42e9afc
commit eae73624ad
2 changed files with 14 additions and 15 deletions

View File

@ -534,9 +534,7 @@ func (db *DB) Connection(fc func(tx *DB) error) (err error) {
defer conn.Close() defer conn.Close()
tx.Statement.ConnPool = conn tx.Statement.ConnPool = conn
err = fc(tx) return fc(tx)
return
} }
// Transaction start a transaction as a block, return error will rollback, otherwise to commit. // Transaction start a transaction as a block, return error will rollback, otherwise to commit.
@ -547,6 +545,10 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
// nested transaction // nested transaction
if !db.DisableNestedTransaction { if !db.DisableNestedTransaction {
err = db.SavePoint(fmt.Sprintf("sp%p", fc)).Error err = db.SavePoint(fmt.Sprintf("sp%p", fc)).Error
if err != nil {
return
}
defer func() { defer func() {
// Make sure to rollback when panic, Block error or Commit error // Make sure to rollback when panic, Block error or Commit error
if panicked || err != nil { if panicked || err != nil {
@ -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 { } else {
tx := db.Begin(opts...) tx := db.Begin(opts...)
if tx.Error != nil {
return tx.Error
}
defer func() { defer func() {
// Make sure to rollback when panic, Block error or Commit error // Make sure to rollback when panic, Block error or Commit error
@ -568,12 +571,9 @@ func (db *DB) Transaction(fc func(tx *DB) error, opts ...*sql.TxOptions) (err er
} }
}() }()
if err = tx.Error; err == nil { if err = fc(tx); err == nil {
err = fc(tx) panicked = false
} return tx.Commit().Error
if err == nil {
err = tx.Commit().Error
} }
} }

View File

@ -2,13 +2,13 @@ package tests_test
import ( import (
"fmt" "fmt"
"testing"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
"gorm.io/gorm" "gorm.io/gorm"
"testing"
) )
func TestWithSingleConnection(t *testing.T) { func TestWithSingleConnection(t *testing.T) {
var expectedName = "test" var expectedName = "test"
var actualName string var actualName string
@ -35,7 +35,6 @@ func TestWithSingleConnection(t *testing.T) {
if actualName != expectedName { if actualName != expectedName {
t.Errorf("WithSingleConnection() method should get correct value, expect: %v, got %v", expectedName, actualName) t.Errorf("WithSingleConnection() method should get correct value, expect: %v, got %v", expectedName, actualName)
} }
} }
func getSetSQL(driverName string) (string, string) { func getSetSQL(driverName string) (string, string) {