class LolDba::MigrationFormatter

Public Class Methods

new(indexes) click to toggle source
# File lib/lol_dba/index_finding/migration_formatter.rb, line 3
def initialize(indexes)
  @indexes = indexes
end

Public Instance Methods

format_for_migration(missing_indexes) click to toggle source
# File lib/lol_dba/index_finding/migration_formatter.rb, line 16
def format_for_migration(missing_indexes)
  add = []
  missing_indexes.each do |table_name, keys_to_add|
    keys_to_add.each do |key|
      next if key.blank?
      add << format_index(table_name, key)
    end
  end
  add
end
format_index(table_name, key) click to toggle source
# File lib/lol_dba/index_finding/migration_formatter.rb, line 27
def format_index(table_name, key)
  if key.is_a?(Array)
    keys = key.collect { |col| ":#{col}" }
    "add_index :#{table_name}, [#{keys.join(', ')}]"
  else
    "add_index :#{table_name}, :#{key}"
  end
end
migration_instructions(formated_indexes) click to toggle source
# File lib/lol_dba/index_finding/migration_formatter.rb, line 36
    def migration_instructions(formated_indexes)
      <<-MIGRATION
* TIP: if you have a problem with the index name('index name too long'), you can
solve with the :name option. Something like :name => 'my_index'.
* run `rails g migration AddMissingIndexes` and add the following content:

    class AddMissingIndexes < ActiveRecord::Migration
      def change
        #{formated_indexes.sort.uniq.join("\n        ")}
      end
    end
MIGRATION
    end
puts_migration_content() click to toggle source
# File lib/lol_dba/index_finding/migration_formatter.rb, line 7
def puts_migration_content
  formated_indexes = format_for_migration(@indexes)
  if formated_indexes.blank?
    puts 'Yey, no missing indexes found!'
  else
    puts migration_instructions(formated_indexes)
  end
end