Created
October 25, 2013 16:53
-
-
Save alistairholt/7157929 to your computer and use it in GitHub Desktop.
Rails & Postgres: Better dropping of the database – https://coderwall.com/p/qtkppg
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
pgdrop() { | |
RAILS_ENV=$1 | |
: ${RAILS_ENV:="development"} | |
RUBY_SCRIPT=$(cat <<SCRIPT | |
db_config_path = File.expand_path("config/database.yml", Dir.getwd) | |
abort 'NO_CONFIG' unless File.exists?(db_config_path) | |
db_config = YAML.load(File.open(db_config_path))["$RAILS_ENV"] | |
abort 'NO_POSTGRES' unless db_config["adapter"] == "postgresql" | |
abort db_config["database"] | |
SCRIPT) | |
DB_NAME=$(ruby -ryaml -e $RUBY_SCRIPT 2>&1) | |
if [[ $DB_NAME = 'NO_CONFIG' ]] | |
then | |
echo "No database config file could be found (./config/database.yml)\nMake sure you're running this command from the root of your Rails app" | |
return 0 | |
elif [[ $DB_NAME = 'NO_POSTGRES' ]] | |
then | |
echo "Oops! It doesn't look like your using Postgres for your database" | |
return 0 | |
fi | |
# Assuming the latest verison of Postgres (9.2+) | |
psql -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = \"$DB_NAME\" AND pid <> pg_backend_pid();" > /dev/null 2>&1 | |
RESULT=$(psql -c "DROP DATABASE IF EXISTS \"$DB_NAME\";" 2>&1) | |
if [[ $RESULT == *'does not exist'* ]]; then | |
echo "Database doesn't exist! Nothing to do." | |
else | |
echo 'Database dropped!' | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment