When i try execute this script, i get an error: ERROR: relation "old" does not exist. Script:
update organization
set row_status = 30;
I found some question like this, but their dont help me. My trigger:
Create OR REPLACE function PMigrateDataToHistory()
returns trigger as $PMigrateDataToHistory$
begin
insert into organization_history
select
*
from
OLD;
delete
from
organization as org USING
OLD as o
where
o.id = org.id and
o.version = org.version;
insert into organization
select
n.id,
n.created_at,
n.updated_at,
n.row_status,
n.version + 1,
n.resource
from
NEW as n;
end;
$PMigrateDataToHistory$ LANGUAGE plpgsql;
CREATE TRIGGER TRMigrateDataToHistory AFTER update or delete ON organization
FOR EACH ROW EXECUTE PROCEDURE PMigrateDataToHistory();
For the first
INSERT
, use something likeThe
DELETE
and the secondINSERT
are ill-conceived – for one, this will cause a lot of unnecessary churn in theorganization
table.It would be much better to use a
BEFORE
trigger, add 1 toNEW.version
and returnNEW
. This would cause the values to be adjusted before the record is written to the table.You are mis-understanding what
OLD
andNEW
are: those aren't tables, it is the row that has been inserted or modified.However you do not need to delete and insert everything. Just increment the version in a BEFORE trigger.
Then you can simplify your trigger to:
You need a BEFORE trigger for that:
The process when you delete a row doesn't make sense to me. The current code does the following:
delete from organization
is executed and the row is deletedafter
trigger, so the row is already gone from the table)The same behaviour can be achieved by the simply incrementing the version in the before trigger. If you want to prevent deletion completely simply return
null
in the before trigger: