Monday, May 13, 2013

Duplicate Postgres database

It is unbelievable how easy is to create copy of Postgres database. The only command you need is

CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser

There are 2 possible issues regarding to command above:
  1. In some cases database name must be quoted (In my case
    CREATE DATABASE "sirene-migration-testing2" 
      WITH TEMPLATE "sirene-migration-testing" OWNER dbuser;
  2. If some other connections are active in source database then error will be thrown (ERROR: source database "sourcedb" is being accessed by other users). There is simple script to kill all other connections in postges database except current connection

    In PostgreSQL 9.2 and above, to disconnect everything except your session from the database you are connected to:

    SELECT pg_terminate_backend(procpid)
    FROM pg_stat_activity
    WHERE datname = current_database()
      AND procpid <> pg_backend_pid();