5
5
"database/sql/driver"
6
6
"fmt"
7
7
"io"
8
+ "regexp"
9
+ "strings"
8
10
9
11
"go.opentelemetry.io/otel"
10
12
"go.opentelemetry.io/otel/attribute"
@@ -16,7 +18,14 @@ import (
16
18
"gorm.io/plugin/opentelemetry/metrics"
17
19
)
18
20
19
- var dbRowsAffected = attribute .Key ("db.rows_affected" )
21
+ var (
22
+ firstWordRegex = regexp .MustCompile (`^\w+` )
23
+ cCommentRegex = regexp .MustCompile (`(?is)/\*.*?\*/` )
24
+ lineCommentRegex = regexp .MustCompile (`(?im)(?:--|#).*?$` )
25
+ sqlPrefixRegex = regexp .MustCompile (`^[\s;]*` )
26
+
27
+ dbRowsAffected = attribute .Key ("db.rows_affected" )
28
+ )
20
29
21
30
type otelPlugin struct {
22
31
provider trace.TracerProvider
@@ -124,7 +133,9 @@ func (p *otelPlugin) after() gormHookFunc {
124
133
query = tx .Dialector .Explain (tx .Statement .SQL .String (), vars ... )
125
134
}
126
135
127
- attrs = append (attrs , semconv .DBStatementKey .String (p .formatQuery (query )))
136
+ formatQuery := p .formatQuery (query )
137
+ attrs = append (attrs , semconv .DBStatementKey .String (formatQuery ))
138
+ attrs = append (attrs , semconv .DBOperationKey .String (dbOperation (formatQuery )))
128
139
if tx .Statement .Table != "" {
129
140
attrs = append (attrs , semconv .DBSQLTableKey .String (tx .Statement .Table ))
130
141
}
@@ -172,3 +183,10 @@ func dbSystem(tx *gorm.DB) attribute.KeyValue {
172
183
return attribute.KeyValue {}
173
184
}
174
185
}
186
+
187
+ func dbOperation (query string ) string {
188
+ s := cCommentRegex .ReplaceAllString (query , "" )
189
+ s = lineCommentRegex .ReplaceAllString (s , "" )
190
+ s = sqlPrefixRegex .ReplaceAllString (s , "" )
191
+ return strings .ToLower (firstWordRegex .FindString (s ))
192
+ }
0 commit comments