Skip to content

Commit 4c9938c

Browse files
committed
feat: backup postgres databases owned by a specific user if PGDATABASE is not set and pg_dump is being used
1 parent 6926f45 commit 4c9938c

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

postgres-logical-backup/dump.sh

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ IFS=$'\n\t'
77
# PGHOST PGPASSWORD
88

99
ALL_DB_SIZE_QUERY="select sum(pg_database_size(datname)::numeric) from pg_database;"
10+
1011
PG_BIN=/usr/lib/postgresql/$PG_VERSION/bin
1112
DUMP_SIZE_COEFF=5
1213
ERRORCOUNT=0
@@ -16,16 +17,16 @@ LOGICAL_BACKUP_S3_RETENTION_TIME=${LOGICAL_BACKUP_S3_RETENTION_TIME:=""}
1617
LOGICAL_BACKUP_S3_ENDPOINT=${LOGICAL_BACKUP_S3_ENDPOINT:-}
1718

1819
function estimate_size {
19-
"$PG_BIN"/psql -tqAc "${ALL_DB_SIZE_QUERY}"
20+
psql -tqAc "${ALL_DB_SIZE_QUERY}"
2021
}
2122

2223
function dump {
2324
echo "Taking dump from ${PGHOST} using ${USE_PG_DUMP:-pg_dumpall}"
2425

2526
if [[ "${USE_PG_DUMP:-}" == "true" ]]; then
26-
"$PG_BIN"/pg_dump
27+
pg_dump --verbose
2728
else
28-
"$PG_BIN"/pg_dumpall --exclude-database='postgres'
29+
pg_dumpall --exclude-database='postgres' --verbose
2930
fi
3031
}
3132

@@ -105,7 +106,7 @@ function aws_upload {
105106
[[ ! -z "${LOGICAL_BACKUP_S3_REGION}" ]] && args+=("--region=${LOGICAL_BACKUP_S3_REGION}")
106107

107108
echo "Uploading dump to s3"
108-
aws s3 cp - "$PATH_TO_BACKUP" "${args[@]//\'/}"
109+
aws s3 cp - "$PATH_TO_BACKUP" "${args[@]}"
109110
}
110111

111112
function gcs_upload {
@@ -130,6 +131,18 @@ if [ "$LOGICAL_BACKUP_PROVIDER" == "az" ]; then
130131
dump | compress > /tmp/azure-backup.sql.gz
131132
az_upload /tmp/azure-backup.sql.gz
132133
else
134+
135+
# Backup all the databases owned by the user if PGDATABASE is not set
136+
if [[ "${USE_PG_DUMP:-}" == "true" ]] && [[ -z "${PGDATABASE:-}" ]]; then
137+
GET_DATABASE_LIST_FOR_USER_QUERY="SELECT datname FROM pg_database WHERE datistemplate = false AND datname = '$PGUSER';"
138+
DATABASES=$(psql -U postgres -tqAc $GET_DATABASE_LIST_FOR_USER_QUERY)
139+
for DB in $DATABASES; do
140+
echo "Backing up $DB"
141+
# We set PGDATABASE locally for each run
142+
PGDATABASE=$DB dump | compress | upload
143+
done
144+
fi
145+
133146
dump | compress | upload
134147
[[ ${PIPESTATUS[0]} != 0 || ${PIPESTATUS[1]} != 0 || ${PIPESTATUS[2]} != 0 ]] && (( ERRORCOUNT += 1 ))
135148
set +x

0 commit comments

Comments
 (0)