PostgreSQL Tutorial: Physical Backup and Recovery (PITR-Point in time Recovery restores data to a specified transaction ID or a specified point in time based on archive logs)

Simulation scenario

Scenario: At 02:00 every morning, full backup (PBK) is started. On the next day, if someone accidentally deletes the data at 14:00, do you want to restore the data to the state before the accidental deletion at 14:00?

1. Restore the full data and use the full data of PBK to restore the data up to 02:00 in the morning. (A lot of data will be lost)

2. Archive recovery: The archive in the backup contains data information between 02:00 and 14:00. The data can be restored to the specified transaction ID or specified time point based on the archive log, thereby achieving complete data recovery.

Prepare scenarios and specific operations

1. Build a t3 table to query some data

-- 构建一张表
create table t3 (id int);
insert into t3 values (1);
insert into t3 values (11);

2. Simulate full preparation operations starting at 2 a.m.

pg_basebackup -D /pg_basebackup -Ft -Pv -Upostgres -h 192.168.11.32 -p 5432 -R

3. Do some write operations again, and then delete the data by mistake

-- 凌晨2点已经全备完毕
-- 模拟第二天操作
insert into t3 values (111);
insert into t3 values (1111);
-- 误删操作  2023年3月20日20:13:26
delete from t3;

4. Recover data (confirm that there are archive logs)

Delete all the data of the current service and follow the previous full recovery routine.

image.png

Then throw the base.tar in the complete content to the data directory, and throw the archive log to the /archive location.

5. View the archive log and find the specified transaction ID

Viewing archive logs requires a command provided by postgresql

# 如果命令未找到,说明两种情况,要么没有这个可执行文件,要么是文件在,没设置环境变量
# 咱们这是后者
pg_waldump
# 也可以采用全路径的方式
/usr/pgsql-12/bin/pg_waldump

image.png

image.png

6. Modify the method of recovering data in the data directory

Modify postgresql.auto.conffiles

Replace the previous maximum recovery with the specified transaction id recovery

Based on the configuration example provided, how to specify the transaction id

image.png

Modify the postgresql.auto.conf file to specify the transaction ID

image.png

7. Start the postgreSQL service and check whether it is restored to the specified transaction ID.

image.png

8. Remember to execute the function after the meeting to avoid being unable to perform write operations.

select pg_wal_replay_resume();

Guess you like

Origin blog.csdn.net/a772304419/article/details/132929973