package contextx
import "context"
type (
transLockCtx struct{}
)
func NewTransLock(ctx context.Context) context.Context {
return context.WithValue(ctx, transLockCtx{}, true)
}
func FromTransLock(ctx context.Context) bool {
v := ctx.Value(transLockCtx{})
return v != nil && v.(bool)
}
func FindOne[T any](
ctx context.Context,
id string,
noLockFn func(ctx context.Context, id string) (*T, error),
lockFn func(ctx context.Context, id string) (*T, error),
) (*T, error) {
if FromTransLock(ctx) {
return lockFn(ctx, id)
}
return noLockFn(ctx, id)
}
type repositoryImpl struct {
q *sqlc.Queries
}
func (r repositoryImpl) FindOne(ctx context.Context, id string) (*group.Group, error) {
g, err := contextx.FindOne[sqlc.Group](ctx, id, r.q.SelectGroupById, r.q.SelectGroupForUpdate)
if err != nil {
return nil, err
}
return &group.Group{
Id: g.ID,
Name: g.Name,
}, nil
}