Skip to content

Commit a40100f

Browse files
committed
Create sync-db.sh
1 parent 3dd43ba commit a40100f

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

scripts/sync-db.sh

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/bin/bash
2+
# Sync production PostgreSQL database to local instance
3+
# Usage: ./scripts/sync-db.sh
4+
# Requires: TECHSTACKS_DB_PROD env var with .NET connection string
5+
# e.g. Server=host;Port=5433;User Id=user;Password=pass;Database=dbname
6+
7+
set -euo pipefail
8+
9+
if [ -z "${TECHSTACKS_DB_PROD:-}" ]; then
10+
echo "Error: TECHSTACKS_DB_PROD environment variable is not set"
11+
echo "Expected .NET connection string format:"
12+
echo " Server=host;Port=5433;User Id=user;Password=pass;Database=dbname"
13+
exit 1
14+
fi
15+
16+
# Parse .NET connection string
17+
parse_connstr() {
18+
echo "$TECHSTACKS_DB_PROD" | tr ';' '\n' | grep -i "^$1=" | head -1 | cut -d'=' -f2-
19+
}
20+
21+
REMOTE_HOST=$(parse_connstr "Server")
22+
REMOTE_PORT=$(parse_connstr "Port")
23+
REMOTE_USER=$(parse_connstr "User Id")
24+
REMOTE_PASS=$(parse_connstr "Password")
25+
REMOTE_DB=$(parse_connstr "Database")
26+
27+
REMOTE_PORT="${REMOTE_PORT:-5432}"
28+
29+
# Local
30+
LOCAL_HOST="localhost"
31+
LOCAL_PORT="5432"
32+
LOCAL_USER="techstacks"
33+
LOCAL_DB="techstacks"
34+
35+
DUMP_FILE="/tmp/techstacks-prod-dump.sql"
36+
37+
echo "==> Dumping production database from ${REMOTE_HOST}:${REMOTE_PORT}..."
38+
PGPASSWORD="$REMOTE_PASS" pg_dump \
39+
-h "$REMOTE_HOST" \
40+
-p "$REMOTE_PORT" \
41+
-U "$REMOTE_USER" \
42+
-d "$REMOTE_DB" \
43+
--no-owner \
44+
--no-acl \
45+
-F plain \
46+
-f "$DUMP_FILE"
47+
48+
echo "==> Dump complete: $(du -h "$DUMP_FILE" | cut -f1)"
49+
50+
echo "==> Dropping and recreating local database..."
51+
PGPASSWORD="${LOCAL_PGPASSWORD:-techstacks}" dropdb \
52+
-h "$LOCAL_HOST" \
53+
-p "$LOCAL_PORT" \
54+
-U "$LOCAL_USER" \
55+
--if-exists \
56+
"$LOCAL_DB"
57+
58+
PGPASSWORD="${LOCAL_PGPASSWORD:-techstacks}" createdb \
59+
-h "$LOCAL_HOST" \
60+
-p "$LOCAL_PORT" \
61+
-U "$LOCAL_USER" \
62+
"$LOCAL_DB"
63+
64+
echo "==> Restoring dump to local database..."
65+
PGPASSWORD="${LOCAL_PGPASSWORD:-techstacks}" psql \
66+
-h "$LOCAL_HOST" \
67+
-p "$LOCAL_PORT" \
68+
-U "$LOCAL_USER" \
69+
-d "$LOCAL_DB" \
70+
-f "$DUMP_FILE" \
71+
-v ON_ERROR_STOP=1 2>&1 | grep -v "^SET\|^COMMENT\|^ALTER\|^CREATE\|^$" || true
72+
73+
echo "==> Verifying restore..."
74+
TABLE_COUNT=$(PGPASSWORD="${LOCAL_PGPASSWORD:-techstacks}" psql \
75+
-h "$LOCAL_HOST" \
76+
-p "$LOCAL_PORT" \
77+
-U "$LOCAL_USER" \
78+
-d "$LOCAL_DB" \
79+
-t -c "SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public';")
80+
echo "==> Restored ${TABLE_COUNT// /} tables"
81+
82+
echo "==> Cleaning up dump file..."
83+
rm -f "$DUMP_FILE"
84+
85+
echo "==> Done! Local database synced from production."

0 commit comments

Comments
 (0)