Skip to content

Commit 9827b88

Browse files
committed
Test if insert_all / upsert_all apply correct values
If Rails give the database multiple values that would conflict in their identifiers (be it unique indexes or primary keys), the database has to decide which ones to apply. For `insert_all`, this will be the first one (since on conflict, the second entry will be skipped). For `upsert_all`, this is the last one (since on each duplicate, the values get updated). This commit adds two tests to verify that. The `upsert_all` test has be skipped on PostgreSQL, as upserting with duplicate identifiers is not supported. For more details, see rails#35531.
1 parent e9d7ca5 commit 9827b88

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

activerecord/test/cases/insert_all_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,16 @@ def test_insert_all_with_skip_duplicates_and_autonumber_id_given
185185
end
186186
end
187187

188+
def test_insert_all_only_applies_last_value_when_given_duplicate_identifiers
189+
skip unless supports_insert_on_duplicate_skip?
190+
191+
Book.insert_all [
192+
{ id: 111, name: "expected_new_name" },
193+
{ id: 111, name: "unexpected_new_name" }
194+
]
195+
assert_equal "expected_new_name", Book.find(111).name
196+
end
197+
188198
def test_skip_duplicates_strategy_does_not_secretly_upsert
189199
skip unless supports_insert_on_duplicate_skip?
190200

@@ -399,6 +409,18 @@ def test_upsert_all_updates_existing_record_by_primary_key
399409
assert_equal "New edition", Book.find(1).name
400410
end
401411

412+
def test_upsert_all_only_applies_last_value_when_given_duplicate_identifiers
413+
skip unless supports_insert_on_duplicate_update? && !current_adapter?(:PostgreSQLAdapter)
414+
415+
Book.create!(id: 112, name: "original_name")
416+
417+
Book.upsert_all [
418+
{ id: 112, name: "unexpected_new_name" },
419+
{ id: 112, name: "expected_new_name" }
420+
]
421+
assert_equal "expected_new_name", Book.find(112).name
422+
end
423+
402424
def test_upsert_all_does_notupdates_existing_record_by_when_there_is_no_key
403425
skip unless supports_insert_on_duplicate_update? && !supports_insert_conflict_target?
404426

0 commit comments

Comments
 (0)