2017-04-25 493 views
0

晚上好,使用交易的双重插入postgres

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

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

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 $$; 

我的疑问是,如果该交易应该是里面的功能,或者如果它是一个不同的过程。我如何使用正确的隔离级别来创建它。

亲切的问候

回答

1

交易不能启动/里面的Postgres函数结束。如果你想要一些逻辑,使其在功能。在你的情况下,你不需要任何东西 - 如果第一次插入生成异常,事务将中止。但是,如果你需要一些复杂的检查,作出正确的代码,例如

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

运行在交易功能之外启动它,比如:

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

但我怎么才能称之为交易?任何时候我需要做这些双重插入,如果它不是一个过程,我将如何调用该交易? –

+0

'''开始; select * from insert_into_answercomments(1,2); 结束;''' –

+0

谢谢。隔离级别呢?你有什么想法是什么水平?我如何申报? –