views:

402

answers:

1

Hi guys, i have this simple plpgsql function:

CREATE FUNCTION "update_times" () RETURNS trigger AS '
    BEGIN
        NEW.update_time = NOW();
        RETURN NEW;
    END;'
LANGUAGE "plpgsql";

--The trigger:
CREATE TRIGGER test_update_time BEFORE UPDATE ON contact FOR EACH ROW EXECUTE PROCEDURE update_times();

and this works well, but only with BEFORE triggers...

I prefern to fire the trigger after the update, so i changed the function and the trigger itself as:

CREATE FUNCTION "update_times_after" () RETURNS trigger AS '
    BEGIN
        OLD.update_time = NOW();
        RETURN OLD;
    END;'
LANGUAGE "plpgsql";

--The trigger:
CREATE TRIGGER test_update_time_after AFTER UPDATE ON contact FOR EACH ROW EXECUTE PROCEDURE update_times_after();

But the AFTER trigger dont work (the trigger dont fire or the function fail).

What i am doing wrong?

A: 

After trigger is run when the data is already saved to table. So no modification (especially on OLD.!) doesn't make any sense.

If you want to change the data that is save to disk, you have to do it BEFORE it is saved.

depesz
Yes but i want to update the 'update_time' field when the update sql has been executed and the data is been saved...
DaNieL
Not sure if I understand. And what is the difference between before and after in this case?Anyway - if you want to modify the row that is being saved to table, it should be done in BEFORE trigger.
depesz
Ops.. sorry my bad, i have misread the documentation.. i thought that the BEFORE trigger was fired before updating the row, so if the query fail the trigger would be fired anyway. My bad.
DaNieL
It is still possible that the query will fail after some of the "before" triggers will run. But it's not a problem.
depesz