案例產生背景:
業務人員誤清空表內容, 數據表為靜態表,每天凌晨這張表會有數據插入,別的時間是沒有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=#
