Files
mayfly-go/server/pkg/base/ctx.go

31 lines
530 B
Go
Raw Normal View History

2024-11-20 22:43:53 +08:00
package base
import (
"context"
"gorm.io/gorm"
)
type CtxKey string
const (
DbKey CtxKey = "db"
)
2024-12-08 13:04:23 +08:00
// NewCtxWithDb 将事务db放置context中若已存在则直接返回ctx
func NewCtxWithDb(ctx context.Context, db *gorm.DB) context.Context {
if tx := GetDbFromCtx(ctx); tx != nil {
return ctx
2024-11-20 22:43:53 +08:00
}
2024-12-08 13:04:23 +08:00
return context.WithValue(ctx, DbKey, db)
2024-11-20 22:43:53 +08:00
}
// GetDbFromCtx 获取ctx中的事务db
func GetDbFromCtx(ctx context.Context) *gorm.DB {
2024-12-08 13:04:23 +08:00
if txdb, ok := ctx.Value(DbKey).(*gorm.DB); ok {
return txdb
2024-11-20 22:43:53 +08:00
}
return nil
}