Created
May 23, 2021 12:49
-
-
Save alpaca-tc/6c3f63d8d4c560a23d703f9274e4453f to your computer and use it in GitHub Desktop.
重複するインデックスを検知する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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