From 1b40d6a53a4f524eb2f0fe84caa55a9eabec0aa7 Mon Sep 17 00:00:00 2001 From: John Date: Fri, 9 Oct 2020 23:42:33 +0800 Subject: [PATCH] do tx.Rollback if there's panic in gdb.Transaction --- database/gdb/gdb_core.go | 5 ++++ database/gdb/gdb_z_mysql_transaction_test.go | 28 ++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/database/gdb/gdb_core.go b/database/gdb/gdb_core.go index cbc8a4c9a..73ea066da 100644 --- a/database/gdb/gdb_core.go +++ b/database/gdb/gdb_core.go @@ -310,6 +310,11 @@ func (c *Core) Transaction(f func(tx *TX) error) (err error) { return err } defer func() { + if err == nil { + if e := recover(); e != nil { + err = fmt.Errorf("%v", e) + } + } if err != nil { if e := tx.Rollback(); e != nil { err = e diff --git a/database/gdb/gdb_z_mysql_transaction_test.go b/database/gdb/gdb_z_mysql_transaction_test.go index a76cc942a..b5c54dfdb 100644 --- a/database/gdb/gdb_z_mysql_transaction_test.go +++ b/database/gdb/gdb_z_mysql_transaction_test.go @@ -764,3 +764,31 @@ func Test_Transaction(t *testing.T) { } }) } + +func Test_Transaction_Panic(t *testing.T) { + table := createInitTable() + defer dropTable(table) + + gtest.C(t, func(t *gtest.T) { + err := db.Transaction(func(tx *gdb.TX) error { + if _, err := tx.Replace(table, g.Map{ + "id": 1, + "passport": "USER_1", + "password": "PASS_1", + "nickname": "NAME_1", + "create_time": gtime.Now().String(), + }); err != nil { + t.Error(err) + } + panic("error") + return nil + }) + t.AssertNE(err, nil) + + if value, err := db.Table(table).Fields("nickname").Where("id", 1).Value(); err != nil { + gtest.Error(err) + } else { + t.Assert(value.String(), "name_1") + } + }) +}