Files
mayfly-go/server/pkg/base/ctx.go
meilin.huang e56788af3e refactor: dbm
2024-12-08 13:04:23 +08:00

31 lines
530 B
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package base
import (
"context"
"gorm.io/gorm"
)
type CtxKey string
const (
DbKey CtxKey = "db"
)
// NewCtxWithDb 将事务db放置context中若已存在则直接返回ctx
func NewCtxWithDb(ctx context.Context, db *gorm.DB) context.Context {
if tx := GetDbFromCtx(ctx); tx != nil {
return ctx
}
return context.WithValue(ctx, DbKey, db)
}
// GetDbFromCtx 获取ctx中的事务db
func GetDbFromCtx(ctx context.Context) *gorm.DB {
if txdb, ok := ctx.Value(DbKey).(*gorm.DB); ok {
return txdb
}
return nil
}