daily pastebin goal
75%
SHARE
TWEET

Untitled

a guest Apr 16th, 2018 49 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. namespace :db do
  2.   desc "LOADER: Discover indexes etc that might be good to add"
  3.   task :inspect => :environment do
  4.     cnx = ActiveRecord::Base.connection
  5.     cnx.tables.each do |table|
  6.       puts "# #{table}"
  7.       puts '# ==='
  8.       begin
  9.         klass = table.singularize.camelize.constantize
  10.       rescue
  11.         puts "# uninitialized constant #{table.singularize.camelize}, consider dropping #{table}"
  12.         puts "# drop_table #{table}"
  13.         puts ""
  14.         next
  15.       end
  16.      
  17.       puts '# indexes'
  18.       puts '==='
  19.       indexes = cnx.execute("show indexes from #{table};")
  20.       index_names = []
  21.       indexes.each do |r|
  22.         index_names << r[4]
  23.         puts "#" + r.inspect unless r[2] == "PRIMARY"
  24.       end
  25.      
  26.       suggested_indexes = []
  27.       puts "#   columns"
  28.       puts "#   ==="
  29.       klass.columns.each do |column|
  30.         gap = " " * (30 - column.name.length)
  31.         puts "#     #{column.name} #{gap} #{column.sql_type}"
  32.         if !index_names.include?(column.name)
  33.           suggested_indexes << column
  34.         end
  35.       end
  36.       puts ""
  37.      
  38.       puts "#   suggested indexes"
  39.       puts "#   ==="
  40.      
  41.       suggested_indexes.each do |index|
  42.         line = "     add_index :#{table}, :#{index.name}"
  43.         puts index.name =~ /_type$|type$|_id|_at$|_on/ ? "#{line}" : "##{line}"
  44.       end
  45.       puts ""
  46.      
  47.     end
  48.   end
  49. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top