[译] PostgreSQL 用 DEFAULT 更新 updated_at
授权转载与 AI 辅助翻译(非官方)
原作者及版权:© Gunnar Morling;首发:2024-02-20
英文原文:Last Updated Columns With Postgres
授权:英文原文及本简体中文译文均按 CC BY-SA 4.0 分享。编辑改动:增加中文翻译、译注和分类导航;保留完整英文正文,调整排版,外嵌演示以链接呈现。未暗示原作者认可本译文。
分类:Java 后端与交易 · PostgreSQL、时间字段、DEFAULT
博客首页目录 · 一手技术资料总索引
中文译文
许多应用需要记录每条数据什么时候创建、最后一次更新是什么时候。常见做法是在表里放 created_at 和 updated_at。为了让应用开发更省事,最好让数据库在插入或更新记录时自动维护这些值。
创建时间容易处理:给列设置默认值 current_timestamp。如果 INSERT 没有给该列赋值,数据库就用当前时间戳填充。那最后更新时间怎么办?
只设默认值不够,因为更新行时这一列已经有值。也不宜在应用代码里生成时间:这样创建和更新就用了不同的时钟。应用服务器和数据库服务器时间不一致时,可能发生两列时间顺序颠倒的情况。
MySQL 可以用 ON UPDATE 在更新行时写入当前时间戳;Postgres 没有这个特性。搜索这个问题,常见做法是用更新触发器。我以前也会这么做,能用,但每张表都声明一个触发器就开始麻烦了。
同事告诉我还有个更简单的办法:Postgres 更新行时,允许显式把一列设回默认值。假设有下面这张表和这一行:
CREATE TABLE movie (
id SERIAL NOT NULL,
title TEXT,
viewer_rating NUMERIC(2, 1),
created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
updated_at TIMESTAMP NOT NULL DEFAULT current_timestamp
);
INSERT INTO movie (title, score) VALUES ('North by Northwest', 9.2);
那么,自动更新 updated_at 可以这样写:
UPDATE
movie
SET
viewer_rating = 9.6, updated_at = DEFAULT
WHERE
id = 1;
数据库执行语句时会取这个值,因此不会因为 created_at 与 updated_at 来自不同的时钟而产生冲突。它不像 MySQL 的 ON UPDATE 那么省心,因为应用发出的每条 UPDATE 都必须显式写 DEFAULT,但还是很实用,比给所有表都建触发器简单。如果应用还要拿到更新后的值,可以用 RETURNING 返回:
UPDATE
movie
SET
score = 9.6, updated_at = DEFAULT
WHERE
id = 1
RETURNING
updated_at;
想自己运行示例,可以去 DB Fiddle。
译注:转载时保留原 SQL。原文第一个
INSERT和最后一个UPDATE用了score,但建表定义的是viewer_rating;复制运行前,把两处score改成viewer_rating。若希望业务时钟反映语句开始或实际调用时刻,还要区分 PostgreSQL 的current_timestamp、statement_timestamp()与clock_timestamp()。
English Original
Last Updated Columns With Postgres
In many applications it’s a requirement to keep track of when a record was created and updated the last time. Often, this is implemented by having columns such as created_at and updated_at within each table. To make things as simple as possible for application developers, the database itself should take care of maintaining these values automatically when a record gets inserted or updated.
For the creation timestamp, that’s as simple as specifying a column default value of current_timestamp. When omitting the value from an INSERT statement, the field will be populated automatically with the current timestamp. What about the update timestamp though?
Solely relying on the default value won’t cut it, as the field already has a value when a row gets updated. You also shouldn’t set the value from within your application code. Otherwise, create and update timestamps would have different sources, potentially leading to anomalies if there are clock differences between application and database server, such as a row’s created_at timestamp being younger than it’s updated_at timestamp.
For MySQL, the ON UPDATE clause can be used to set the current timestamp when a row gets updated. Postgres does not support this feature, unfortunately. If you search for a solution, most folks suggest defining an ON UPDATE trigger for setting the update timestamp. This also is what I’d have done until recently; it works, but having to declare such a trigger for every table can quickly become a bit cumbersome.
But as I’ve just learned from a colleague, there’s actually a much simpler solution: Postgres lets you explicitly set a field’s value to its default value when updating a row. So given this table and row:
CREATE TABLE movie (
id SERIAL NOT NULL,
title TEXT,
viewer_rating NUMERIC(2, 1),
created_at TIMESTAMP NOT NULL DEFAULT current_timestamp,
updated_at TIMESTAMP NOT NULL DEFAULT current_timestamp
);
INSERT INTO movie (title, score) VALUES ('North by Northwest', 9.2);
Then auto-updating the updated_at field is as simple as this:
UPDATE
movie
SET
viewer_rating = 9.6, updated_at = DEFAULT
WHERE
id = 1;
The value will be retrieved by the database when executing the statement, so there is no potential for inconsistencies with the created_at value. It is not quite as elegant as MySQL’s ON UPDATE, as you must make sure to set the value to DEFAULT in each UPDATE statement your application issues. But pretty handy nevertheless, and certainly more convenient than defining triggers for all tables. If you need to retrieve the value from within your application as well, you simply can expose it using the RETURNING clause:
UPDATE
movie
SET
score = 9.6, updated_at = DEFAULT
WHERE
id = 1
RETURNING
updated_at;
If you want to play with this example by yourself, you can find it here on DB Fiddle.

浙公网安备 33010602011771号