Postgres SET UNLOGGED 需要很长时间

Postgres SET UNLOGGED takes a long time

运行 Postgres-9.5。我有一个很大的 table 正在做 ALTER TABLE table SET UNLOGGED。我已经删除了所有针对 table 的外键约束,因为无法取消记录 FK 引用的 table。查询耗时约 20 分钟,全程消耗 100% CPU。我能理解要记录 table 需要很长时间,但要取消记录似乎并不困难...但是是吗?

我可以做些什么来更快地设置 table unlogged 吗?

SET UNLOGGED 涉及 table 重写,因此对于大型 table,您可能需要相当长的时间。

正如您所说,制作 table UNLOGGED 似乎没有那么难。简单地转换 table 并不 那么困难;复杂的因素是需要做到这一点 crash-safe。 UNLOGGED table 有一个与之关联的附加文件(init fork),并且无法将此文件的创建与提交的其余部分同步。

因此,SET UNLOGGED 构建了一个 table 的副本,并附加了一个初始化分支,然后换入新的 relfilenode, which the commit can handle atomically. A more efficient implementation would be possible, but not without changing the representation of unlogged tables (which predate SET UNLOGGED by quite a while) or the logic behind COMMIT itself, both of which were deemed too intrusive for this relatively minor feature. You can read the discussion behind the design on the pgsql-hackers list

如果您确实需要最大限度地减少停机时间,您可以采用与 SET UNLOGGED 类似的方法:创建一个新的 UNLOGGED table,复制所有记录,在同步最后几项更改时短暂锁定旧的 table,并在完成后将新的 table 换成 RENAME