Skip to content

Instantly share code, notes, and snippets.

@cmaitchison
Forked from tommeier/seqeul.rake
Created May 13, 2011 12:42
Show Gist options
  • Save cmaitchison/970459 to your computer and use it in GitHub Desktop.
Save cmaitchison/970459 to your computer and use it in GitHub Desktop.
Close postgres open connections before running test suite
task 'db:test:prepare' => :close_postgres_connections
task :close_postgres_connections => :environment do
#Kill any other open connections on the test db
db_adapter = defined?(::ActiveRecord::Base) ? ActiveRecord::Base.connection : nil
db_adapter ||= defined?(::Sequel::Model) ? ::Sequel::Model.db : nil
if Rails.env.test? && db_adapter
db_config = Rails.configuration.database_configuration[Rails.env].symbolize_keys
begin
#Will only work on Postgres > 8.4
::Sequel::Model.db.execute <<-SQL.gsub(/^\s{6}/,'')
SELECT COUNT(pg_terminate_backend(procpid))
FROM pg_stat_activity
WHERE datname = '#{db_config[:database]}';
SQL
rescue => e
#Will raise an error as it kills existing process running this command
#Seems to be only way to ensure *all* test connections are closed
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment