How to restore a single table from a .sql postgresql backup?

前端 未结 7 621
耶瑟儿~
耶瑟儿~ 2020-12-09 04:19

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 pr         


        
7条回答
  •  盖世英雄少女心
    2020-12-09 04:43

    I happen to have pg_dumpall dump around. And I would like to restore table named users from the database named edc, as you most likely will have equally named tables in different databases and even schemas.

    For my case, the following sed oneliner works:

    sed -ne '/^\\connect edc/,/^\\connect/{/\susers\(\s\|$\)/,/;\|\\\./p}' pg92.dump
    

    What it does:

    1. /^\\connect edc/,/^\\connect/ limits the search to be the scope of my database;
    2. {…} will perform all inside commands for the range;
    3. /\susers\(\s\|$\)/ matches all lines with users on it's own, including at the end of the line;
    4. /;\|\\\./ matches lines with ; or containing \.
    5. 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 the psql command with right switches.

提交回复
热议问题