I'd recommend adding id field as a primary key to audit tables, since you need to reference to the emp
table when rolling back to it and you also need that emp
to reference corresponding version of emp_addr
.
So audit table DDLs should look like this:
/* Audit table for emp table */
create table emp_audit (
id bigserial,
operation character(1),
updatetime timestamp,
emp_id integer,
version varchar(50),
CONSTRAINT audit_emp_id PRIMARY KEY (id)
);
/* Audit table for emp_addr table */
create table emp_addr_audit (
id bigserial,
operation character(1),
addr_id integer,
emp_id integer,
line1 varchar(30),
CONSTRAINT fk_ audit_emp_id FOREIGN KEY emp_audit_id
REFERENCES emp_audit (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
);
Next you will need to create a trigger, to store changes. Note, that you will have to monitor changes in both tables and create references to the corresponding stored records.
CREATE TRIGGER t_audit_emp_IUD
AFTER INSERT OR UPDATE OR DELETE -- probably u want only update. Not sure
ON emp
FOR EACH ROW
EXECUTE PROCEDURE emp_modified();
CREATE TRIGGER t_audit_emp_addr_IUD
AFTER INSERT OR UPDATE OR DELETE
ON emp_addr
FOR EACH ROW
EXECUTE PROCEDURE emp_addr_modified();
And finally define the functions. Note, that functions should be stored in database before triggers, since triggers reference to the functions.
Rollback function should take emp_audit.id
as an input and restore the state according to the audit table. It would be a good idea to save state before rolling back to prevent possible data loss.
If this doesn't answer your question, please clarify which part do you actually need help with.