Thursday, August 13, 2020

How to perform a full export and import of an entire database in PostgreSQL


Export the database "db01" from your source postgres server:

pg_dump db01 -v -Fc >db01.dmp

The -v means "verbose" and -Fc means "custom format" (as opposed to "directory format", which would be indicated by -Fd)

Import the database "db01" in your destination postgres server

First, transfer the directory db01.dmp file from the source server to the target server using scp.
pg_restore -v -d db01 -1 db01.dmp
The -1 option means "all or nothing"; either the entire operation succeed, or nothing is done.

If the database doesn't exist, you need to connect to another database in the cluster first:
pg_restore -v -C -d postgres /exports/full_db_export.dmp

Export the database "db01" using the directory format:

pg_dump -Fd db01 -f /exports/full_db01 -v

This will create the directory /exports/full_db01 which contains all the files necessary for restore. The -v means "verbose" and -Fd means "directory format"

Import the database "db01":


Again, transfer the needed files, this time the entire directory /exports/full_db01 from the source server to the target server using scp.
Then import the database, either by recreating the database indicated by the -C option:
pg_restore /exports/full_db01 -C -c -d postgres -j 2 -v

or by importing the objects into an existing database, in my case "db02":
pg_restore /exports/full_db01 -c -d db02 -j 2 -v

  • The -C option means "create database".
  • The -d postgres option indicates the database to which the pg_dump utility makes an initial connection
  • The -c option means "drop the database objects before creating"
  • -j is the number of jobs started in parallel

    The official documentation for the pg_dump utility can be found here
    here
  • No comments:

    Post a Comment