Ai
1 Star 0 Fork 0

go-libs/db-xorm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
transaction.go 2.19 KB
一键复制 编辑 原始数据 按行查看 历史
非一般 提交于 2025-05-08 00:32 +08:00 . fix: transaction for auto commit
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-08-01
package src
import (
"context"
"fmt"
"gitee.com/go-libs/log"
)
type (
TransactionHandler func(ctx context.Context, session *Session) error
)
func Transaction(ctx context.Context, handlers ...TransactionHandler) (err error) {
var session *Session
// Creates
// a master connect session.
if session, err = Config.GetMaster(ctx); err != nil {
return
}
// Close
// session when done.
defer func() {
if se := session.Close(); se != nil {
log.Infofc(ctx, `transaction session close error: %v`, se)
}
}()
// Schedule to executor with a master session.
err = TransactionWithSession(ctx, session, handlers...)
return
}
func TransactionWithSession(ctx context.Context, session *Session, handlers ...TransactionHandler) (err error) {
// Close auto commit.
if _, err = session.Exec("SET AUTOCOMMIT = 0"); err != nil {
return
}
// Open transaction.
if err = session.Begin(); err != nil {
return
}
// Executed when process done.
defer func() {
// Catch
// runtime panic and recover it.
if r := recover(); r != nil {
log.Fatalfc(ctx, `transaction panic: %v`, r)
err = fmt.Errorf(`r`)
}
// End transaction with rollback or commit.
if err != nil {
if se := session.Rollback(); se != nil {
log.Errorfc(ctx, "transaction rollback error: %v", se)
}
} else {
if se := session.Commit(); se != nil {
log.Errorfc(ctx, "transaction commit error: %v", se)
}
}
// Reopen auto commit.
_, _ = session.Exec("SET AUTOCOMMIT = 1")
}()
// Range handlers.
for _, handler := range handlers {
if err = handler(ctx, session); err != nil {
break
}
}
return
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/go-libs/db-xorm.git
git@gitee.com:go-libs/db-xorm.git
go-libs
db-xorm
db-xorm
v1.2.6

搜索帮助