Two-Phase Commit With PREPARE TRANSACTION

Run a two-phase commit with PREPARE TRANSACTION, then finish it from another session with COMMIT PREPARED or ROLLBACK PREPARED.

SqlResilience

Code

snippet
-- 会话一:开启事务、完成本地写入、准备提交
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
PREPARE TRANSACTION 'transfer-42';
-- 此时事务已脱离当前会话,等待全局提交或回滚

-- 会话二(或恢复进程):决定提交
COMMIT PREPARED 'transfer-42';

-- 另一种结局:回滚准备好的事务
-- ROLLBACK PREPARED 'transfer-42';

-- 查看当前实例中准备好的事务
SELECT gid, prepared, owner, database
FROM pg_prepared_xacts
ORDER BY prepared;

-- 两阶段提交要求实例预留事务容量
SHOW max_prepared_transactions;

What the code does

Several statements share this file — SELECT / UPDATE, with accounts and pg_prepared_xacts among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.

Applying it

The accounts table is the working surface here.

Statements that matter

UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
SELECT gid, prepared, owner, database
FROM pg_prepared_xacts
ORDER BY prepared;

Interactive Tools for This Topic

FAQ

Which relations are involved here?
The references are `accounts`, `pg_prepared_xacts`.