Skip to content

Commit

Permalink
fix: Fix passing data using context in gorm
Browse files Browse the repository at this point in the history
  • Loading branch information
laynax committed Feb 22, 2023
1 parent e1b066b commit 3c1371e
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions pkg/instrumentation/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,26 @@ import (
"gorm.io/gorm"
)

const (
type spanContextKey string

var (
// ParentSpanGormKey is the name of the parent span key
ParentSpanGormKey = "tracingParentSpan"
parentSpanGormKey = spanContextKey("trancingParentSpan")
// SpanGormKey is the name of the span key
SpanGormKey = "tracingSpan"
spanGormKey = spanContextKey("tracingSpan")
)

// TraceDatabase sets span to gorm settings, returns cloned DB
func TraceDatabase(ctx context.Context, db *gorm.DB) *gorm.DB {
if ctx == nil {
return db
}

parentSpan, _ := ddtrace.SpanFromContext(ctx)
return db.Set(ParentSpanGormKey, parentSpan)

return db.Session(&gorm.Session{
Context: context.WithValue(db.Statement.Context, parentSpanGormKey, parentSpan),
})
}

// InstrumentDatabase adds callbacks for tracing, call TraceDatabase to make it work
Expand Down Expand Up @@ -58,12 +64,11 @@ func (c *callbacks) afterDelete(db *gorm.DB) { c.after(db) }
func (c *callbacks) beforeRow(db *gorm.DB) { c.before(db, "", c.serviceName) }
func (c *callbacks) afterRow(db *gorm.DB) { c.after(db) }
func (c *callbacks) before(db *gorm.DB, operationName string, serviceName string) {
val, ok := db.Get(ParentSpanGormKey)
parentSpan, ok := db.Statement.Context.Value(parentSpanGormKey).(ddtrace.Span)
if !ok {
return
}

parentSpan := val.(ddtrace.Span)
spanOpts := []ddtrace.StartSpanOption{
ddtrace.ChildOf(parentSpan.Context()),
ddtrace.SpanType(ext.SpanTypeSQL),
Expand All @@ -73,16 +78,15 @@ func (c *callbacks) before(db *gorm.DB, operationName string, serviceName string
operationName = strings.Split(db.Statement.SQL.String(), " ")[0]
}
sp := ddtrace.StartSpan(operationName, spanOpts...)
db.Set(SpanGormKey, sp)
db.Statement.Context = context.WithValue(db.Statement.Context, spanGormKey, sp)
}

func (c *callbacks) after(db *gorm.DB) {
val, ok := db.Get(SpanGormKey)
sp, ok := db.Statement.Context.Value(spanGormKey).(ddtrace.Span)
if !ok {
return
}

sp := val.(ddtrace.Span)
sp.SetTag(ext.ResourceName, strings.ToUpper(db.Statement.SQL.String()))
sp.SetTag("db.table", db.Statement.Table)
sp.SetTag("db.query", strings.ToUpper(db.Statement.SQL.String()))
Expand Down

0 comments on commit 3c1371e

Please sign in to comment.