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 10, 2024
1 parent 45d0a54 commit 6bfc5d3
Show file tree
Hide file tree
Showing 2 changed files with 29 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,14 @@ def query(sql)
propagator.inject(sql, context: context)
end

super
result = super

attributes = { 'db.response.returned_rows' => result.count }
attributes['db.response.affected_rows'] = result.affected_rows unless result.affected_rows.nil?

span.add_attributes(attributes)

result
end
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,26 @@
_(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

it 'includes affected rows' do
client.query(<<~SQL)
CREATE TABLE products (
product_id int
)
SQL

client.query('INSERT INTO products (product_id) VALUES (1), (2), (3)')

_(exporter.finished_spans.last.attributes['db.response.affected_rows']).must_equal(3)
ensure
client.query('DROP TABLE IF EXISTS products')
end
end

describe 'when connecting' do
Expand Down

0 comments on commit 6bfc5d3

Please sign in to comment.