I need to track changes to records in a table. What I did was create a second table that inherits from the first and adds a revision counter.
CREATE TABLE A (
id SERIAL,
foo TEXT,
PRIMARY KEY (id));
CREATE TABLE B (
revision INTEGER NOT NULL) INHERITS (A);
Then I created a trigger that will update table B every time A is inserted / updated. What I cannot understand is how to get B.revision to maintain an individual "sequence" for each identifier.
Example: table A has 2 rows, i and j.
I have been updated 3 times and should have 3 revisions: (1, 2, 3).
j has been updated 2 times and should have two revisions: (1, 2).
That's what I still have, maybe I'm going the wrong way, and someone can help me!
CREATE OR REPLACE FUNCTION table_update() RETURNS TRIGGER AS $table_update$
DECLARE
last_revision INTEGER;
BEGIN
SELECT INTO last_revision MAX(revision) FROM B WHERE id = NEW.id;
IF NOT FOUND THEN
last_revision := 0;
END IF;
INSERT INTO B SELECT NEW.*;
RETURN NEW;
END;
$table_update$ LANGUAGE plpgsql;
CREATE TRIGGER table_update
AFTER INSERT OR UPDATE ON A
FOR EACH ROW EXECUTE PROCEDURE table_update();