RDS PostgreSQL支持通过设置列级别参数on_update_set_default,在不使用触发器的情况下,自动更新指定时间列。
前提条件
实例大版本为PostgreSQL 15及以上。
实例内核小版本为20241230及以上。
说明如需升级内核小版本,请参见升级内核小版本。
功能简介
在某些业务场景中,应用程序希望在更新表中某一行时,即使未显式指定时间列,也能自动更新该列。在原生PostgreSQL中,仅能通过触发器实现此功能。RDS PostgreSQL支持通过设置列级别参数on_update_set_default,在不使用触发器的情况下自动更新指定时间列。
该功能目前支持六种时间类型:TIMESTAMP、TIMESTAMPTZ、DATE、TIME、TIMETZ和INTERVAL。
开启指定时间列的on_update_set_default参数
ALTER TABLE <test> ALTER COLUMN <update_time> SET(on_update_set_default=true);
使用示例
创建测试表test并插入测试数据。
CREATE TABLE test (id INT, create_time TIMESTAMPTZ DEFAULT now(), update_time TIMESTAMPTZ DEFAULT now()); INSERT INTO test VALUES(1); SELECT * FROM test;
返回结果:
id | create_time | update_time ----+-------------------------------+------------------------------- 1 | 2025-01-09 16:07:48.481879+08 | 2025-01-09 16:07:48.481879+08
更新测试表数据。
UPDATE test SET id=2; SELECT * FROM test;
返回结果,update_time列内容未更新:
id | create_time | update_time ----+-------------------------------+------------------------------- 2 | 2025-01-09 16:07:48.481879+08 | 2025-01-09 16:07:48.481879+08
修改测试表update_time列的on_update_set_default参数值,以启用自动更新时间列的功能。
ALTER TABLE test ALTER COLUMN update_time SET(on_update_set_default=true); SELECT attoptions FROM pg_attribute WHERE attname='update_time';
返回结果:
attoptions ------------------------------ {on_update_set_default=true}
更新测试表数据。
UPDATE test SET id=3; SELECT * FROM test;
返回结果,update_time列内容自动更新:
id | create_time | update_time ----+-------------------------------+------------------------------- 3 | 2025-01-09 16:07:48.481879+08 | 2025-01-09 16:08:39.601701+08
该文章对您有帮助吗?