Skip to content

Commit ce03255

Browse files
authored
Merge pull request rails#48018 from fatkodima/insert_all-out-of-order-indexes
Allow `insert_all`/`upsert_all` to use indexes with columns not in the same order as in `:unique_by`
2 parents 976c487 + 45bff16 commit ce03255

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

activerecord/lib/active_record/insert_all.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,9 @@ def find_unique_index_for(unique_by)
151151

152152
name_or_columns = unique_by || model.primary_key
153153
match = Array(name_or_columns).map(&:to_s)
154+
sorted_match = match.sort
154155

155-
if index = unique_indexes.find { |i| match.include?(i.name) || i.columns == match }
156+
if index = unique_indexes.find { |i| match.include?(i.name) || Array(i.columns).sort == sorted_match }
156157
index
157158
elsif match == primary_keys
158159
unique_by.nil? ? nil : ActiveRecord::ConnectionAdapters::IndexDefinition.new(model.table_name, "#{model.table_name}_primary_key", true, match)

activerecord/test/cases/insert_all_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,18 @@ def test_insert_all_and_upsert_all_raises_when_index_is_missing
219219
end
220220
end
221221

222+
def test_insert_all_and_upsert_all_finds_index_with_inverted_unique_by_columns
223+
skip unless supports_insert_conflict_target?
224+
225+
columns = [:author_id, :name]
226+
assert ActiveRecord::Base.connection.index_exists?(:books, columns)
227+
228+
assert_difference "Book.count", +2 do
229+
Book.insert_all [{ name: "Remote", author_id: 1 }], unique_by: columns.reverse
230+
Book.upsert_all [{ name: "Rework", author_id: 1 }], unique_by: columns.reverse
231+
end
232+
end
233+
222234
def test_insert_all_and_upsert_all_works_with_composite_primary_keys_when_unique_by_is_provided
223235
skip unless supports_insert_conflict_target?
224236

0 commit comments

Comments
 (0)