Thursday, June 14, 2007

How to restore data from a previous PostgreSQL installation

Recently I was given a task to restore data from a previous PostgreSQL installation to my latest Postgresql installation. The server on which the database server was running crashed. Though I tried to find if any help was available on the net and surprisingly most of the sites talked about restoring data from backup created using pgdump or pgdumpall. After a lot of digging I learnt that if I give my data path while starting the database server using pg_ctl PostgreSQL can make the data accessible. I did the same and I found that the database was not getting mounted properly. Here are the steps one should keep in mind if they want to access their database from previous postgresql installation directory.

1. Check for the version of previous Postgresql installation.
/.../data/PG_VERSION (location of directory data under previous postgresql installation directory)

2. Check if it matches the current version i.e if the version of Postgresql from PG_VERSION file matches your current Postgresql installation
- >If the versions match, just clean start your postgresql using your old directory in the data path
pg_ctl start -D /data path to previous installation/
or alternatively you can use
postmaster -D /data path to previous installation/

- > if the versions don't match as it was in my case, [I had Postgresql 7.4 installed previously and now I wanted to get the data on to Postgresql 8.4] we have to do a bit more than just starting database server with old data path.

Steps to recover data from previous version of Postgresql

a) install Postgresql 7.4 (remember even if you cannot find version 7.4 you can install any 7.x version)
for this, I downloaded the source and compiled and installed it on my system
Ubuntu users don't have to go through all this they can directly use binary package download from

https://launchpad.net/ubuntu/+source/postgresql/7.4.5-3

This site also has downloadable source code so people who use Linux flavors for which binary is not available can rebuild the binary on their system locally.

RPM binary packages are also available from www.postgresql.org

http://www.postgresql.org/ftp/binary/v7.4.17/


Once installed, use the command in step-2, Postgresql should mount the database without any errors, login to postgresql database server and you should be able to see all your previous data.