Last active
May 31, 2018 20:28
-
-
Save rob-murray/eed9fc05e42b2c5e591f1a5e9da975a3 to your computer and use it in GitHub Desktop.
Postgres: Kill and block incoming connections and then drop the current environment's database. ⚠️ :hack:
This file contains 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
desc "Kill and block incoming connections and then drop the current environment's database." | |
task "db:force_drop" => "environment" do | |
if Rails.env.production? && ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"] !~ /true|1/ | |
raise "Cannot drop the production database. Disable this with 'DISABLE_DATABASE_ENVIRONMENT_CHECK=true'" | |
end | |
db_config = Rails.configuration.database_configuration[Rails.env] | |
db_name = db_config.fetch("database") | |
kill_postgres_connections_sql = <<-SQL | |
SELECT pg_terminate_backend(pg_stat_activity.pid) | |
FROM pg_stat_activity | |
WHERE pg_stat_activity.datname = '#{db_name}'; | |
SQL | |
block_postgres_connections_sql = <<-SQL | |
UPDATE pg_catalog.pg_database | |
SET datallowconn=false WHERE datname='#{db_name}'; | |
SQL | |
enable_postgres_connections_sql = <<-SQL | |
UPDATE pg_catalog.pg_database | |
SET datallowconn=true WHERE datname='#{db_name}'; | |
SQL | |
ActiveRecord::Base.establish_connection( | |
db_config.merge("database" => "postgres", "schema_search_path" => "public") | |
) | |
begin | |
ActiveRecord::Base.connection.execute(block_postgres_connections_sql) | |
ActiveRecord::Base.connection.execute(kill_postgres_connections_sql) | |
ActiveRecord::Base.connection.drop_database(db_name) | |
ensure | |
ActiveRecord::Base.connection.execute(enable_postgres_connections_sql) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment