|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +set -e |
| 4 | + |
| 5 | +echo "Starting database dump restoration..." |
| 6 | + |
| 7 | +for dump_file in /data/*.dump; do |
| 8 | + if [ ! -f "$dump_file" ]; then |
| 9 | + echo "No .dump files found in /data/ directory" |
| 10 | + break |
| 11 | + fi |
| 12 | + |
| 13 | + db_name=$(basename "$dump_file" .dump) |
| 14 | + |
| 15 | + echo "Processing $dump_file -> database '$db_name'" |
| 16 | + |
| 17 | + if psql -U postgres -h localhost -p 5432 -lqt | cut -d \| -f 1 | grep -qw "$db_name"; then |
| 18 | + echo "Database '$db_name' already exists. Checking if it has data..." |
| 19 | + |
| 20 | + table_count=$(psql -U postgres -h localhost -p 5432 -d "$db_name" -t -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';" 2>/dev/null || echo "0") |
| 21 | + |
| 22 | + if [ "$table_count" -gt 0 ]; then |
| 23 | + echo "Database '$db_name' already has $table_count tables. Skipping restoration." |
| 24 | + continue |
| 25 | + else |
| 26 | + echo "Database '$db_name' exists but is empty. Proceeding with restoration..." |
| 27 | + fi |
| 28 | + else |
| 29 | + echo "Creating database '$db_name'..." |
| 30 | + psql -U postgres -h localhost -p 5432 -c "CREATE DATABASE \"$db_name\";" 2>/dev/null || { |
| 31 | + echo "Warning: Could not create database '$db_name' (may already exist)" |
| 32 | + } |
| 33 | + fi |
| 34 | + |
| 35 | + echo "Restoring $dump_file into database '$db_name'..." |
| 36 | + |
| 37 | + # Use --clean --if-exists to handle existing objects gracefully |
| 38 | + if pg_restore -U postgres -h localhost -p 5432 --clean --if-exists --no-owner --no-privileges -d "$db_name" "$dump_file" 2>/dev/null; then |
| 39 | + echo "Successfully restored $dump_file" |
| 40 | + |
| 41 | + final_table_count=$(psql -U postgres -h localhost -p 5432 -d "$db_name" -t -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public';" 2>/dev/null || echo "0") |
| 42 | + echo " Database '$db_name' now has $final_table_count tables" |
| 43 | + else |
| 44 | + echo "Warning: pg_restore reported errors for $dump_file (this may be normal for some dump formats)" |
| 45 | + fi |
| 46 | + |
| 47 | + echo "" |
| 48 | +done |
| 49 | + |
| 50 | +echo "Database dump restoration completed" |
| 51 | + |
| 52 | +echo "Summary of available databases:" |
| 53 | +psql -U postgres -h localhost -p 5432 -c "\l" | grep -E "^\s+[a-zA-Z]" | head -20 |
0 commit comments