Skip to content

Commit

Permalink
Add row count and affected rows to Trilogy spans
Browse files Browse the repository at this point in the history
Identifying queries that return/update many rows is very useful for
improving database performance. Queries that return many rows can cause
applications to use excess memory (or in some cases like Vitess) could
be blocked altogether. Queries that update many rows can cause
replication lag and generally put more pressure on a database.

This commit adds both of these values (row_count and affected_rows) to
spans created from Trilogy#query to help identify these problematic
queries. Trilogy::Result#count will always return a value (0 for
mutations), but #affected_rows only returns values for mutations (nil
for SELECTs).
  • Loading branch information
skipkayhil committed Dec 5, 2024
1 parent 45d0a54 commit be86418
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def query(sql)
OpenTelemetry::Instrumentation::Trilogy.attributes
),
kind: :client
) do |_span, context|
) do |span, context|
if propagator && sql.frozen?
sql = +sql
propagator.inject(sql, context: context)
Expand All @@ -58,7 +58,12 @@ def query(sql)
propagator.inject(sql, context: context)
end

super
result = super

span.set_attribute('db.response.returned_rows', result.count)
span.set_attribute('db.response.affected_rows', result.affected_rows) unless result.affected_rows.nil?

result
end
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,12 @@
_(span.attributes[OpenTelemetry::SemanticConventions::Trace::DB_SYSTEM]).must_equal 'mysql'
_(span.attributes[OpenTelemetry::SemanticConventions::Trace::DB_STATEMENT]).must_equal 'DESELECT ?'
end

it 'includes row count' do
client.query('SELECT 1')

_(span.attributes['db.response.returned_rows']).must_equal(1)
end
end

describe 'when connecting' do
Expand Down

0 comments on commit be86418

Please sign in to comment.