Created
September 13, 2011 16:42
-
-
Save vitobotta/1214274 to your computer and use it in GitHub Desktop.
List unindexed foreign keys
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
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