← 中文资源

简体中文版本

ctid 与 xmin 暴露行版本机制

UPDATE 不原地改:新版本写到新物理位置,ctid 随之改变,xmin 记录写入事务;只读访问不追加版本,旧版本留给 VACUUM 回收——表膨胀的根源在这里可见。

阅读英文原文

实现说明

这个文件依次执行 SELECT 语句,涉及 drafts。

常见问题

这里涉及哪些关系(表/CTE)?

引用的是 drafts。

核心语句

UPDATE drafts SET title = 'v2' WHERE id = 1;
UPDATE drafts SET title = 'v3' WHERE id = 1;
CREATE TEMP TABLE drafts (
    id    integer PRIMARY KEY,
    title text NOT NULL
);

代码示例

-- MVCC: UPDATE does not modify in place, it writes a new version; the old one stays put until VACUUM reclaims it
-- xmin records the transaction id that wrote the version; ctid is the row's physical location
CREATE TEMP TABLE drafts (
    id    integer PRIMARY KEY,
    title text NOT NULL
);

INSERT INTO drafts VALUES (1, 'v1');

-- after two UPDATEs: still 1 visible row, but 3 versions already exist underneath
UPDATE drafts SET title = 'v2' WHERE id = 1;
UPDATE drafts SET title = 'v3' WHERE id = 1;

-- ctid changes with every update: new versions land at new physical locations
SELECT ctid, xmin, title FROM drafts;

-- read-only access adds no versions: two SELECTs in a row report the exact same ctid
SELECT ctid, title FROM drafts;
SELECT ctid, title FROM drafts;

-- many small updates stretch the version chain: the source of table bloat; VACUUM reclaims the old versions