Killing db connections softly with rake tasks

I literally couldn't decide what pun to use here: drop it like it's hot, killing me softly, or something about waiting for the (data)base to drop. Anyway, I frequently, and in every project, have this need, so this time, I will post it somewhere I won't forget it.

When I need to search for it next time, I will have solid search functionality on my blog!
# frozen_string_literal: true

namespace :db do
  desc "Terminate all connections to the development databases"
  task terminate_connections: :environment do
    if Rails.env.local?
      database_name = ActiveRecord::Base.connection_db_config.database
      ActiveRecord::Base.connection.execute(<<~SQL.squish)
        SELECT pg_terminate_backend(pg_stat_activity.pid)
          FROM pg_stat_activity
         WHERE pg_stat_activity.datname = '#{database_name}'
           AND pid <> pg_backend_pid();
      SQL
    end
  end
end

Rake::Task["db:drop"].enhance(["db:terminate_connections"])
The important thing here is to enhance it because that ensures the order is correct. If you instead open the db:drop task and invoke the task there, it will fail because that runs after. 

Comments

No comments yet. Be the first to comment!
Your email address will be verified before your first comment is posted. It will not be displayed publicly.
Legal Information
By commenting, you agree to our Privacy Policy and Terms of Service.