postgres create rule on insert do nothing if exists insert otherwise; RETURNING id

两盒软妹~` 提交于 2021-01-29 20:30:07

问题


In Postgres, is it possible to CREATE RULE which does nothing if some key exists but inserts otherwise. In either case it should return the id of the inserted/skipped row.

I need a rule, so please do not give alternates. I currently have the below rule that does nothing on conflicting inserts and I want to perform an insert with RETURNING id clause but I am getting the below error

ERROR:  cannot perform INSERT RETURNING on relation "fco_assets"
HINT:  You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.
********** Error **********

ERROR: cannot perform INSERT RETURNING on relation "fco_assets"
SQL state: 0A000
Hint: You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.

Below is my current rule

CREATE OR REPLACE RULE table_ignore AS
ON INSERT TO table
WHERE (EXISTS ( SELECT 1
       FROM table
      WHERE table.key::text = new.key::text)) DO INSTEAD NOTHING;

Thanks

来源:https://stackoverflow.com/questions/59846085/postgres-create-rule-on-insert-do-nothing-if-exists-insert-otherwise-returning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!