Skip to content

Instantly share code, notes, and snippets.

@jtrim
Last active August 29, 2015 14:00
Show Gist options
  • Save jtrim/11217280 to your computer and use it in GitHub Desktop.
Save jtrim/11217280 to your computer and use it in GitHub Desktop.
Duplicates a database from the master version. Useful for having different databases per branch in a codebase.
<%
current_branch_name ||= begin
`/usr/bin/env git branch` =~ /^\*\s+(.*)$/
current_branch_name = $1.gsub('-', '_')
end
%>
development:
adapter: postgresql
database: myapp_development_<%= current_branch_name %>
username: myapp
host: localhost
test:
adapter: postgresql
database: myapp_test_<%= current_branch_name %>
database: myapp
host: localhost
#!/usr/bin/env bash
CURRENT_DB_NAME=`/usr/bin/env ruby <<RUBY
require 'erb'
require 'yaml'
db_config_str = ERB.new(File.read('config/database.yml')).result
db_config = YAML.load(db_config_str)
current_db_name = db_config["development"]["database"]
print current_db_name
RUBY`
if [[ $1 == "" ]]; then
DB_USERNAME=`/usr/bin/env ruby <<RUBY
require 'erb'
require 'yaml'
db_config_str = ERB.new(File.read('config/database.yml')).result
db_config = YAML.load(db_config_str)
user_name = db_config["development"]["username"]
print user_name
RUBY`
SOURCE_DB_NAME=`/usr/bin/env ruby <<RUBY
require 'erb'
require 'yaml'
current_branch_name = "master"
db_config_str = ERB.new(File.read('config/database.yml')).result(binding)
db_config = YAML.load(db_config_str)
current_db_name = db_config["development"]["database"]
print current_db_name
RUBY`
else
SOURCE_DB_NAME=$1
DB_USERNAME=$2
fi
if [[ $2 == "" && $DB_USERNAME == "" ]]; then
echo "Need a source database name and a PG user"
echo "Usage: duplicate_db <SOURCE_DB_NAME> <DB_USERNAME>"
exit 1
fi
# echo "Destination database name (default: ${CURRENT_DB_NAME}):"
# read DESTINATION_DB_NAME
# if [[ $DESTINATION_DB_NAME =~ "^ *$" || $DESTINATION_DB_NAME == "" ]]; then
# DESTINATION_DB_NAME=$CURRENT_DB_NAME
# fi
DESTINATION_DB_NAME=$CURRENT_DB_NAME
echo "Copying the contents of '${SOURCE_DB_NAME}' into '${DESTINATION_DB_NAME}' as user '${DB_USERNAME}'."
echo "Are you sure? [yn]"
read PROCEED
if [[ $PROCEED != "y" ]]; then
echo "Aborting."
exit 2
fi
dropdb --if-exists -U $DB_USERNAME $DESTINATION_DB_NAME
createdb -U $DB_USERNAME $DESTINATION_DB_NAME
pg_dump -x --no-owner -U $DB_USERNAME $SOURCE_DB_NAME | psql -U $DB_USERNAME -d $DESTINATION_DB_NAME
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment