diff --git a/lib/active_record/connection_adapters/sqlserver/database_statements.rb b/lib/active_record/connection_adapters/sqlserver/database_statements.rb index 9e36d61aa..a4bb95831 100644 --- a/lib/active_record/connection_adapters/sqlserver/database_statements.rb +++ b/lib/active_record/connection_adapters/sqlserver/database_statements.rb @@ -26,6 +26,8 @@ def perform_query(raw_connection, sql, binds, type_casted_binds, prepare:, notif end verified! + + notification_payload[:affected_rows] = affected_rows(result) notification_payload[:row_count] = result.count result end @@ -39,7 +41,7 @@ def cast_result(raw_result) end def affected_rows(raw_result) - raw_result.first['AffectedRows'] + raw_result&.first&.fetch('AffectedRows', 0) || 0 end def raw_execute(sql, name = nil, binds = [], prepare: false, async: false, allow_retry: false, materialize_transactions: true, batch: false) @@ -68,6 +70,11 @@ def exec_update(sql, name = nil, binds = []) super(sql, name, binds) end + def exec_insert_all(sql, name) + sql = sql.dup << "; SELECT @@ROWCOUNT AS AffectedRows" + super(sql, name) + end + def begin_db_transaction internal_execute("BEGIN TRANSACTION", "TRANSACTION", allow_retry: true, materialize_transactions: false) end @@ -179,6 +186,8 @@ def execute_procedure(proc_name, *variables) end result = result.each.map { |row| row.is_a?(Hash) ? row.with_indifferent_access : row } + + notification_payload[:affected_rows] = affected_rows(result) notification_payload[:row_count] = result.count result end diff --git a/test/cases/coerced_tests.rb b/test/cases/coerced_tests.rb index 1ffa0694c..01d08ddfd 100644 --- a/test/cases/coerced_tests.rb +++ b/test/cases/coerced_tests.rb @@ -372,6 +372,13 @@ def test_payload_row_count_on_raw_sql_coerced Book.where(author_id: nil, name: 'row count book 3').delete_all Book.lease_connection.add_index(:books, [:author_id, :name], unique: true) end + + # Fix randomly failing test. The loading of the model's schema was affecting the test. + coerce_tests! :test_payload_affected_rows + def test_payload_affected_rows_coerced + Book.send(:load_schema!) + original_test_payload_affected_rows + end end end