-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
46 lines (37 loc) · 995 Bytes
/
context.go
File metadata and controls
46 lines (37 loc) · 995 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package bunquery
import (
"context"
"errors"
"github.com/uptrace/bun"
)
type dbCtxKey struct{}
type dbCtx struct {
db bun.IDB
mods QueryMods
}
var ErrNoContext = errors.New("no db context")
func getDbCtx(ctx context.Context) (*dbCtx, bool) {
qctx, ok := ctx.Value(dbCtxKey{}).(*dbCtx)
return qctx, ok
}
func createDbCtx(ctx context.Context, db bun.IDB, bindings QueryMods) context.Context {
return context.WithValue(ctx, dbCtxKey{}, &dbCtx{
db: db,
mods: bindings,
})
}
func NewContext(ctx context.Context, db bun.IDB, mods ...QueryMod) context.Context {
return createDbCtx(ctx, db, mods)
}
func UseContextMods(ctx context.Context, mods ...QueryMod) (context.Context, error) {
if dbCtx, ok := getDbCtx(ctx); ok {
return createDbCtx(ctx, dbCtx.db, mods), nil
}
return ctx, ErrNoContext
}
func FromContext(ctx context.Context) (bun.IDB, QueryMods, error) {
if dbCtx, ok := getDbCtx(ctx); ok {
return dbCtx.db, dbCtx.mods, nil
}
return nil, nil, ErrNoContext
}