Skip to content

Instantly share code, notes, and snippets.

@rvillas
Created June 10, 2015 00:10
Show Gist options
  • Save rvillas/51ec4722f79c42b2619c to your computer and use it in GitHub Desktop.
Save rvillas/51ec4722f79c42b2619c to your computer and use it in GitHub Desktop.

Revisions

  1. rvillas created this gist Jun 10, 2015.
    19 changes: 19 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    # http://stackoverflow.com/questions/5108876/kill-a-postgresql-session-connection
    namespace :db do
    desc "Fix 'database is being accessed by other users'"
    task :terminate => :environment do
    ActiveRecord::Base.connection.execute <<-SQL
    SELECT
    pg_terminate_backend(pid)
    FROM
    pg_stat_activity
    WHERE
    -- don't kill my own connection!
    pid <> pg_backend_pid()
    -- don't kill the connections to other databases
    AND datname = '#{ActiveRecord::Base.connection.current_database}';
    SQL
    end
    end

    Rake::Task["db:drop"].enhance ["db:terminate"]