1
I am creating a Trigger in Postgres and would like to turn all columns into JSON to insert in a single column of table 'LOG', I would like to turn for example 'OLD.*' into JSON and add it in column 'oldvalue' of table LOG.
create table log_table (
tablename varchar(200),
oldvalue varchar(200),
newvalue varchar(200),
operation varchar(10),
user_id integer
);
CREATE OR REPLACE FUNCTION teste_log() RETURNS TRIGGER AS $$
BEGIN
IF (TG_OP = 'DELETE') THEN
INSERT INTO log_table VALUES(TG_TABLE_NAME, TG_OP, user, OLD.*);
RETURN OLD;
ELSIF (TG_OP = 'UPDATE') THEN
INSERT INTO log_table VALUES(TG_TABLE_NAME, TG_OP, user, NEW.*);
RETURN NEW;
ELSIF (TG_OP = 'INSERT') THEN
INSERT INTO log_table VALUES(TG_TABLE_NAME, TG_OP, user, NEW.*);
RETURN NEW;
END IF;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER teste_log
AFTER INSERT OR UPDATE OR DELETE ON public.*
FOR EACH ROW EXECUTE PROCEDURE teste_log();