PostgreSQL Tutorial: Transaction Savepoints

For example, there is a large transaction operation in the project that is difficult to control. Timeouts have an impact. Rolling back will cause everything to be repeated, which is too costly.

For large transactions, I split them into several parts. After the first part is completed, I build a save point. If the subsequent operation fails and needs to be rolled back, there is no need to roll back the whole disk. Roll back to the previous save point and continue to try again.

One may find that this breaks the atomicity of the overall transaction.

But, as long as the operation is reasonable, you can retry the save point extraction. As long as the retry is unsuccessful, you can still roll back the entire disk.

For example, in an e-commerce project, place an order, deduct inventory, create an order, delete a shopping cart, increase user points, notify merchants... This is actually a big deal. After the core functions of deducting inventory and placing orders are completed, a save point can be added. If subsequent operations fail, you can try again from the stage after the order is successfully created.

However, in fact, the above-mentioned business has a better processing method based on final consistency, which can ensure availability.

Just do it simply.

-- savepoint操作
-- 开启事务
begin;
-- 插入一条数据
insert into test values (8,'铃铛',55,11);
-- 添加一个保存点
savepoint ok1;
-- 再插入数据,比如出了一场
insert into test values (9,'大唐官府',66,22);
-- 回滚到之前的提交点
rollback to savepoint ok1;
-- 就可以开始重试操作,重试成功,commit,失败可以rollback;
commit;

Guess you like

Origin blog.csdn.net/a772304419/article/details/132929045
Recommended