60 lines
1.9 KiB
Bash
60 lines
1.9 KiB
Bash
|
|
#!/usr/bin/env bash
|
||
|
|
# Restore a platform.db or messenger.db dump into a SCRATCH database.
|
||
|
|
# DOES NOT touch the live DB by default — restores into a uniquely-named
|
||
|
|
# database so you can verify the dump is valid before any cutover.
|
||
|
|
#
|
||
|
|
# Usage:
|
||
|
|
# ./scripts/restore-pg.sh <dump-file> [--to=<dbname>]
|
||
|
|
#
|
||
|
|
# Example:
|
||
|
|
# ./scripts/restore-pg.sh /mnt/bigdisk/atlilith-backups/pg/platform_20260516_030000.sql.zst
|
||
|
|
# → restores into "platform_restore_20260516_185500"
|
||
|
|
|
||
|
|
set -euo pipefail
|
||
|
|
|
||
|
|
DUMP="${1:?usage: $0 <dump-file> [--to=<dbname>]}"
|
||
|
|
TARGET_DB=""
|
||
|
|
|
||
|
|
for arg in "$@"; do
|
||
|
|
case "$arg" in
|
||
|
|
--to=*) TARGET_DB="${arg#*=}" ;;
|
||
|
|
esac
|
||
|
|
done
|
||
|
|
|
||
|
|
if [ ! -f "$DUMP" ]; then
|
||
|
|
echo "error: dump not found: $DUMP" >&2
|
||
|
|
exit 1
|
||
|
|
fi
|
||
|
|
|
||
|
|
# Default target: <original-dbname>_restore_<timestamp>
|
||
|
|
if [ -z "$TARGET_DB" ]; then
|
||
|
|
base=$(basename "$DUMP" .sql.zst)
|
||
|
|
original_db="${base%%_*}"
|
||
|
|
TARGET_DB="${original_db}_restore_$(date +%Y%m%d_%H%M%S)"
|
||
|
|
fi
|
||
|
|
|
||
|
|
# Hard guard: refuse to write into a DB that already exists with rows.
|
||
|
|
existing_rows=$(psql -h localhost -p 25440 -U platform -tAc \
|
||
|
|
"SELECT count(*) FROM pg_database WHERE datname='${TARGET_DB}';" 2>/dev/null || echo 0)
|
||
|
|
if [ "$existing_rows" -gt 0 ]; then
|
||
|
|
echo "error: database '${TARGET_DB}' already exists. Choose a different --to= name." >&2
|
||
|
|
exit 1
|
||
|
|
fi
|
||
|
|
|
||
|
|
echo "==> creating scratch database: ${TARGET_DB}"
|
||
|
|
psql -h localhost -p 25440 -U platform -c "CREATE DATABASE \"${TARGET_DB}\";"
|
||
|
|
|
||
|
|
echo "==> restoring ${DUMP} → ${TARGET_DB}"
|
||
|
|
zstd -dc "$DUMP" | psql -h localhost -p 25440 -U platform -d "${TARGET_DB}" -v ON_ERROR_STOP=1
|
||
|
|
|
||
|
|
echo "==> verification: row counts on key tables"
|
||
|
|
psql -h localhost -p 25440 -U platform -d "${TARGET_DB}" -c "
|
||
|
|
SELECT 'users' AS table, count(*) FROM users
|
||
|
|
UNION ALL SELECT 'orgs', count(*) FROM orgs
|
||
|
|
UNION ALL SELECT 'org_members', count(*) FROM org_members;
|
||
|
|
"
|
||
|
|
|
||
|
|
echo ""
|
||
|
|
echo "done. scratch database: ${TARGET_DB}"
|
||
|
|
echo "to drop: psql -h localhost -p 25440 -U platform -c 'DROP DATABASE \"${TARGET_DB}\"'"
|