-
Notifications
You must be signed in to change notification settings - Fork 0
/
metric.go
50 lines (41 loc) · 849 Bytes
/
metric.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
package ormx
import (
"context"
"strings"
)
type MetricHandler interface {
Emit(context.Context, string, bool)
}
var metricHandler MetricHandler
func emitMetric(ctx context.Context, sql string) {
if metricHandler == nil {
return
}
var (
table string
write bool
)
if i := strings.Index(sql, " FROM "); i > 0 {
write = false
sql = strings.TrimSpace(sql[i+6:])
} else if j := strings.Index(sql, " INTO "); j > 0 {
write = true
sql = strings.TrimSpace(sql[j+6:])
} else if k := strings.Index(sql, "UPDATE "); k >= 0 {
write = true
sql = strings.TrimSpace(sql[k+7:])
} else {
return
}
tableName, subSQL, ok := strings.Cut(sql, " ")
if ok {
table = tableName
} else {
emitMetric(ctx, subSQL)
return
}
metricHandler.Emit(ctx, table, write)
}
func SetMetricHandler(h MetricHandler) {
metricHandler = h
}