UPDATE trigger function
CREATE OR REPLACE FUNCTION fu_person()
RETURNS trigger
LANGUAGE plpgsql
AS $function$
BEGIN
IF NEW.audit_id = OLD.audit_id THEN
UPDATE person_hst
SET
address = NEW.address,
date_of_birth = NEW.date_of_birth,
person_id = NEW.person_id,
name = NEW.name
WHERE person_hst.person_id = NEW.person_id
AND person_hst.audit_id = NEW.audit_id
AND person_hst.effective_until = 'infinity';
ELSE
UPDATE person_hst
SET effective_until = (
SELECT timestamp
FROM audit
WHERE audit.audit_id = NEW.audit_id
)
WHERE person_hst.person_id = NEW.person_id
AND effective_until = 'infinity';
INSERT INTO person_hst (
effective_until,
effective_from,
address,
audit_id,
date_of_birth,
person_id,
name
) SELECT
'infinity' AS effective_until,
audit.timestamp,
NEW.address,
NEW.audit_id,
NEW.date_of_birth,
NEW.person_id,
NEW.name
FROM audit
WHERE audit_id = NEW.audit_id;
END IF;
RETURN NEW;
END;
$function$
;