namespace :db do
  desc 'Optimize all tables'
  task :optimize => :load_config do
    ActiveRecord::Base.establish_connection
    pids = []

    # Run it in parallel, one process per table.

    Signal.trap 'SIGINT' do
      pids.each do |pid|
        Process.kill('KILL', pid)
        exit 1
      end
    end

    ActiveRecord::Base.connection.select_values('SHOW TABLES').each do |table|
      pids << Process.fork do
        ActiveRecord::Base.establish_connection

        puts " * Start optimizing #{table}"
        ActiveRecord::Base.connection.execute("OPTIMIZE TABLE `#{table}`")
        puts " * Done optimizing #{table}"
      end
    end

    Process.waitall
    puts " * Done all"
  end
end
