Skip to content

Commit 27c3ad0

Browse files
authored
Merge pull request rails#35892 from ryohashimoto/bulk_insert_logs
Improve log messages for #insert_all` / `#upsert_all` etc. methods
2 parents 3f0a25a + 54dce68 commit 27c3ad0

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

activerecord/lib/active_record/insert_all.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@ def initialize(model, inserts, on_duplicate:, returning: nil, unique_by: nil)
2121
end
2222

2323
def execute
24-
connection.exec_query to_sql, "Bulk Insert"
24+
message = "#{model} "
25+
message += "Bulk " if inserts.many?
26+
message += (on_duplicate == :update ? "Upsert" : "Insert")
27+
connection.exec_query to_sql, message
2528
end
2629

2730
def updatable_columns

activerecord/test/cases/insert_all_test.rb

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,42 @@ def test_insert_all_and_upsert_all_raises_when_index_is_missing
181181
end
182182
end
183183

184+
def test_insert_logs_message_including_model_name
185+
skip unless supports_insert_conflict_target?
186+
187+
capture_log_output do |output|
188+
Book.insert(name: "Rework", author_id: 1)
189+
assert_match "Book Insert", output.string
190+
end
191+
end
192+
193+
def test_insert_all_logs_message_including_model_name
194+
skip unless supports_insert_conflict_target?
195+
196+
capture_log_output do |output|
197+
Book.insert_all [{ name: "Remote", author_id: 1 }, { name: "Renote", author_id: 1 }]
198+
assert_match "Book Bulk Insert", output.string
199+
end
200+
end
201+
202+
def test_upsert_logs_message_including_model_name
203+
skip unless supports_insert_on_duplicate_update?
204+
205+
capture_log_output do |output|
206+
Book.upsert(name: "Remote", author_id: 1)
207+
assert_match "Book Upsert", output.string
208+
end
209+
end
210+
211+
def test_upsert_all_logs_message_including_model_name
212+
skip unless supports_insert_on_duplicate_update?
213+
214+
capture_log_output do |output|
215+
Book.upsert_all [{ name: "Remote", author_id: 1 }, { name: "Renote", author_id: 1 }]
216+
assert_match "Book Bulk Upsert", output.string
217+
end
218+
end
219+
184220
def test_upsert_all_updates_existing_records
185221
skip unless supports_insert_on_duplicate_update?
186222

@@ -224,4 +260,17 @@ def test_insert_all_raises_on_unknown_attribute
224260
Book.insert_all! [{ unknown_attribute: "Test" }]
225261
end
226262
end
263+
264+
private
265+
266+
def capture_log_output
267+
output = StringIO.new
268+
old_logger, ActiveRecord::Base.logger = ActiveRecord::Base.logger, ActiveSupport::Logger.new(output)
269+
270+
begin
271+
yield output
272+
ensure
273+
ActiveRecord::Base.logger = old_logger
274+
end
275+
end
227276
end

0 commit comments

Comments
 (0)