postgres today-i-learned - It costs 1 mins to read

Đây là bài học xương máu rút ra được khi can thiệp database trực tiếp trên Production vì làm mất data của một Table (may là phát hiện kịp nên đã break câu lệnh destroy data). Sau khi rà soát thiệt hại thì mình thống kê là cần phải khôi phục lại khoảng 1000 record đầu tiên của Table đó trên Postgres. Vậy làm thế nào để khôi phục một phần dữ liệu của một table thay vì bung bản backup ra và restore lại toàn bộ database?

Thật may là Postgres có hỗ trợ lệnh COPY data và đây là cách mình đã khôi phục lại 1000 record bị xóa nhầm:

COPY (SELECT * FROM mytable WHERE [_CONDITION X_]...) TO '/tmp/myfile.tsv'
COPY mytable FROM 'myfile.tsv'
-- Login to psql and run the following
-- What is the result?
SELECT MAX(id) FROM your_table;

-- Then run...
-- This should be higher than the last result.
SELECT nextval('your_table_id_seq');

-- If it's not higher... run this set the sequence last to your highest pid it. 
-- (wise to run a quick pg_dump first...)
SELECT setval('your_table_id_seq', (SELECT MAX(id) FROM your_table));
-- if your tables might have no rows
-- false means the set value will be returned by the next nextval() call    
SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);