使用 TRANSACTION postgres 双重插入

Double INSERT using a TRANSACTION postgres

晚上好,

我想创建一个具有适当隔离级别的事务。在那个交易中,我想做一个双插入,如果一个失败,另一个被中止。

我已经创建了一个存储过程:

create or replace function insert_into_answercomments(userid INTEGER, answerid INTEGER, body text)
  returns void language plpgsql as $$
DECLARE result INTEGER;
  insert into publications(body, userid)
  VALUES (body, userid)
  returning publications.publicationid AS publicationid INTO result;

  insert into comments(publicationid) VALUES (result);

  insert into answercomments(commentid, answerid) VALUES (result, answerid);
end $$;

我怀疑交易是否应该在函数内部,或者它是否是一个不同的过程。如何使用正确的隔离级别创建它。

亲切的问候

事务不能在 postgres 函数中 started/ended。如果你想要一些逻辑,把它放在函数内部。在你的情况下你不需要任何东西 - 如果第一次插入产生异常,事务中止。但是,如果您需要一些复杂的检查,请在代码中进行正确的设置,例如

if result > 90 then
  insert ...second insert
end if;

到运行函数在事务外启动它,例如:

begin;
select * from insert_into_answercomments(1,2);
end;