-
Notifications
You must be signed in to change notification settings - Fork 14
/
context.go
48 lines (37 loc) · 1.17 KB
/
context.go
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
47
48
package sql
import (
"context"
"database/sql"
"github.com/avito-tech/go-transaction-manager/trm/v2"
trmcontext "github.com/avito-tech/go-transaction-manager/trm/v2/context"
)
// DefaultCtxGetter is the CtxGetter with settings.DefaultCtxKey.
var DefaultCtxGetter = NewCtxGetter(trmcontext.DefaultManager)
// CtxGetter gets Tr from trm.СtxManager by casting trm.Transaction to Tr.
type CtxGetter struct {
ctxManager trm.СtxManager
}
// NewCtxGetter returns *CtxGetter to get Tr from context.Context.
func NewCtxGetter(c trm.СtxManager) *CtxGetter {
return &CtxGetter{ctxManager: c}
}
// DefaultTrOrDB returns Tr from context.Context or DB(Tr) otherwise.
func (c *CtxGetter) DefaultTrOrDB(ctx context.Context, db Tr) Tr {
if tr := c.ctxManager.Default(ctx); tr != nil {
return c.convert(tr)
}
return db
}
// TrOrDB returns Tr from context.Context by trm.CtxKey or DB(Tr) otherwise.
func (c *CtxGetter) TrOrDB(ctx context.Context, key trm.CtxKey, db Tr) Tr {
if tr := c.ctxManager.ByKey(ctx, key); tr != nil {
return c.convert(tr)
}
return db
}
func (c *CtxGetter) convert(tr trm.Transaction) Tr {
if tx, ok := tr.Transaction().(*sql.Tx); ok {
return tx
}
return nil
}