0 Star 0 Fork 0

shallot / Go开发工具集

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
Clone or Download
transaction.go 711 Bytes
Copy Edit Raw Blame History
package dbtool
import (
"database/sql"
"errors"
"github.com/jinzhu/gorm"
)
// 事务实际操作函数
type TransactionFunc[T any] func(*gorm.DB) (T, error)
// GORM事务处理
func Transaction[T any](db *gorm.DB, f TransactionFunc[T]) (data T, err error) {
tx := db.Begin()
defer func() {
if r := recover(); r != nil {
err = r.(error)
tx.Rollback()
}
}()
data, err = f(tx)
if err != nil {
tx.Rollback()
return
}
tx.Commit()
return
}
// 判断是否是事务句柄
func IsTransaction(db *gorm.DB) error {
if db == nil {
return errors.New("数据库对象为空")
}
_, ok := db.CommonDB().(*sql.Tx)
if !ok {
return errors.New("数据库对象不是事务")
}
return nil
}
Go
1
https://gitee.com/gxsshallot/gotool.git
git@gitee.com:gxsshallot/gotool.git
gxsshallot
gotool
Go开发工具集
2324c52c6c14

Search

53164aa7 5694891 3bd8fe86 5694891