Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
Double INSERT using a TRANSACTION postgres

Good evening,

I want to create a TRANSACTION with the proper isolation level. On that transaction I want to do a double insert and if one fails the other one is aborted.

I have a stored procedure already created:

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

My doubt is if the transaction should be inside the function or if it is a different procedure. How do I create it with a correct isolation level.

Kind Regards

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

transaction cannot be started/ended inside postgres function. If you want some logic, make it inside function. In your case you don't need anything - if first insert generates exception, transaction aborts. But if you need some sophisticated check, make it right in code, eg

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

to run function in transaction start it outside, eg:

begin;
select * from insert_into_answercomments(1,2);
end;
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda