-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
70 lines (59 loc) · 1.29 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package spansqlx
import (
"context"
"cloud.google.com/go/spanner"
)
type txContextKey int8
const (
// ReadWrite transaction
rwTxContextKey txContextKey = iota + 1
// ReadOnly transaction
roTxContextKey
)
func SetTxContext(ctx context.Context, arg interface{}) context.Context {
if ctx == nil {
ctx = context.Background()
}
switch tx := arg.(type) {
case *spanner.ReadOnlyTransaction:
ctx = context.WithValue(ctx, roTxContextKey, tx)
case *spanner.ReadWriteTransaction:
ctx = context.WithValue(ctx, rwTxContextKey, tx)
}
return ctx
}
func hasReadWriteTxContext(ctx context.Context) (*spanner.ReadWriteTransaction, bool) {
if ctx == nil {
return nil, false
}
tx, ok := ctx.Value(rwTxContextKey).(*spanner.ReadWriteTransaction)
if !ok {
return nil, false
}
if tx == nil {
return nil, false
}
return tx, true
}
func hasReadOnlyTxContext(ctx context.Context) (*spanner.ReadOnlyTransaction, bool) {
if ctx == nil {
return nil, false
}
tx, ok := ctx.Value(rwTxContextKey).(*spanner.ReadOnlyTransaction)
if !ok {
return nil, false
}
if tx == nil {
return nil, false
}
return tx, true
}
func hasTxContext(ctx context.Context) interface{} {
if v, ok := hasReadOnlyTxContext(ctx); ok {
return v
}
if v, ok := hasReadWriteTxContext(ctx); ok {
return v
}
return nil
}