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
6
set -e
7
8
if [ $# -ne 2 ]; then
9
  echo "Usage: pgmigrate <source> <destination>"
10
  exit 1
11
fi
12
13
SOURCE=$1
14
DESTINATION=$2
15
16
echo "Migrating from $SOURCE to $DESTINATION"
17
18
echo "Dumping source database"
19
pg_dump $SOURCE > /tmp/dump.sql
20
21
if ! 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"
26
fi
27
28
echo "Restoring to destination database"
29
psql $DESTINATION < /tmp/dump.sql
30
31
echo "Cleaning up"
32
rm /tmp/dump.sql
33
34
echo "Done"
35
Paste69 Logo