Use builtin Rails index_exists? for indices (#6293)

This commit is contained in:
rhymes 2020-02-26 17:05:24 +01:00 committed by GitHub
parent e2cb359b2d
commit fc09716709
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 24 deletions

View file

@ -1,19 +0,0 @@
module IndexMigrationHelpers
def add_index_if_missing(table_name, column_name, options = {})
columns = Array(column_name)
if options.key?(:name) && indexes(table_name).none? { |idx| idx.name == options[:name] }
add_index(table_name, column_name, options)
elsif indexes(table_name).none? { |idx| idx.columns.map(&:to_sym) == columns }
add_index(table_name, column_name, options)
end
end
def remove_index_if_exists(table_name, options = {})
columns = Array(options[:column])
if options.key?(:name) && indexes(table_name).any? { |idx| idx.name == options[:name] }
remove_index(table_name, options)
elsif indexes(table_name).any? { |idx| idx.columns.map(&:to_sym) == columns }
remove_index(table_name, options)
end
end
end

View file

@ -1,5 +1,8 @@
# https://github.com/ankane/strong_migrations#existing-migrations
StrongMigrations.start_after = 20_200_106_074_859
# https://github.com/ankane/strong_migrations#removing-an-index
StrongMigrations.enable_check(:remove_index)
# https://github.com/ankane/strong_migrations#target-version
StrongMigrations.target_postgresql_version = 11

View file

@ -1,14 +1,23 @@
class AddTitleWebsiteUrlIndexesToPodcastEpisodes < ActiveRecord::Migration[5.2]
disable_ddl_transaction!
include IndexMigrationHelpers
def up
add_index_if_missing(:podcast_episodes, :title, algorithm: :concurrently)
add_index_if_missing(:podcast_episodes, :website_url, algorithm: :concurrently)
unless index_exists?(:podcast_episodes, :title)
add_index :podcast_episodes, :title, algorithm: :concurrently
end
unless index_exists?(:podcast_episodes, :website_url)
add_index :podcast_episodes, :website_url, algorithm: :concurrently
end
end
def down
remove_index_if_exists(:podcast_episodes, column: :title, algorithm: :concurrently)
remove_index_if_exists(:podcast_episodes, column: :website_url, algorithm: :concurrently)
if index_exists?(:podcast_episodes, :title)
remove_index :podcast_episodes, column: :title, algorithm: :concurrently
end
if index_exists?(:podcast_episodes, :website_url)
remove_index :podcast_episodes, column: :website_url, algorithm: :concurrently
end
end
end