PostgreSQL has been shipped with a lot of tools for ease of managing the database. Some actions that we typically perform in managing databases are backing up a database and restoring it to another database server. In PostgreSQL, we can utilize pg_dump
to back up the data from a database and psql
or pg_restore
to restore the data into a new database.
Generating A Backup File
There are several available formats for the exported data: plain, directory, compressed, and custom. The plain format is using plain SQL syntax to export the data. To make the tables are exported separately, we can utilize directory format. The custom format is utilizing a built-in compression mechanism and results in an optimized binary formatted file. It is suitable for a large database. If we use a custom format, we can only restore it using pg_restore
, but we have the ability to selectively choose desired tables to be restored.
The following command is used to generate a plain formatted file with the INSERT
syntax as the SQL command for inserting records. The file
parameter is used to specify the destination file to store the result.
pg_dump \
--host=localhost \
--port=5432 \
--username=postgres \
--password \
--dbname=mydatabase
--file=outputFilePlain \
--format=p \
--inserts \
--no-owner \
--no-privileges
The following command is used to generate a custom formatted file.
pg_dump \
--host=localhost \
--port=5432 \
--username=postgres \
--password \
--dbname=mydatabase
--file=outputFileCustom \
--format=c \
--inserts \
--no-owner \
--no-privileges
Restoring Database from A Backup File
As I have mentioned above, we can utilize psql
or pg_restore
to restore the database from a backup file. But, only the pg_restore
command can be used to restore the custom formatted file.
The following command is used to restore a database from a plain formatted file. We must create the destination database first before running this command. The file
parameter is used to specify the source file.
psql \
--host=localhost \
--port=5432 \
--username=postgres \
--password \
--dbname=mynewdatabase \
--file=inputFilePlain
The following command is used to restore the database from a custom formatted file using pg_restore
. We need to notice that the last part is the name of the input file without the name of a command parameter.
pg_restore \
--host=localhost \
--port=5432 \
--username=postgres \
--password \
--dbname=mynewdatabase \
inputFileCustom
Comments
Post a Comment