Skip to content

Instantly share code, notes, and snippets.

@igponce
Created December 15, 2014 23:55
Show Gist options
  • Save igponce/0b3ac09c09394edd8ba2 to your computer and use it in GitHub Desktop.
Save igponce/0b3ac09c09394edd8ba2 to your computer and use it in GitHub Desktop.
Simple database logging with triggers
-- Simple database logging to a table via Triggers (PostgresSQL)
-- Create tables --
create table tbl1 ( id integer, name varchar(20), ssn integer );
create table tbl1_logcopy ( modified date, id integer, name varchar(20), ssn integer );
-- Populate --
insert into tbl1 values ( 1, '123', 1000);
insert into tbl1 values ( 2, '234', 2000);
insert into tbl1 values ( 3, '345', 3000);
insert into tbl1 values ( 4, '456', 4000);
insert into tbl1 values ( 5, '567', 5000);
insert into tbl1 values ( 6, '678', 6000);
insert into tbl1 values ( 7, '789', 7000);
-- Create Trigger Function --
CREATE OR REPLACE FUNCTION log_into_tbl1_logcopy() RETURNS TRIGGER AS $$
BEGIN
INSERT INTO tbl1_logcopy VALUES ( now() , OLD.id, OLD.name, OLD.ssn );
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Activate trigger --
CREATE TRIGGER log_silently
BEFORE UPDATE OR DELETE ON tbl1
FOR EACH ROW EXECUTE PROCEDURE log_into_tbl1_logcopy();
-- Do update and see what happens with tbl1_logcopy ;-)
update tbl1 set id=1001 where id=1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment