-
Notifications
You must be signed in to change notification settings - Fork 15
/
utils.go
85 lines (69 loc) · 1.48 KB
/
utils.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package lungo
import (
"context"
"fmt"
"reflect"
)
const (
supported = "supported"
ignored = "ignored"
)
func ensureContext(ctx context.Context) context.Context {
// check context
if ctx != nil {
return ctx
}
return context.Background()
}
func assertOptions(opts interface{}, fields map[string]string) {
// get value
value := reflect.ValueOf(opts).Elem()
// check fields
for i := 0; i < value.NumField(); i++ {
// get name
name := value.Type().Field(i).Name
// check if field is supported
support := fields[name]
if support == supported || support == ignored {
continue
}
// otherwise, assert field is nil
if !value.Field(i).IsNil() {
panic(fmt.Sprintf("lungo: unsupported option: %s", name))
}
}
}
func useTransaction(ctx context.Context, engine *Engine, lock bool, fn func(*Transaction) (interface{}, error)) (interface{}, error) {
// ensure context
ctx = ensureContext(ctx)
// use active transaction from session in context
sess, ok := ctx.Value(sessionKey{}).(*Session)
if ok {
txn := sess.Transaction()
if txn != nil {
return fn(txn)
}
}
// create transaction
txn, err := engine.Begin(ctx, lock)
if err != nil {
return nil, err
}
// handle unlocked transactions immediately
if !lock {
return fn(txn)
}
// ensure abortion
defer engine.Abort(txn)
// yield callback
res, err := fn(txn)
if err != nil {
return nil, err
}
// commit transaction
err = engine.Commit(txn)
if err != nil {
return nil, err
}
return res, nil
}