-
Notifications
You must be signed in to change notification settings - Fork 9
/
transaction.go
59 lines (47 loc) · 1.42 KB
/
transaction.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
package hotload
import (
"context"
"database/sql/driver"
)
// managedTx wraps a sql/driver.Tx so that it can store the context of the
// transaction and clean up the execqueryCallsCounter on Commit or Rollback.
type managedTx struct {
tx driver.Tx
conn *managedConn
ctx context.Context
}
func (t *managedTx) Commit() error {
err := t.tx.Commit()
t.cleanup()
return err
}
func (t *managedTx) Rollback() error {
err := t.tx.Rollback()
t.cleanup()
return err
}
func observeSQLStmtsSummary(ctx context.Context, execStmtsCounter, queryStmtsCounter int) {
labels := GetExecLabelsFromContext(ctx)
service := labels[GRPCServiceKey]
method := labels[GRPCMethodKey]
sqlStmtsSummary.WithLabelValues(service, method, ExecStatement).Observe(float64(execStmtsCounter))
sqlStmtsSummary.WithLabelValues(service, method, QueryStatement).Observe(float64(queryStmtsCounter))
}
func (t *managedTx) cleanup() {
observeSQLStmtsSummary(t.ctx, t.conn.execStmtsCounter, t.conn.queryStmtsCounter)
t.conn.resetExecStmtsCounter()
t.conn.resetQueryStmtsCounter()
}
var promLabelKey = struct{}{}
func ContextWithExecLabels(ctx context.Context, labels map[string]string) context.Context {
return context.WithValue(ctx, promLabelKey, labels)
}
func GetExecLabelsFromContext(ctx context.Context) map[string]string {
if ctx == nil {
return nil
}
if ctx.Value(promLabelKey) == nil {
return nil
}
return ctx.Value(promLabelKey).(map[string]string)
}