Pgdump_restore
Chapter 44: pg_dump & pg_restore
Section titled “Chapter 44: pg_dump & pg_restore”Backup and Restore Fundamentals
Section titled “Backup and Restore Fundamentals”44.1 pg_dump
Section titled “44.1 pg_dump”pg_dump extracts a PostgreSQL database into a script file or archive.
# Basic dump (plain SQL text)pg_dump -U postgres -d mydb > backup.sql
# Compressed dumppg_dump -U postgres -d mydb | gzip > backup.sql.gz
# Custom format (parallel, compressed)pg_dump -U postgres -d mydb -Fc -f backup.dump
# Directory format (parallel)pg_dump -U postgres -d mydb -Fd -j 4 -f backup_dir
# Only schemapg_dump -U postgres -d mydb --schema-only > schema.sql
# Only datapg_dump -U postgres -d mydb --data-only > data.sql
# Specific tablespg_dump -U postgres -d mydb -t users -t orders > tables.sql
# Exclude tablepg_dump -U postgres -d mydb --exclude-table=logs > backup.sql44.2 pg_restore
Section titled “44.2 pg_restore”pg_restore restores PostgreSQL databases from pg_dump archives.
# Restore from plain SQLpsql -U postgres -d mydb < backup.sql
# Restore from custom formatpg_restore -U postgres -d mydb backup.dump
# Restore to different databasepg_restore -U postgres -d newdb backup.dump
# Restore specific tablespg_restore -U postgres -d mydb -t users backup.dump
# Drop objects before creatingpg_restore -U postgres -d mydb --clean backup.dump
# Create database firstcreatedb -U postgres newdbpg_restore -U postgres -d newdb backup.dump44.3 Automation
Section titled “44.3 Automation”# Daily backup script#!/bin/bashBACKUP_DIR="/backups"DATE=$(date +%Y%m%d)DB_NAME="mydb"
# Create backuppg_dump -U postgres -d $DB_NAME | gzip > $BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz
# Keep only last 7 daysfind $BACKUP_DIR -name "*.sql.gz" -mtime +7 -delete
# Verify backupgunzip -c $BACKUP_DIR/${DB_NAME}_${DATE}.sql.gz | head -n 10Summary
Section titled “Summary”| Command | Use |
|---|---|
| pg_dump | Create backup |
| pg_restore | Restore from archive |
| psql | Execute SQL file |