Skip to content

Instantly share code, notes, and snippets.

@kuczmama
Created May 21, 2019 03:03
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 kuczmama/6c9a76c223e5f73c1c40ab2a782e6b5e to your computer and use it in GitHub Desktop.
Save kuczmama/6c9a76c223e5f73c1c40ab2a782e6b5e to your computer and use it in GitHub Desktop.
Heroku to RDS migration script from single to multi-tenant
#/bin/sh
usage() { echo "Usage: $0 APP_NAME DESTINATION SCHEMA_NAME" 1>&2; exit 1; }
if [ "$#" -ne 3 ]; then
usage
fi
function pathParts() {
url=$1
proto="`echo $url | grep '://' | sed -e's,^\(.*://\).*,\1,g'`"
# remove the protocol
url=`echo $url | sed -e s,$proto,,g`
# extract the user and password (if any)
userpass="`echo $url | grep @ | cut -d@ -f1`"
pass=`echo $userpass | grep : | cut -d: -f2`
if [ -n "$pass" ]; then
user=`echo $userpass | grep : | cut -d: -f1`
else
user=$userpass
fi
# extract the host -- updated
hostport=`echo $url | sed -e s,$userpass@,,g | cut -d/ -f1`
port=`echo $hostport | grep : | cut -d: -f2`
if [ -n "$port" ]; then
host=`echo $hostport | grep : | cut -d: -f1`
else
host=$hostport
fi
# extract the path (if any)1
path="`echo $url | grep / | cut -d/ -f2-`"
}
APP_NAME=$1
DEST=$2
SCHEMA_NAME=$3
pathParts $DEST
DESTINATION_DB_NAME="$path"
DATE=$(date +"%Y-%m-%d-%H%M")
echo "Backing up $APP_NAME"
backup_filename="$APP_NAME-$DATE.backup.dump"
heroku run 'pg_dump $DATABASE_URL --format custom --no-owner' -a $APP_NAME > "$backup_filename"
echo "ALTER SCHEMA public RENAME TO $SCHEMA_NAME in source"
schema_dump_filename="$SCHEMA_NAME-$APP_NAME-$DATE.schema.dump"
heroku pg:psql -c "ALTER SCHEMA public RENAME TO $SCHEMA_NAME" -a $APP_NAME
echo "CREATE SCHEMA IF NOT EXISTS $SCHEMA_NAME in destination"
psql -d $DEST -c "CREATE SCHEMA IF NOT EXISTS $SCHEMA_NAME"
echo "Backup source to $schema_dump_filename"
heroku run "pg_dump \$DATABASE_URL --format custom --schema $SCHEMA_NAME --no-owner" -a $APP_NAME > "$schema_dump_filename"
echo "put source schema back to public"
heroku pg:psql -c "ALTER SCHEMA $SCHEMA_NAME RENAME TO public" -a $APP_NAME
echo "Restore $SCHEMA_NAME to $DEST"
/usr/lib/postgresql/10/bin/pg_restore --format custom --schema $SCHEMA_NAME -d $DEST "$schema_dump_filename"
echo "Creating Tenant row"
psql -d $DEST -c "INSERT INTO public.tenants (name, created_at, updated_at) VALUES ('$SCHEMA_NAME', now(), now())"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment