Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow insert_all/upsert_all to use indexes with columns not in the same order as in :unique_by #48018

Merged
merged 1 commit into from
Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion activerecord/lib/active_record/insert_all.rb
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,9 @@ def find_unique_index_for(unique_by)

name_or_columns = unique_by || model.primary_key
match = Array(name_or_columns).map(&:to_s)
sorted_match = match.sort

if index = unique_indexes.find { |i| match.include?(i.name) || i.columns == match }
if index = unique_indexes.find { |i| match.include?(i.name) || Array(i.columns).sort == sorted_match }
index
elsif match == primary_keys
unique_by.nil? ? nil : ActiveRecord::ConnectionAdapters::IndexDefinition.new(model.table_name, "#{model.table_name}_primary_key", true, match)
Expand Down
12 changes: 12 additions & 0 deletions activerecord/test/cases/insert_all_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,18 @@ def test_insert_all_and_upsert_all_raises_when_index_is_missing
end
end

def test_insert_all_and_upsert_all_finds_index_with_inverted_unique_by_columns
skip unless supports_insert_conflict_target?

columns = [:author_id, :name]
assert ActiveRecord::Base.connection.index_exists?(:books, columns)

assert_difference "Book.count", +2 do
Book.insert_all [{ name: "Remote", author_id: 1 }], unique_by: columns.reverse
Book.upsert_all [{ name: "Rework", author_id: 1 }], unique_by: columns.reverse
end
end

def test_insert_all_and_upsert_all_works_with_composite_primary_keys_when_unique_by_is_provided
skip unless supports_insert_conflict_target?

Expand Down