我必须在postgres中编写一个触发器 trigger应该在rp_resourceUser表中插入值。
我有三个表rp_user,rp_resourceUser,rp_resourceType它们都在公共模式下
fields in rp_user
user_id bigint NOT NULL,
is_gtl boolean,
is_tsc_admin boolean,
username character varying(255) NOT NULL,
gtl_user_id bigint,
fields in rp_resource_type
resource_type_id bigint NOT NULL,
resource_template text,
resource_type character varying(255),
fields in rp_resource_user_type
resource_user_type_id bigint NOT NULL,
gtl_user_id bigint NOT NULL,
resource_type_id bigint NOT NULL,
user_id bigint NOT NULL,
CONSTRAINT rp_resource_user_type_pkey PRIMARY KEY (resource_user_type_id),
CONSTRAINT fk6t2cd10tfar76hvvchyo81u66 FOREIGN KEY (user_id)
REFERENCES public.rp_user (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fkb273dt5c7b9s49jlwf1cmbxib FOREIGN KEY (gtl_user_id)
REFERENCES public.rp_user (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT fkmbxelxexffw96mcgcu3y25ixl FOREIGN KEY (resource_type_id)
REFERENCES public.rp_resource_type (resource_type_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT uk994khkskqm5c77mlyipwxu0dv UNIQUE (user_id, gtl_user_id, resource_type_id)
因此,当设置用户表中的gtl标志而不是rp_resource_user_type中的插入值时触发器的条件
我写过类似的东西
CREATE TRIGGER gtlPermission AFTER UPDATE ON rp_user.is_gtl
FOR EACH ROW
WHEN (public.rp_user.is_gtl IS true)
EXECUTE PROCEDURE setGtlPermission();
Create or Replace Function setGtlPsermission () RETURNS TRIGGER AS $rp_resource_user_type$
BEGIN
INSERT INTO rp_resource_user_type(resource_user_type_id, gtl_user_id, resource_type_id,user_id)
VALUES (new.resource_user_type_id, rp_user.gtl_user_id, rp_resource_type.resource_type_id ,rp_user.user_id);
RETURN NEW;
END;
$rp_resource_user_type$ LANGUAGE plpgsql;
我之前从未写过触发器,所以我甚至不知道那是不是......所以需要建议
答案 0 :(得分:0)
new.resource_user_type_id
将无效... CREATE TRIGGER gtlPermission AFTER UPDATE ON rp_user FOR EACH ROW WHEN (public.rp_user.is_gtl IS true) EXECUTE PROCEDURE setGtlPermission();
WITH c as (select * from rp_user join rp_resource_type on some not existing so far key) INSERT INTO rp_resource_user_type (gtl_user_id, resource_type_id,user_id) select gtl_user_id, resource_type_id ,user_id from c where c.user_id = NEW.user_id;
rp_resource_type
(你是如何引用它的)这让我怀疑加入NEW的所需行将缺席,因此不会插入新行进入rp_user
表永远...... 我建议你首先在所有三个表上手动操作数据,记下操作和要求的顺序,首先改进模式(特别是使用FK和序列),然后再回到创建触发器。