2025年9月25日: PostgreSQL 18 发布!
支持的版本: 当前 (18) / 17 / 16 / 15 / 14 / 13
开发版本: devel
不支持的版本: 12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2

F.44. tcn — 通知监听器表内容更改的触发器函数 #

tcn 模块提供了一个触发器函数,用于通知在该触发器函数上附加的任何表内容更改的监听器。它必须用作 AFTER 触发器 FOR EACH ROW

此模块被认为是受信任的,这意味着非超级用户也可以在其拥有的数据库上安装它,前提是他们具有 CREATE 权限。

CREATE TRIGGER 语句中,该函数最多只能提供一个参数,并且该参数是可选的。如果提供了参数,则它将用于通知的频道名称。如果省略,则 tcn 将用作频道名称。

通知的有效载荷包含表名、指示执行何种操作的字母以及主键列的列名/值对。每个部分之间用逗号分隔。为了方便使用正则表达式进行解析,表名和列名始终用双引号括起来,数据值始终用单引号括起来。嵌入的引号会加倍。

下面是一个使用该扩展的简短示例。

test=# create table tcndata
test-#   (
test(#     a int not null,
test(#     b date not null,
test(#     c text,
test(#     primary key (a, b)
test(#   );
CREATE TABLE
test=# create trigger tcndata_tcn_trigger
test-#   after insert or update or delete on tcndata
test-#   for each row execute function triggered_change_notification();
CREATE TRIGGER
test=# listen tcn;
LISTEN
test=# insert into tcndata values (1, date '2012-12-22', 'one'),
test-#                            (1, date '2012-12-23', 'another'),
test-#                            (2, date '2012-12-23', 'two');
INSERT 0 3
Asynchronous notification "tcn" with payload ""tcndata",I,"a"='1',"b"='2012-12-22'" received from server process with PID 22770.
Asynchronous notification "tcn" with payload ""tcndata",I,"a"='1',"b"='2012-12-23'" received from server process with PID 22770.
Asynchronous notification "tcn" with payload ""tcndata",I,"a"='2',"b"='2012-12-23'" received from server process with PID 22770.
test=# update tcndata set c = 'uno' where a = 1;
UPDATE 2
Asynchronous notification "tcn" with payload ""tcndata",U,"a"='1',"b"='2012-12-22'" received from server process with PID 22770.
Asynchronous notification "tcn" with payload ""tcndata",U,"a"='1',"b"='2012-12-23'" received from server process with PID 22770.
test=# delete from tcndata where a = 1 and b = date '2012-12-22';
DELETE 1
Asynchronous notification "tcn" with payload ""tcndata",D,"a"='1',"b"='2012-12-22'" received from server process with PID 22770.

提交更正

如果您在文档中发现任何不正确之处,与您在使用特定功能时的体验不符,或者需要进一步澄清,请使用 此表单 来报告文档问题。