受支持版本: 当前版本 (18) / 17 / 16 / 15 / 14
开发版本: 19 / devel
此文档适用于不受支持的 PostgreSQL 版本。
您可能需要查看当前版本的相同页面,或上面列出的其他受支持版本。

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