Skip to content

Commit 8b3c4e5

Browse files
committed
Add affected_rows to sql.active_record
1 parent 0afebac commit 8b3c4e5

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

lib/active_record/connection_adapters/sqlserver/database_statements.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ def perform_query(raw_connection, sql, binds, type_casted_binds, prepare:, notif
2626
end
2727

2828
verified!
29+
30+
notification_payload[:affected_rows] = affected_rows(result)
2931
notification_payload[:row_count] = result.count
3032
result
3133
end
@@ -39,7 +41,7 @@ def cast_result(raw_result)
3941
end
4042

4143
def affected_rows(raw_result)
42-
raw_result.first['AffectedRows']
44+
raw_result&.first&.fetch('AffectedRows', 0) || 0
4345
end
4446

4547
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 = [])
6870
super(sql, name, binds)
6971
end
7072

73+
def exec_insert_all(sql, name)
74+
sql = sql.dup << "; SELECT @@ROWCOUNT AS AffectedRows"
75+
super(sql, name)
76+
end
77+
7178
def begin_db_transaction
7279
internal_execute("BEGIN TRANSACTION", "TRANSACTION", allow_retry: true, materialize_transactions: false)
7380
end
@@ -179,6 +186,8 @@ def execute_procedure(proc_name, *variables)
179186
end
180187

181188
result = result.each.map { |row| row.is_a?(Hash) ? row.with_indifferent_access : row }
189+
190+
notification_payload[:affected_rows] = affected_rows(result)
182191
notification_payload[:row_count] = result.count
183192
result
184193
end

test/cases/coerced_tests.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,13 @@ def test_payload_row_count_on_raw_sql_coerced
372372
Book.where(author_id: nil, name: 'row count book 3').delete_all
373373
Book.lease_connection.add_index(:books, [:author_id, :name], unique: true)
374374
end
375+
376+
# Fix randomly failing test. The loading of the model's schema was affecting the test.
377+
coerce_tests! :test_payload_affected_rows
378+
def test_payload_affected_rows_coerced
379+
Book.send(:load_schema!)
380+
original_test_payload_affected_rows
381+
end
375382
end
376383
end
377384

0 commit comments

Comments
 (0)