Search code examples
postgresqlpsqlpg-dumppg-restore

Unable to restore psql database from pg_dump with a different username


I need to dump a postgres database from computer1 with postgres username1 and then restore it on computer2 with postgres username2. I keep running into the error that looks like the backup file wants to use username1:

When I run this on computer2:

psql dbname < backupname.pgsql

I get this error:

ERROR:  role "username1" does not exist

I have tried:

// Dumping from computer1:

pg_dump dbname > backupname.sql
pg_dump dbname > backupname.pgsql
pg_dump -U username1 dbname -N topology -T spacial_ref_sys > backupname.pgsql


// Restoring on computer2:

psql dbname < backupname.pgsql

Is it the dumping or the restoring that needs to be modified to get past this?


Solution

  • The problem is with the dumping. With insight from this post I was able to resolve this using:

    // On Computer1
    
    pg_dump dbname -O -x > backupname.sql
    
    
    // On Computer2
    
    psql dbname < backupname.sql
    

    The option flags used with pg_dump are:

    -O   <-- No owner
             Do not output commands to set ownership of objects to match the original database
    
    -x   <-- No privileges
             Prevent dumping of access privileges (grant/revoke commands)
    

    See the PostgreSQL docs for pg_dump for more info on the option flags.