Skip to content

Instantly share code, notes, and snippets.

@taiar
Created November 15, 2019 12:03
Show Gist options
  • Save taiar/5345b5fcd53504f17dee1e220e247cdb to your computer and use it in GitHub Desktop.
Save taiar/5345b5fcd53504f17dee1e220e247cdb to your computer and use it in GitHub Desktop.
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