Re: Call a Normal function inside a Trigger Function

From: Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>
To: FOUTE K(dot) Jaurès <jauresfoute(at)gmail(dot)com>
Cc: PostgreSQL General <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Call a Normal function inside a Trigger Function
Date: 2023-04-16 19:13:20
Message-ID: CAFj8pRAap4pNytvqLZ7GTSfO7kagyZzC6Ggkp1R6OC_Y=dqNPA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hi

ne 16. 4. 2023 v 20:47 odesílatel FOUTE K. Jaurès <jauresfoute(at)gmail(dot)com>
napsal:

> Can I have an example please? Or a link
>
> On Sun, 16 Apr 2023, 17:08 Pavel Stehule, <pavel(dot)stehule(at)gmail(dot)com> wrote:
>
>> Hi
>>
>>
>> ne 16. 4. 2023 v 16:15 odesílatel FOUTE K. Jaurès <jauresfoute(at)gmail(dot)com>
>> napsal:
>>
>>> Hello,
>>>
>>> Is it possible to call a function inside a trigger function ?
>>> Any idea or link are welcome. Thanks in advance
>>>
>>
>> sure, there is not any limit.
>>
>
CREATE OR REPLACE FUNCTION allow_update(d date)
RETURNS bool AS $$
BEGIN
RETURN EXTRACT(YEAR FROM d) = EXTRACT(YEAR FROM current_date);
END;
$$ LANGUAGE plpgsql;

-- allow update record only from current year
CREATE OR REPLACE FUNCTION trg_func()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
IF NOT allow_update(NEW.inserted) THEN
RAISE EXCEPTION 'cannot insert';
END IF;
ELSE IF TG_OP = 'UPDATE' THEN
IF NOT allow_update(NEW.inserted) OR NOT allow_update(OLD.inserted)
THEN
RAISE EXCEPTION 'cannot update';
END IF;
ELSE
IF NOT allow_update(OLD.inserted) THEN
RAISE EXCEPTION 'cannot delete';
END IF;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER AFTER INSERT OR UPDATE OR DELETE ON sometab
FOR EACH ROW EXECUTE FUNCTION trg_func();

Regards

Pavel

p.s. You can do everything in trigger - Postgres is not Oracle where there
were some issues (if my memory serves well). There is only one risk -
possible recursion

>> Regards
>>
>> Pavel
>>
>>
>>>
>>> Best Regards
>>> --
>>> Jaurès FOUTE
>>>
>>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message FOUTE K. Jaurès 2023-04-16 19:22:27 Re: Call a Normal function inside a Trigger Function
Previous Message Adrian Klaver 2023-04-16 19:13:12 Re: Call a Normal function inside a Trigger Function