Redrock Postgres 搜索 英文
版本: 9.3 / 9.4 / 9.5 / 9.6 / 10 / 11 / 12 / 13 / 14 / 15 / 16 / 17

F.42. 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.