update: gorm session config

This commit is contained in:
zhaoyupeng 2025-06-17 14:14:39 +08:00
parent b3fdecd62f
commit 7dd48c0c50

View File

@ -5,8 +5,13 @@ import (
"gorm.io/gorm"
)
type Config struct {
Debug bool
DryRun bool
}
type DB interface {
Session(ctx context.Context) *gorm.DB
Session(ctx context.Context, configs ...Config) *gorm.DB
}
type db struct {
@ -17,6 +22,28 @@ var (
Default DB
)
func (db *db) Session(ctx context.Context) *gorm.DB {
return db.tx.Session(&gorm.Session{Context: ctx})
func (db *db) Session(ctx context.Context, configs ...Config) *gorm.DB {
var (
sc = &gorm.Session{Context: ctx}
session *gorm.DB
)
if len(configs) == 0 {
session = db.tx.Session(sc)
return session
}
cfg := configs[0]
if cfg.DryRun {
sc.DryRun = true
}
session = db.tx.Session(sc)
if cfg.Debug {
session = session.Debug()
}
return session
}