Sync Pantheon DB to local MySQL DB
On this page
At my day job we do heavy WordPress development work and we use Pantheon for hosting our sites.
Each Pantheon site has 3 environments: Dev, Test and Live.
When we deploy it goes to Dev and then we manually deploy to Test and then to Live.
We switch between projects a lot so sometimes I haven't touched a particular project in a while and my local environment does not reflect what is currently on Pantheon.
At the beginning I used to do the sync process manually by creating a DB backup and importing it locally via Tableplus but it was a tedious process.
So I decided to automate it by writing a script and I want to share it here:
#!/bin/bash
# Default values
PANTHEON_SITE=""
LOCAL_DB_NAME=""
ENVIRONMENT="live" # Default environment
DB_DUMP_FILE="$HOME/pantheon-local-copies/db/$PANTHEON_SITE-db.tgz" # Default dump file path
# Parse command line options
while [ "$#" -gt 0 ]; do
case "$1" in
--pantheon-site=*)
PANTHEON_SITE="${1#*=}"
;;
--local-db=*)
LOCAL_DB_NAME="${1#*=}"
;;
--env=*)
ENVIRONMENT="${1#*=}"
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
shift
done
# Check if required options are set
if [ -z "$PANTHEON_SITE" ] || [ -z "$LOCAL_DB_NAME" ]; then
echo "Usage: $0 --pantheon-site=<PANTHEON_SITE> --local-db=<LOCAL_DB_NAME> [--env=<ENVIRONMENT>]"
exit 1
fi
# Ensure PANTHEON_SITE is not empty
if [ -z "$PANTHEON_SITE" ]; then
echo "Error: PANTHEON_SITE is not set. Please provide a valid site name."
exit 1
fi
# Create a backup of the database
echo "Creating a backup of the $ENVIRONMENT database..."
terminus backup:create --element=db $PANTHEON_SITE.$ENVIRONMENT
echo "Downloading $ENVIRONMENT database from Pantheon..."
# Download the database from the specified environment
DB_DUMP_FILE="$HOME/pantheon-local-copies/db/$PANTHEON_SITE-db.tgz"
terminus backup:get --element=db --to=$DB_DUMP_FILE $PANTHEON_SITE.$ENVIRONMENT
MYSQL_USER="root"
MYSQL_PASSWORD="" # Assuming no password
DB_DUMP_FILE="$HOME/pantheon-local-copies/db/$PANTHEON_SITE-db.tgz"
# Check if the dump file exists before decompressing
if [ -f "$DB_DUMP_FILE" ]; then
echo "Decompressing database dump..."
gunzip -c $DB_DUMP_FILE > "${DB_DUMP_FILE%.tgz}.sql"
else
echo "Error: Database dump file not found at $DB_DUMP_FILE"
exit 1
fi
DB_SQL_FILE="${DB_DUMP_FILE%.tgz}.sql"
echo "Importing database into local MySQL..."
# Use mysql command to import the database
mysql -h 127.0.0.1 -P 3306 -u $MYSQL_USER $LOCAL_DB_NAME < $DB_SQL_FILE
echo "Cleaning up..."
# Remove the dump file after import
rm $DB_DUMP_FILE
rm $DB_SQL_FILE
echo "Database synchronization complete."
Then I add a command alias to my zsh settings
alias syncpdb="~/scripts/sync-db.sh"
And I run the command as the following
syncpdb --pantheon-site=testname --local-db=testname --env=dev