gpt4 book ai didi

postgresql - postgres - 防止规则/触发器调用自己 - 无限循环

转载 作者:行者123 更新时间:2023-11-29 11:41:01 25 4
gpt4 key购买 nike

假设我有下表:

create table A
(
identifier integer not null primary key,
title text not null,
... -- other fields
);

在 A 上执行 UPDATE 时,我不一定只想更新目标行,但我还想将更新应用到 A 中的另一行。我尝试编写“重写规则”或“触发前”,但我总是以无限循环结束:

create function A(in A, in A) returns void as
$$
declare
i integer;
begin
-- do some logic which finds other row (hardcoded in this example)
i = 2;

-- update old row
update A set title = $2.title where identifier = $1.identifier;

-- apply updates to other row
update A set ... where identifier = i;
end;
$$ language plpgsql;

create rule A as on update to A do instead select A(old, new);

我测试的数据:

insert into A (identifier, title) values (1, 'old title 1');
insert into A (identifier, title) values (2, 'old title 2');

update A set title = 'new title 1' where identifier = 1;

当使用“触发前”而不是“重写规则”时,也会出现同样的问题。

有没有办法在需要时绕过规则/触发器?我无法在第一行之后更改表 A 禁用规则 A 并在返回之前更改表 A 启用规则 A,因为表 A 正在被我们自己使用。

更新

我设法通过创建一个虚拟继承表来做到这一点,而不是直接在表上完成“内部更新”。这绕过了触发器/规则。

    drop table if exists A cascade;

create table A
(
identifier serial not null primary key,
title text not null
);

create table A_
(

) inherits (A);

create or replace function A() returns trigger as
$$
declare
i integer;
begin
-- create duplicate row
insert into A (title) values (new.title) returning identifier into i;

-- update new row
update A_ set title = new.title where identifier = i;

-- do not propagate update
return null;
end
$$ language plpgsql;

create trigger A before update on A for each row execute procedure A();

insert into A (title) values ('old title 1');
insert into A (title) values ('old title 2');

update A set title = 'new title 1' where identifier = 1;

select * from A;

最佳答案

为了避免触发器中的无限循环,您需要添加一个额外的 where 子句以避免多次重新影响一行:

update foo
set bar = 'baz'
where bar <> 'baz'

无法避免规则中的递归,因为在解析原始查询(和新查询)时会抛出新查询,而没有考虑各个查询的 where 子句。

关于postgresql - postgres - 防止规则/触发器调用自己 - 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6805799/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com