Given I have a table User with column status (active/inactive)
these users may be attached with some other entities, so I do not want them to get modified unless explicitly specified.
and for attaching to newer entities I only need the latest updated ones.
So when an UPDATE is performed, I want to make the existing row inactive,
and INSERT the updated values as a new row.
I am using PostgreSQL
Best Answer
This is not very complicated to do. If a BEFORE trigger returns a NULL value, this prevents the UPDATE from taking place.
So in the trigger function you can check the conditions if an UPDATE is allowed. If not, Run an
UPDATE
statement that marks the row as inactive and do an INSERT.Something along the lines (not tested!):
And the trigger definition:
I would be very careful to deploy something like this. This kind of "magic" in the background might be the cause of a lot of confusion and trouble, so use with care!