Skip to content

Instantly share code, notes, and snippets.

@vitobotta
Created September 13, 2011 16:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vitobotta/1214274 to your computer and use it in GitHub Desktop.
Save vitobotta/1214274 to your computer and use it in GitHub Desktop.
List unindexed foreign keys
namespace :indexes do
desc "List unindexed foreign keys"
task :unindexed_foreign_keys => :environment do
ActiveRecord::Base.logger = Logger.new('/dev/null')
missing_indexes = {}
connection = ActiveRecord::Base.connection
connection.tables.collect do |table|
columns = connection.columns(table).collect(&:name).select{ |column| column =~ /.*(_id|_type)$/ }
indexed_columns = connection.indexes(table).collect(&:columns).flatten.uniq
unindexed = columns - indexed_columns
missing_indexes[table] = unindexed unless unindexed.empty?
end
unless missing_indexes.empty?
puts "def self.up"
missing_indexes.each do |table, columns|
columns.each { |column| puts " add_index :#{table}, :#{column}" }
end
puts "end"
puts "def self.down"
missing_indexes.each do |table, columns|
columns.each { |column| puts " remove_index :#{table}, :#{column}" }
end
puts "end"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment