namespace :postgresql do

  desc 'Kills all processes connected to postgresql'
  task :kick_all => :environment do

    processes = ActiveRecord::Base.connection.execute(
      'SELECT usename, procpid FROM pg_stat_activity '+
      'WHERE datname = current_database() AND procpid <> pg_backend_pid();'
    )

    processes.each do |p|
      procpid = p['procpid']
      puts "killing process #{procpid}"
      system("sudo kill -9 #{procpid}")
    end
  end
end

