“invalid transaction termination” in Postgres when trying to update a value using a function

dba.stackexchange https://dba.stackexchange.com/questions/274383

Вопрос

I'm new to postgres. I defined a function like this:

CREATE OR REPLACE FUNCTION increment_count() 
  RETURNS TRIGGER LANGUAGE plpgsql 
  AS $$
   BEGIN 
     UPDATE posts SET count=count+1 WHERE pid=NEW.pid;
   COMMIT;
   END;
  $$;

This gives me error invalid transaction termination

Это было полезно?

Решение

You can not commit in a trigger, and you forgot the return statement.

CREATE OR REPLACE FUNCTION increment_count() 
  RETURNS TRIGGER LANGUAGE plpgsql 
  AS $$
    BEGIN 
      UPDATE posts SET count=count+1 WHERE pid=NEW.pid;
      return null;
    END;
  $$;

In case of a BEFORE trigger, "return NEW" should be used!

Лицензировано под: CC-BY-SA с атрибуция
Не связан с dba.stackexchange
scroll top