Preparing for Migration
Before starting, ensure you have:
pg_dump or pgAdmin’s built-in backup tool to create a full backup of the source database. This prevents data loss if issues arise during migration.sudo apt install pgadmin4 on Debian) and configure it to connect to their respective PostgreSQL instances.sudo systemctl status postgresql).Exporting Data from the Source Server
You can export data using either logical backups (portable SQL files) or file transfers (for large datasets).
Option 1: Logical Backup with pgAdmin (GUI)
/home/user/source_db_backup.sql) and Format (select “Plain” for SQL).CREATE TABLE, INSERT, and other statements to recreate the database.Option 2: Logical Backup with Command Line (pg_dump)
For larger databases or automation, use pg_dump:
pg_dump -U postgres -d source_database -f /path/to/source_db_backup.sql
Replace postgres with your username, source_database with the database name, and /path/to/ with the desired output directory.
Option 3: Export Specific Tables as CSV
To export individual tables (e.g., for partial migration), use pgAdmin’s Query Tool or COPY command:
COPY (SELECT * FROM your_table) TO '/path/to/export/file.csv' WITH (FORMAT csv, HEADER true, DELIMITER ',');
This creates a CSV file with table data, which can be imported into the target database.
Transferring Data to the Target Server
Use secure file transfer tools like scp to move the exported file from the source to the target server:
scp /path/to/source_db_backup.sql user@target_server_ip:/home/user/
Replace user with the target server’s username and target_server_ip with its IP address. Enter the user’s password when prompted.
Importing Data to the Target Server
Once the file is transferred, import it into the target PostgreSQL instance using pgAdmin or command line.
Option 1: Logical Import with pgAdmin (GUI)
target_db), and click Save.Option 2: Logical Import with Command Line (psql)
For automation or large datasets, use psql:
psql -U postgres -d target_database -f /path/to/source_db_backup.sql
Replace postgres with your username, target_database with the target database name, and /path/to/ with the file’s location.
Option 3: Import CSV Data
To import CSV files, use pgAdmin’s Query Tool or COPY command:
COPY your_table FROM '/path/to/import/file.csv' WITH (FORMAT csv, HEADER true, DELIMITER ',');
Ensure the target table exists and has matching columns.
Verifying Data Integrity
After migration, validate the data to ensure completeness and accuracy:
SELECT COUNT(*) FROM your_table;).SELECT * FROM your_table LIMIT 10) to verify data consistency.pg_restore, add the --verbose flag to see detailed progress and errors.Troubleshooting Common Issues
pg_dump with the --compatible flag (e.g., --compatible=12 for PostgreSQL 12 compatibility).COPY command or export settings accordingly.