pg_current_xact_id Assigns On First Read
pg_current_xact_id() assigns an XID even when the transaction only reads, while the if_assigned variant stays NULL until a write actually needs one.
Code
-- 只读事务还没消耗 XID:if_assigned 返回 NULL
BEGIN;
SELECT pg_current_xact_id_if_assigned() AS before_write; -- NULL
-- 读取即分配:不需要任何写入也会拿到当前事务的 xid8
SELECT pg_current_xact_id() AS forced;
SELECT pg_current_xact_id_if_assigned() AS after_read; -- 与 forced 相同
ROLLBACK;
-- xid8 是 64 位:不像内部 32 位 xid 那样每 40 亿回绕
CREATE TABLE job_claims (
job_id integer PRIMARY KEY,
claimed_xid xid8
);
BEGIN;
INSERT INTO job_claims VALUES (101, pg_current_xact_id());
-- 同一事务内重复读取得到同一个 id:INSERT 与比较包进同一事务
SELECT claimed_xid = pg_current_xact_id() AS same_tx
FROM job_claims
WHERE job_id = 101;
COMMIT;
-- 子事务(SAVEPOINT)里读取返回的仍是顶层事务 ID
BEGIN;
SELECT pg_current_xact_id() AS top_level_xid;
SAVEPOINT sp1;
SELECT pg_current_xact_id() AS inside_subxact; -- 与 top_level_xid 相同
ROLLBACK TO SAVEPOINT sp1;
COMMIT;
-- 旧函数 txid_current() 返回 bigint,已列入废弃表、仅向后兼容
SELECT txid_current() AS legacy_bigint;Inside the snippet
SELECT / INSERT / CREATE statements share the script, touching job_claims.
Breaking the statements into their working parts: a WHERE clause limiting the rows one statement is allowed to reach; a PRIMARY KEY that enforces row identity.
Using it
Run the statement against the job_claims table.
Statements the file turns on
SELECT claimed_xid = pg_current_xact_id() AS same_tx
FROM job_claims
WHERE job_id = 101;
CREATE TABLE job_claims (
job_id integer PRIMARY KEY,
claimed_xid xid8
);
SELECT pg_current_xact_id_if_assigned() AS after_read; -- 与 forced 相同
Interactive Tools for This Topic
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.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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables does this file reference?
- `job_claims`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.