A table's rows were mistakenly deleted from the database. We have a db backup which results in a sql file that can restored like so:
psql -h localhost -d proddump -f /Users/U/Desktop/prod_db_backup/PostgreSQL/site_prod.sql
This ends up doing a full restore locally. But what we need is to restore a single table's rows to production. Any tips on how to make this work with PostgreSQL 9.1?
Thanks
Don't do SQL backups if you need single table restore, etc. Use
pg_dump
's-Fc
option - the "custom" format. This can be restored usingpg_restore
. Selective restore is possible, as are all sorts of other handy features.pg_restore
can convert a custom-format dump into an SQL dump later if you need it.If you're stuck with an existing dump, your only options are:
Use a text editor to extract the target table data to a separate file and just restore that; or
Restore the dump to a throwaway database then use
pg_dump
to take a selective dump including just that table. Since it's throwaway, you can use a separate Pg instance on some unloaded fast-but-unsafe machine where you turn on all the "make it fast but eat my data if you like" options likefsync=off
. You should NEVER set that in production.I'm not aware of any tool for this, but this one-liner extracts
precious_table
frommy_backup.sql
file:There is an easy way.
'pg_restore' has a '--table/-t' option.
Use '-h' for remote host. See other options here
You can use grep + sed in roder to get table data:
First, you need to identify boundaries:
In order to extract data for table test2:
Note, you need to subtract one from the second number (i.e exclude next copy stmt)
Now, you can load
new_table_name.sql
and restore data which you need. Now, you can load data into new tableI happen to have
pg_dumpall
dump around. And I would like to restore table namedusers
from the database namededc
, as you most likely will have equally named tables in different databases and even schemas.For my case, the following
sed
oneliner works:What it does:
/^\\connect edc/,/^\\connect/
limits the search to be the scope of my database;{…}
will perform all inside commands for the range;/\susers\(\s\|$\)/
matches all lines withusers
on it's own, including at the end of the line;/;\|\\\./
matches lines with;
or containing\.
p
forces the matching lines to be outputted (note, that sed is invoked with-n
).Depending on the complexity of your data, you might need to tweak this.
All you have to do is to pipe
sed
output to thepsql
command with right switches.