Created
October 27, 2016 21:46
-
-
Save yknx4/2023e747e21d02e09d15594a90f5bac9 to your computer and use it in GitHub Desktop.
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
#!/bin/sh | |
# --- Command line | |
previous_head="$1" | |
new_head="$2" | |
branch_checkout="$3" | |
# --- Constants | |
separator="/" | |
master_branch="master" | |
# --- Functions | |
database_exists () { | |
name=${1:0:63} | |
return `psql -U postgres -lqtA | cut -d\| -f1 | grep -qFx "$name"` | |
} | |
kill_connections() { | |
psql -U postgres -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '$database_name' AND pid <> pg_backend_pid();" > /dev/null | |
} | |
duplicate_database_to() { | |
name=${1:0:63} | |
echo "Creating $name from $database_name" | |
createdb -T $database_name $name | |
} | |
drop_database() { | |
name=${1:0:63} | |
echo "Deleting existing $name" | |
dropdb -U postgres "$name" | |
} | |
rename_database() { | |
old_name=${1:0:63} | |
new_name=${2:0:63} | |
# echo "Renaming $old_name to $new_name" | |
psql -U postgres -c "SET standard_conforming_strings=on;" -q -b | |
psql -U postgres -c "ALTER DATABASE \"$old_name\" RENAME TO \"$new_name\";" -q -e | |
psql -U postgres -c "SET standard_conforming_strings=off;" -q -b | |
} | |
alias branch_name='git name-rev --name-only' | |
# --- Variables | |
previous_branch=`branch_name $previous_head` | |
new_branch=`git branch | grep -e "^*" | cut -d' ' -f 2` | |
database_name="db/beanstack_development" | |
old_database=$database_name$separator$previous_branch | |
new_database=$database_name$separator$new_branch | |
main_backup=$database_name$separator$master_branch | |
# --- Script | |
# --- Exit script if it is not a branch change | |
if [ $branch_checkout -eq 0 ]; then | |
exit 0 | |
fi | |
echo "Switching from $previous_branch to $new_branch" | |
echo "Killing existing connections to $database_name" | |
kill_connections | |
if ! database_exists $main_backup; then | |
duplicate_database_to $main_backup | |
fi | |
if [ "$previous_branch" == "$new_branch" ]; then | |
exit 0 | |
fi | |
if [ "$previous_branch" != "$master_branch" ]; then | |
if database_exists $old_database; then | |
drop_database $old_database | |
fi | |
if database_exists $new_database; then | |
rename_database $database_name $old_database | |
else | |
duplicate_database_to $old_database | |
fi | |
fi | |
if [ "$previous_branch" != "$new_branch" ]; then | |
if database_exists $new_database; then | |
if database_exists $database_name; then | |
drop_database $database_name | |
fi | |
rename_database $new_database $database_name | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment