Created
          October 28, 2014 09:48 
        
      - 
      
 - 
        
Save maxd/766f86648010270b2b5d to your computer and use it in GitHub Desktop.  
    Rake task for drop active connections to PostgreSQL database
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | namespace :db do | |
| namespace :drop do | |
| task connections: :environment do | |
| begin | |
| database = ActiveRecord::Base.connection.current_database | |
| ActiveRecord::Base.connection.execute(<<-SQL) | |
| SELECT pg_terminate_backend(pg_stat_activity.pid) | |
| FROM pg_stat_activity | |
| WHERE pg_stat_activity.datname = '#{database}' AND pid <> pg_backend_pid(); | |
| SQL | |
| rescue ActiveRecord::NoDatabaseError | |
| # Do nothing | |
| end | |
| end | |
| end | |
| end | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | namespace :db do | |
| namespace :drop do | |
| task connections: :environment do | |
| database = Rails.configuration.database_configuration[Rails.env]['database'] | |
| begin | |
| ActiveRecord::Base.connection.execute(<<-SQL) | |
| SELECT pg_terminate_backend(pg_stat_activity.pid) | |
| FROM pg_stat_activity | |
| WHERE pg_stat_activity.datname = '#{database}' AND pid <> pg_backend_pid(); | |
| SQL | |
| rescue ActiveRecord::NoDatabaseError | |
| # Do nothing | |
| end | |
| end | |
| end | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment