Created
March 23, 2024 22:52
-
-
Save flipbit03/6631e740f366cbffa1ed21fb2768b3ae to your computer and use it in GitHub Desktop.
Restore a dump to a PG database, using Docker to use the exact version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # Function to check if an environment variable is set | |
| check_env_variable() { | |
| local var_name="$1" | |
| local var_desc="$2" | |
| if [ -z "${!var_name}" ]; then | |
| echo "Error: '${var_name}' environment variable is not set. Please set it to ${var_desc}." | |
| exit 1 | |
| fi | |
| } | |
| # Check required environment variables | |
| check_env_variable "PG_VERSION" "specify the PostgreSQL version" | |
| check_env_variable "DB_USER" "specify the database user" | |
| check_env_variable "DB_PASSWORD" "specify the database password" | |
| check_env_variable "DB_HOST" "specify the database host" | |
| check_env_variable "DB_PORT" "specify the database port" | |
| check_env_variable "DB_NAME" "specify the database name" | |
| check_env_variable "BACKUP_FILE" "specify the filename of the backup file" | |
| # Get current user's ID and group ID | |
| CURRENT_UID=$(id -u) | |
| CURRENT_GID=$(id -g) | |
| # Run the PostgreSQL container to restore the database | |
| docker run \ | |
| --rm \ | |
| --volume=$(pwd):/host \ | |
| -e PGPASSWORD="$DB_PASSWORD" \ | |
| -e CURRENT_UID="$CURRENT_UID" \ | |
| -e CURRENT_GID="$CURRENT_GID" \ | |
| --user="$CURRENT_UID:$CURRENT_GID" \ | |
| --network host \ | |
| postgres:${PG_VERSION} \ | |
| pg_restore -v -U "$DB_USER" -h "$DB_HOST" -p "$DB_PORT" -d "$DB_NAME" -Fc "/host/$BACKUP_FILE" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment