Skip to content

Instantly share code, notes, and snippets.

@lucianghinda
Created October 11, 2018 03:17
Show Gist options
  • Save lucianghinda/dd9045af4fcbd99282324e4b49570aa9 to your computer and use it in GitHub Desktop.
Save lucianghinda/dd9045af4fcbd99282324e4b49570aa9 to your computer and use it in GitHub Desktop.
Enhance Migration to Check for Foreign Keys
# 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