【问题标题】:Double INSERT using a TRANSACTION postgres使用 TRANSACTION postgres 进行双重插入
【发布时间】:2017-04-25 19:54:09
【问题描述】:

晚上好,

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

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

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

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

亲切的问候

【问题讨论】:

    标签: postgresql transactions plpgsql


    【解决方案1】:

    事务不能在 postgres 函数中启动/结束。如果您想要一些逻辑,请将其设置在函数内部。在您的情况下,您不需要任何东西 - 如果第一次插入生成异常,则事务中止。但是,如果您需要一些复杂的检查,请在代码中正确设置,例如

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

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

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

    【讨论】:

    • 但是我该如何称呼该交易呢?任何时候我需要进行这些双重插入,如果它不是一个过程,我将如何调用该事务?
    • begin; select * from insert_into_answercomments(1,2); end;
    • 谢谢。隔离级别呢?你知道什么水平吗?如何申报?
    • postgresql.org/docs/current/static/transaction-iso.html 在你的情况下,READ COMMITTED 就足够了
    • 因为如果你在事务中运行它,没有人会看到你的一半插入。而且您根本没有选择任何东西:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2017-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多