Skip to content

Commit

Permalink
Merge pull request rails#44973 from ushi-as/fix-sql-log-for-unnamed-b…
Browse files Browse the repository at this point in the history
…inds

activerecord: fix sql log with unnamed binds
  • Loading branch information
tenderlove authored Apr 28, 2022
2 parents f897428 + fe62bb5 commit 6ce8c03
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
9 changes: 8 additions & 1 deletion activerecord/lib/active_record/log_subscriber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,14 @@ def sql(event)

binds = []
payload[:binds].each_with_index do |attr, i|
attribute_name = attr.respond_to?(:name) ? attr.name : attr[i].name
attribute_name = if attr.respond_to?(:name)
attr.name
elsif attr.respond_to?(:[]) && attr[i].respond_to?(:name)
attr[i].name
else
nil
end

filtered_params = filter(attribute_name, casted_params[i])

binds << render_bind(attr, filtered_params)
Expand Down
37 changes: 37 additions & 0 deletions activerecord/test/cases/bind_parameter_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ def test_logs_binds_after_type_cast
assert_logs_binds(binds)
end

def test_logs_unnamed_binds
binds = ["abcd"]
assert_logs_unnamed_binds(binds)
end

def test_bind_params_to_sql_with_prepared_statements
assert_bind_params_to_sql
end
Expand Down Expand Up @@ -281,6 +286,38 @@ def debug(str)
assert_match %r(\[\["id", 10\]\]\z), logger.debugs.first
end

def assert_logs_unnamed_binds(binds)
payload = {
name: "SQL",
sql: "select * from topics where title = $1",
binds: binds,
type_casted_binds: @connection.send(:type_casted_binds, binds)
}

event = ActiveSupport::Notifications::Event.new(
"foo",
Time.now,
Time.now,
123,
payload)

logger = Class.new(ActiveRecord::LogSubscriber) {
attr_reader :debugs

def initialize
super
@debugs = []
end

def debug(str)
@debugs << str
end
}.new

logger.sql(event)
assert_match %r(\[\[nil, "abcd"\]\]\z), logger.debugs.first
end

def assert_filtered_log_binds(binds)
payload = {
name: "SQL",
Expand Down

0 comments on commit 6ce8c03

Please sign in to comment.