Saturday, July 27, 2013

postgresql backup and restore options

the normal backup and restore syntax in cmd prompt is,

pg_dump -U postgres -p 5432 -Fc -d dbname > dumpfile.dump
to restore schema wise use pg_dump -U postgres -p 5432 -Fc -d dbname > dumpfile.dump

The same syntax in windows is,
"C:\\Program Files(x86)\PostgreSQL\8.3\bin\pg_dump.exe" -U postgres -p 5432 -Fc -d dbname > dumpfile.dump

This script can be put in the batch file to create an automated backup process and to make it run unattended prepare a pgpass.conf file with following lines
localhost:5432:*:postgres:dbname

where postgres is the service username, you can change it to the user with which you are going to run the command. The command for uninterrupted execution is
"C:\\Program Files(x86)\PostgreSQL\8.3\bin\pg_dump.exe" -U postgres -p 5432 -w -Fc -d dbname > dumpfile.dump.  so this will check with the pgpass file and and execute uninterrupted.
The pgpass.conf file can be found in
su - postgres     //this will land in the home directory set for postgres user vi .pgpass.conf    //enter all users entries   chmod 0600 .pgpass.conf    // change the ownership to 0600 to avoid error like    
-bash-3.2$ psql   
WARNING: password file "/opt/PostgreSQL/9.2//.pgpass" has group or world access; permissions should be u=rw (0600) or less 

In windows this can be found at "C:\Users\welcome\AppData\Roamin\postgresql" or %appdata%\postgresql


To restore use the following command as
pg_restore -U postgres -p 5432 -w -d dbname backupfile.dump
to restore schema only, use pg_restore -U postgres -p 5432 -w -s -d dbname backupfile.dump
to restore tablewise, use pg_restore -U postgres -p 5432 -w -s -t tablename -d dbname backupfile.dump
to restore data only, replace the -s option with -a attribute.

1 comment:

Cyber security training courses online said...

Great post. Thanks for sharing detailed information on PostgreSQL automatic backup and script.