Docker images for postgres extended with management bash scripts.
1#!/usr/bin/env bash
2
3
4### Restore database from a backup.
5###
6### Parameters:
7### <1> filename of an existing backup.
8###
9### Usage:
10### $ docker-compose -f <environment>.yml (exec |run --rm) postgres restore <1>
11
12
13set -o errexit
14set -o pipefail
15set -o nounset
16
17
18working_dir="$(dirname ${0})"
19source "${working_dir}/_sourced/constants.sh"
20source "${working_dir}/_sourced/messages.sh"
21
22
23if [[ -z ${1+x} ]]; then
24 message_error "Backup filename is not specified yet it is a required parameter. Make sure you provide one and try again."
25 exit 1
26fi
27backup_filename="${BACKUP_DIR_PATH}/${1}"
28if [[ ! -f "${backup_filename}" ]]; then
29 message_error "No backup with the specified filename found. Check out the 'backups' maintenance script output to see if there is one and try again."
30 exit 1
31fi
32
33message_welcome "Restoring the '${POSTGRES_DB}' database from the '${backup_filename}' backup..."
34
35if [[ "${POSTGRES_USER}" == "postgres" ]]; then
36 message_error "Restoring as 'postgres' user is not supported. Assign 'POSTGRES_USER' env with another one and try again."
37 exit 1
38fi
39
40export PGHOST="${POSTGRES_HOST}"
41export PGPORT="${POSTGRES_PORT}"
42export PGUSER="${POSTGRES_USER}"
43export PGPASSWORD="${POSTGRES_PASSWORD}"
44export PGDATABASE="${POSTGRES_DB}"
45
46message_info "Dropping the database..."
47dropdb "${PGDATABASE}"
48
49message_info "Creating a new database..."
50createdb --owner="${POSTGRES_USER}"
51
52message_info "Applying the backup to the new database..."
53gunzip -c "${backup_filename}" | psql "${POSTGRES_DB}"
54
55message_success "The '${POSTGRES_DB}' database has been restored from the '${backup_filename}' backup."