F
F
furyon2015-01-02 12:57:51
PostgreSQL
furyon, 2015-01-02 12:57:51

How to create an UPDATE trigger without recursion in Postgres?

Hello!
In general procedure and trigger

CREATE FUNCTION advs__up_is_paid_mode() RETURNS TRIGGER
AS $$
BEGIN
  IF NEW.balance<NEW.amount THEN
    UPDATE advs SET is_paid_mode=0 WHERE id=NEW.id;
  ELSE
    UPDATE advs SET is_paid_mode=1 WHERE id=NEW.id;
  END IF;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER advs__up_is_paid_mode__trigger
AFTER INSERT OR UPDATE
ON advs
FOR EACH ROW
EXECUTE PROCEDURE advs__up_is_paid_mode();

In a nutshell, what's going on here:
On each update, it checks if balance < amount then is_paid_mode=0 otherwise 1 .
But when I update, I get an error about stack depth limit exceeded . I suspect that this procedure falls into a recursion.
How to be? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Melkij, 2015-01-02
@furyon

id is the primary key? Those. Should I change this very line? Then before insert or update and NEW changes itself:

IF NEW.balance<NEW.amount THEN
    NEW.is_paid_mode=0;
  ELSE
    NEW.is_paid_mode=1;
  END IF;
RETURN NEW;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question