Search code examples
postgresqlrestorepg-dump

relocate postgres dump when restoring


Is there a way to relocate(?) a postgres dump when restoring it?

I want to restore a dump from a staging db, to my development db where the owner and schema are different from staging.

Is there another way to achieve this then doing a search and replace in the dump?

To give concrete values: my staging db has owner "iplister" and schema "public" while I want to restore to owner "developer" and schema"csapi".

Currently I do

pg_dump \
  postgresql://$OWNER:$PASSWORD@$HOST/$DB | perl -pe '
    s/[ \x27]\Kpublic\./csapi./g;
    s/\biplister\b/developer/g;
  ' > work/prod-db-$( date +%Y-%m-%d_%H-%M-%S ).sql

To create the dump and directly search & replace.

Of course this is error-prone when the dump contains in any dataset one of the searched words. That's why I'm asking for the correct way.


Solution

  • My solution now is:

      pg_dump \
        --no-owner \
        --clean \
        --if-exists \
        postgresql://$OWNER:$PASSWORD@$HOST/$DB | perl -pe '
          if (/^(ALTER|COPY|CREATE|SELECT|DROP)/ .. /;/) {
            s/[ \x27]\Kpublic\./csapi./g;
          } elsif (/^-- /) {
            s/[ \x27]\Kpublic\./csapi./g;
          }
        ' 
    

    The elsif isn't required but takes care for comments.