在更新后使用更新中的数据来呼叫Notify之后,请创建Postgres语句触发
我想创建一个触发器,每当insert
在表中的语句上插入语句,使用插入的数据来调用pg_notify
:
CREATE OR REPLACE FUNCTION notify_updates() RETURNS TRIGGER AS $$
BEGIN
PERFORM pg_notify(NEW.aggregate_type, NEW.aggregate_id::text);
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER model_notification
AFTER INSERT ON events
FOR EACH STATEMENT
EXECUTE PROCEDURE notify_updates()
gencregate_type
和gentregate_id
是事件
表的列。 gengregate_type
的值是事先知道的,并且可以在相关频道上提前调用listing
。
我得到的错误说“频道名称不能为空”。我想这是因为触发器为每个语句而不是每行都运行。
有没有办法为语句触发器做这项工作吗?我认为有趣的部分是可能会插入几行,而Postgres不知道应该选择哪种价值?
这个问题类似于使用pg_notify trigger中的行数据频道名称?,但是我想在每个语句上运行触发器,而不是每行,因为在我的特殊情况下,gengregate_type
和gengregate_id
将是每个插件上的所有行都相同。
I'd like to create a trigger that runs whenever an INSERT
statement on a table succeeded, using the data from the insert to call pg_notify
:
CREATE OR REPLACE FUNCTION notify_updates() RETURNS TRIGGER AS $
BEGIN
PERFORM pg_notify(NEW.aggregate_type, NEW.aggregate_id::text);
RETURN NEW;
END;
$ LANGUAGE plpgsql;
CREATE OR REPLACE TRIGGER model_notification
AFTER INSERT ON events
FOR EACH STATEMENT
EXECUTE PROCEDURE notify_updates()
aggregate_type
and aggregate_id
are columns of the events
table. the values for aggregate_type
are known in advance and it's possible to call LISTEN
on the relevant channels in advance.
The error I get says "channel name cannot be empty". I guess it's because the trigger runs for each statement and not for each row.
Is there a way to make this work for statement triggers? I think the interesting part is that there might be a couple of rows that were inserted and postgres doesn't know which value it should choose?
This question is similar to Using row data in pg_notify trigger as channel name?, but I want to have the trigger run on each statement instead of each row because in my particular case the values for aggregate_type
and aggregate_id
will be the same for all rows on each insert.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要一个过渡表:
阅读文档中有关功能的更多信息:
“另外触发器将从几行构建一行。
You need a transition table:
Read more about the feature in the documentation:
Transition tables were introduced in Postgres 10. Read also Trigger that will build one row from several rows.