-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtxn.go
More file actions
71 lines (56 loc) · 2.01 KB
/
txn.go
File metadata and controls
71 lines (56 loc) · 2.01 KB
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
71
package corekv
import "context"
// TxnStore represents a [Store] that supports transactions.
type TxnStore interface {
Store
// NewTxn returns a new transaction.
NewTxn(readonly bool) Txn
}
// TxnReaderWriter contains the functions for reading and writing values within the store
// and supports transactions.
type TxnReaderWriter interface {
ReaderWriter
// NewTxn returns a new transaction.
NewTxn(readonly bool) Txn
}
// Txn isolates changes made to the underlying store from this object,
// and isolates changes made via this object from the underlying store
// until `Commit` is called.
type Txn interface {
ReaderWriter
// Commit applies all changes made via this [Txn] to the underlying
// [Store].
Commit() error
// Discard discards all changes made via this object so far, returning
// it to the state it was at at time of construction.
Discard()
}
type ctxTxnKey struct{}
// CtxTxnKey is the unique transaction context key that can be used
// to get or set the current transaction on the context.
var CtxTxnKey = &ctxTxnKey{}
// MustGetCtxTxn returns the transaction from the context or panics.
func MustGetCtxTxn(ctx context.Context) Txn {
return MustGetCtxTxnG[Txn](ctx)
}
// MustGetCtxTxn returns the transaction from the context or panics.
func MustGetCtxTxnG[T Txn](ctx context.Context) T {
return ctx.Value(CtxTxnKey).(T) //nolint:forcetypeassert
}
// TryGetCtxTxn returns a transaction and a bool indicating if the
// txn was retrieved from the given context.
func TryGetCtxTxn(ctx context.Context) (Txn, bool) {
return TryGetCtxTxnG[Txn](ctx)
}
// TryGetCtxTxnG returns a transaction and a bool indicating if the
// txn was retrieved from the given context.
func TryGetCtxTxnG[T Txn](ctx context.Context) (T, bool) {
txn, ok := ctx.Value(CtxTxnKey).(T)
return txn, ok
}
// CtxSetTxn returns a new context with the txn value set.
//
// This will overwrite any previously set transaction value.
func SetCtxTxn(ctx context.Context, txn Txn) context.Context {
return context.WithValue(ctx, CtxTxnKey, txn)
}