Skip to content

Commit

Permalink
Add affected_rows to sql.active_record
Browse files Browse the repository at this point in the history
  • Loading branch information
aidanharan committed Dec 9, 2024
1 parent 0afebac commit 8b3c4e5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions test/cases/coerced_tests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 8b3c4e5

Please sign in to comment.