如何编写嵌套的PostgreSQL规则?

时间:2015-11-12 18:37:18

标签: postgresql

在Postgresql 9.4中运行以下简单规则:

create table a1 (id int);
create table a2 (id int);
create table a3 (id int);
create view a0 as select * from a1;

insert into a1 values (1), (2), (3);
insert into a2 select * from a1;
insert into a3 select * from a1;

Create or replace rule a0_delete as
on delete to a0 do instead (
    delete from a1 where id = old.id;
    delete from a2 where id = old.id;
    delete from a3 where id = old.id;
    select a1.id, a2.id, a3.id
    from a1 
    left join a2 using(id)
    left join a3 using(id);
);

delete from a0 where id = 2;

第一次跑步后我无法采取任何行动,我也不知道为什么。 虽然文档http://www.postgresql.org/docs/9.4/static/rules-update.html指出它是可能的,但我无法找到包含多个操作的示例。

有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

多命令规则可以完美运行。你可以尝试这个脚本:

create table a1 (id int);
create table a2 (id int);
create table a3 (id int);

insert into a1 values (1), (2), (3);
insert into a2 select * from a1;
insert into a3 select * from a1;

create or replace rule a1_delete as
on delete to a1 do instead (
    insert into a1 values (old.id* 2);
    delete from a2 where id = old.id;
    delete from a3 where id = old.id;
    select a1.id, a2.id, a3.id
    from a1 
    left join a2 using(id)
    left join a3 using(id);
);

delete from a1 where id = 2;

获得预期结果:

CREATE TABLE
CREATE TABLE
CREATE TABLE
INSERT 0 3
INSERT 0 3
INSERT 0 3
CREATE RULE
 id | id | id 
----+----+----
  1 |  1 |  1
  2 |    |   
  3 |  3 |  3
  4 |    |   
(4 rows)

DELETE 1

您应该在规则的第二个命令中查找逻辑错误。