Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alpaca-tc/6c3f63d8d4c560a23d703f9274e4453f to your computer and use it in GitHub Desktop.
Save alpaca-tc/6c3f63d8d4c560a23d703f9274e4453f to your computer and use it in GitHub Desktop.
重複するインデックスを検知する
# frozen_string_literal: true
RSpec.describe 'ActiveRecord duplicated indexes' do
let(:connection) do
ActiveRecord::Base.connection
end
it 'is not found' do
tables = connection.tables
duplicated_indexes = {}
tables.each do |table_name|
indexes = connection.indexes(table_name)
indexes.each do |index|
(indexes - [index]).each do |other_index|
# ユニーク制約は単体で意味があるインデックスなので、他のインデックスと重複しても問題がない
next if index.unique
# インデックスの内容が重複していなければ問題がない
next unless index.columns == other_index.columns.first(index.columns.size)
duplicated_indexes[index] = other_index
end
end
end
expect(duplicated_indexes).to be_empty, -> {
messages = duplicated_indexes.map { |index, other_index| "#{index.table}: #{index.columns} is included by #{other_index.columns}" }
<<~MESSAGE
Found duplicated indexes
#{messages.join("\n")}
MESSAGE
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment