I am creating a trigger in Postgres and would like to turn all columns into JSON to insert into a single column of the 'LOG' table, I would like to for example 'OLD. *' in JSON and add it in the oldvalue column 'of the LOG table.
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();