Skip to content

Instantly share code, notes, and snippets.

@jameswalton
Last active December 14, 2015 23:49
Show Gist options
  • Save jameswalton/5168925 to your computer and use it in GitHub Desktop.
Save jameswalton/5168925 to your computer and use it in GitHub Desktop.
Checks for database tables that have unindexed columns, and suggests how it can be remedied.
namespace :db do
desc "Output information about the indexes of a database"
task indexes: :environment do
connection = ActiveRecord::Base.connection
tables = {}
columns = []
indexed_columns = []
unindexed_columns = []
connection.tables.collect do |table|
table_columns = connection.columns(table).collect(&:name).select { |column| column.ends_with?("_id" || column.ends_with("_type")) }
table_indexed_columns = connection.indexes(table).collect(&:columns).flatten.uniq
table_unindexed_columns = table_columns - table_indexed_columns
unindexed_columns << table_unindexed_columns
tables[table.to_sym] = table_unindexed_columns if table_unindexed_columns.any?
end
unless tables.empty?
tables.each_pair do |k, v|
puts "#{k} has the following unindexed columns: #{v.join(", ")}"
end
puts "To add these index, paste the following into a migration file:\n\n"
puts "def up"
tables.each_pair do |k, v|
v.each do |value|
puts " add_index :#{k}, :#{value}"
end
end
puts "end\n\n"
puts "def down"
tables.each_pair do |k, v|
v.each do |value|
puts " remove_index :#{k}, :#{value}"
end
end
puts "end"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment