Created
October 25, 2011 19:36
-
-
Save codeprimate/1313968 to your computer and use it in GitHub Desktop.
Rails Rake task to add indexes on columns that are 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
# Rails Rake task to search all database tables and add indexes on columns that are foreign keys, or match the "indexed_columns" variable | |
desc 'Add missing indexes' | |
task :index_tables => :environment do | |
indexed_columns = ['code', 'name', 'updated_at', 'created_at'] | |
tables = ActiveRecord::Base.connection.select_values('show tables') | |
tables.each do |t| | |
columns = ActiveRecord::Base.connection.select_values("describe #{t}") | |
keys = columns.select{|k| k.match(/_id$/) || indexed_columns.include?(k)} | |
indexes = [] | |
ActiveRecord::Base.connection.execute("show indexes in #{t}").each do |i| | |
indexes << i[4] | |
end | |
create_indexes = keys - indexes | |
inserts = create_indexes.map{|i| "CREATE INDEX #{i} ON #{t} (#{i})"} | |
puts " * Creating indexes on #{t}" | |
puts " - Found: #{indexes.sort.join(', ')}" | |
if inserts.empty? | |
puts " - No indexes will be added" | |
end | |
inserts.each do |i| | |
print " - " + i | |
begin | |
ActiveRecord::Base.connection.execute(i) | |
rescue => e | |
puts "ERROR!" | |
end | |
puts | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment