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.
Code
-- 会话一:开启事务、完成本地写入、准备提交
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which relations are involved here?
- The references are `accounts`, `pg_prepared_xacts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.