Skip to content

Instantly share code, notes, and snippets.

@yknx4
Created October 27, 2016 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yknx4/2023e747e21d02e09d15594a90f5bac9 to your computer and use it in GitHub Desktop.
Save yknx4/2023e747e21d02e09d15594a90f5bac9 to your computer and use it in GitHub Desktop.
#!/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