代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。