1#! /usr/bin/env bash
2# This script is used to migrate a postgres database from one server to another.
3# Usage: pgmigrate <source> <destination>
4# Example: pgmigrate postgres://user:pass@localhost:5432/source postgres://user:pass@localhost:5432/destination
5
6set -e
7
8if [ $# -ne 2 ]; then
9 echo "Usage: pgmigrate <source> <destination>"
10 exit 1
11fi
12
13SOURCE=$1
14DESTINATION=$2
15
16echo "Migrating from $SOURCE to $DESTINATION"
17
18echo "Dumping source database"
19pg_dump $SOURCE > /tmp/dump.sql
20
21if ! psql $DESTINATION -c "select 1" > /dev/null 2>&1; then
22 echo "Destination database does not exist. Creating it"
23 dbname=$(echo $DESTINATION | sed -e 's/.*\///')
24 dest=$(echo $DESTINATION | sed -e 's/\/[^/]*$//')
25 psql $dest -c "create database $dbname"
26fi
27
28echo "Restoring to destination database"
29psql $DESTINATION < /tmp/dump.sql
30
31echo "Cleaning up"
32rm /tmp/dump.sql
33
34echo "Done"
35