50 lines
610 B
Go
50 lines
610 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Config struct {
|
|
Debug bool
|
|
DryRun bool
|
|
}
|
|
|
|
type DB interface {
|
|
Session(ctx context.Context, configs ...Config) *gorm.DB
|
|
}
|
|
|
|
type db struct {
|
|
tx *gorm.DB
|
|
}
|
|
|
|
var (
|
|
Default DB
|
|
)
|
|
|
|
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
|
|
}
|