案例产生背景:
业务人员误清空表内容, 数据表为静态表,每天凌晨这张表会有数据插入,别的时间是没有DML动作的。
备天早上有一份PG_DUMP做的备份。
问题解决方案:
将全库备份中的表备份COPY出来,导入数据库即可。
模拟案例:
1. 创建表,并在里面插入一些数据。
postgres=# create table t_row(id serial primary key not null, name varchar(9)); CREATE TABLE postgres=# insert into t_row(name) values('a'); INSERT 0 1 postgres=# insert into t_row(name) values('b'); INSERT 0 1 postgres=# insert into t_row(name) values('c'); INSERT 0 1 postgres=# insert into t_row(name) values('d'); INSERT 0 1 postgres=# insert into t_row(name) values('e'); INSERT 0 1 postgres=# insert into t_row(name) values('f'); INSERT 0 1 postgres=# insert into t_row(name) values('g'); INSERT 0 1 postgres=# insert into t_row(name) values('h'); INSERT 0 1 postgres=# insert into t_row(name) values('i'); INSERT 0 1 postgres=#
2. 备份此库:
postgres@redis1:~$ pg_dump -d postgres -f postgres_all.psql postgres@redis1:~$ ls -ltrh total 8.0K drwxr-xr-x 3 postgres postgres 4.0K Dec 7 07:35 9.5 -rw-rw-r-- 1 postgres postgres 2.3K Dec 9 02:27 postgres_all.psql
3. 删除表:
postgres=# delete from t_row; DELETE 9 postgres=#
4. 打开文件,并COPY出插入数据的部份到另一个文件:
postgres@redis1:~$ sed -n '87,97p' postgres_all.psql > t_row.psql postgres@redis1:~$ cat t_row.psql COPY t_row (id, name) FROM stdin; 1 a 2 b 3 c 4 d 5 e 6 f 7 g 8 h 9 i \. postgres@redis1:~$
5. 将数据恢复:
postgres=# begin; BEGIN postgres=# \i t_row.psql COPY 9 postgres=# select * from t_row; id | name ----+------ 1 | a 2 | b 3 | c 4 | d 5 | e 6 | f 7 | g 8 | h 9 | i (9 rows) postgres=# commit; COMMIT postgres=#