Created
November 15, 2019 12:03
-
-
Save taiar/5345b5fcd53504f17dee1e220e247cdb to your computer and use it in GitHub Desktop.
Find missing db index on rails application (https://alexpeattie.com/blog/stop-forgetting-foreign-key-indexes-in-rails-post-migration-script)
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
| 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