1 Star 1 Fork 0

csingo/cDB

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Gorm.go 2.72 KB
一键复制 编辑 原始数据 按行查看 历史
joe 提交于 2024-12-11 15:35 . update
package cDB
import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"gitee.com/csingo/cLog"
)
const (
Context_GormDBTransaction = "gorm.db.transaction"
)
func findGormClient(ctx *gin.Context, name string) *gorm.DB {
if client, _ := ctx.Get(Context_GormDBTransaction); client != nil {
return client.(*gorm.DB)
} else {
client := Client[*gorm.DB](ctx, name)
if client == nil {
cLog.SetCallerSkip(3)
defer cLog.SetCallerSkip(2)
cLog.WithContext(ctx, map[string]any{
"source": "cDB.WithContextModel",
"connection": name,
}).Panic("database connection is not exists")
}
return client
}
}
// WithContextTable 仅用于 gorm,使用table进行查询
func WithContextTable(ctx *gin.Context, model ModelInterface) *gorm.DB {
name := model.Connection(ctx)
client := findGormClient(ctx, name)
query := client.WithContext(ctx)
connector := container.GetConnector(name)
if connector == nil {
cLog.SetCallerSkip(2)
defer cLog.SetCallerSkip(1)
cLog.WithContext(ctx, map[string]any{
"source": "cDB.WithContextModel",
"connector": name,
}).Error("database connector is not exists")
return query
}
driver := connector.GetDriver()
if driver.IsDebug() {
query = query.Debug()
}
table := model.TableName()
query = query.Table(table)
return query
}
// WithContextModel 仅用于 gorm,使用model实体进行查询
func WithContextModel(ctx *gin.Context, model ModelInterface) *gorm.DB {
name := model.Connection(ctx)
client := findGormClient(ctx, name)
query := client.WithContext(ctx).Model(model)
connector := container.GetConnector(name)
if connector == nil {
cLog.SetCallerSkip(2)
defer cLog.SetCallerSkip(1)
cLog.WithContext(ctx, map[string]any{
"source": "cDB.WithContextModel",
"connector": name,
}).Error("database connector is not exists")
return query
}
driver := connector.GetDriver()
if driver.IsDebug() {
query = query.Debug()
}
table := model.TableName()
query = query.Table(table)
return query
}
func StartTransaction(ctx *gin.Context, name string, f func(ctx *gin.Context, tx *gorm.DB) error) error {
client := Client[*gorm.DB](ctx, name)
err := client.Transaction(func(tx *gorm.DB) error {
newCtx := ctx.Copy()
newCtx.Set(Context_GormDBTransaction, tx)
defer newCtx.Set(Context_GormDBTransaction, nil)
err := f(newCtx, tx)
return err
})
return err
}
func StartTransactionWithModel(ctx *gin.Context, model ModelInterface, f func(ctx *gin.Context, tx *gorm.DB) error) error {
client := Client[*gorm.DB](ctx, model.Connection(ctx))
err := client.Transaction(func(tx *gorm.DB) error {
newCtx := ctx.Copy()
newCtx.Set(Context_GormDBTransaction, tx)
defer newCtx.Set(Context_GormDBTransaction, nil)
err := f(newCtx, tx)
return err
})
return err
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/csingo/cDB.git
git@gitee.com:csingo/cDB.git
csingo
cDB
cDB
v0.4.28

搜索帮助