Created
October 11, 2018 03:17
-
-
Save lucianghinda/dd9045af4fcbd99282324e4b49570aa9 to your computer and use it in GitHub Desktop.
Enhance Migration to Check for Foreign Keys
This file contains hidden or 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
# Script copied from https://alexpeattie.com/blog/stop-forgetting-foreign-key-indexes-in-rails-post-migration-script | |
Rake::Task['db:migrate'].enhance do | |
tables = ActiveRecord::Base.connection.tables | |
all_foreign_keys = tables.flat_map do |table_name| | |
ActiveRecord::Base.connection.columns(table_name).map {|c| [table_name, c.name].join('.') } | |
end.select { |c| c.ends_with?('_id') } | |
indexed_columns = tables.map do |table_name| | |
ActiveRecord::Base.connection.indexes(table_name).map do |index| | |
index.columns.map {|c| [table_name, c].join('.') } | |
end | |
end.flatten | |
unindexed_foreign_keys = (all_foreign_keys - indexed_columns) | |
if unindexed_foreign_keys.any? | |
warn "WARNING: The following foreign key columns don't have an index, which can hurt performance: #{ unindexed_foreign_keys.join(', ') }" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment