Skip to content

Commit 392b35e

Browse files
mrsimoarielvalentinkaylareopelle
authored
fix!: activerecord find_by_sql spans on Rails 7.0+ (#1184)
* fix: activerecord find_by_sql spans on Rails 7.0+ * tests: fix create_table call * tests: rubocop tweak * feat: call spans that produce reads `query` * Refactor patching to use define_method --------- Co-authored-by: Ariel Valentin <[email protected]> Co-authored-by: Kayla Reopelle <[email protected]>
1 parent e3bd524 commit 392b35e

File tree

3 files changed

+24
-7
lines changed

3 files changed

+24
-7
lines changed

instrumentation/active_record/lib/opentelemetry/instrumentation/active_record/patches/querying.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,11 @@ class << base
1818

1919
# Contains ActiveRecord::Querying to be patched
2020
module ClassMethods
21-
def find_by_sql(...)
22-
tracer.in_span("#{self}.find_by_sql") do
23-
super
21+
method_name = ::ActiveRecord.version >= Gem::Version.new('7.0.0') ? :_query_by_sql : :find_by_sql
22+
23+
define_method(method_name) do |*args, **kwargs|
24+
tracer.in_span("#{self} query") do
25+
super(*args, **kwargs)
2426
end
2527
end
2628

instrumentation/active_record/test/instrumentation/active_record/patches/querying_test.rb

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,18 @@
1515

1616
before { exporter.reset }
1717

18-
describe 'find_by_sql' do
18+
describe 'query' do
1919
it 'traces' do
20+
Account.create!
21+
2022
User.find_by_sql('SELECT * FROM users')
23+
Account.first.users.to_a
24+
25+
user_find_spans = spans.select { |s| s.name == 'User query' }
26+
account_find_span = spans.find { |s| s.name == 'Account query' }
2127

22-
find_span = spans.find { |s| s.name == 'User.find_by_sql' }
23-
_(find_span).wont_be_nil
28+
_(user_find_spans.length).must_equal(2)
29+
_(account_find_span).wont_be_nil
2430
end
2531
end
2632
end

instrumentation/active_record/test/test_helper.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,14 @@
3434
database: 'db/development.sqlite3'
3535
)
3636

37-
# Create User model
37+
# Create ActiveRecord models
38+
class Account < ActiveRecord::Base
39+
has_many :users
40+
end
41+
3842
class User < ActiveRecord::Base
43+
belongs_to :account
44+
3945
validate :name_if_present
4046

4147
scope :recently_created, -> { where('created_at > ?', Time.now - 3600) }
@@ -54,9 +60,12 @@ class SuperUser < ActiveRecord::Base; end
5460
# Simple migration to create a table to test against
5561
class CreateUserTable < ActiveRecord::Migration[migration_version]
5662
def change
63+
create_table :accounts, &:timestamps
64+
5765
create_table :users do |t|
5866
t.string 'name'
5967
t.integer 'counter'
68+
t.references 'account'
6069
t.timestamps
6170
end
6271

0 commit comments

Comments
 (0)