do tx.Rollback if there's panic in gdb.Transaction

This commit is contained in:
John 2020-10-09 23:42:33 +08:00
parent f9189d48d1
commit 1b40d6a53a
2 changed files with 33 additions and 0 deletions

View File

@ -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

View File

@ -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")
}
})
}