1
I’m using a function to audit records at Insert, update, delete events for a Postgres 9.6.
I got the script on Git - Audit-Trigger
The script has been implemented and is working perfectly, but one of the results it brings me in the audit log is:
"id"=>"2", "ende"=>"Rua 2 de julho", "nome"=>"Amanda", "senha"=>"1234", "telefone"=>"069", "estaativo"=>"t", "ultimaalteracao"=>"2018-06-21 09:50:15.677835"
How to make the result a JSON:
{
"id":2,
"ende":"Rua 2 de julho",
"nome":"Amanda",
"senha":"1234",
"telefone":"08799919991",
"estaativo":true,
"ultimaalteracao":"2018-06-21 09:50:15.677835"
}
I already tried to change the script obtained above using the function row_to_json
, follows the amendment:
IF (TG_OP = 'UPDATE' AND TG_LEVEL = 'ROW') THEN
--audit_row.row_data = hstore(OLD.*) - excluded_cols;
audit_row.row_data = hstore(row_to_json(OLD)) - excluded_cols;
-- audit_row.changed_fields = (hstore(NEW.*) - audit_row.row_data) - excluded_cols;
audit_row.changed_fields = (hstore(row_to_json(NEW)) - audit_row.row_data) - excluded_cols;
IF audit_row.changed_fields = hstore('') THEN
-- All changed fields are ignored. Skip this update.
RETURN NULL;
END IF;
ELSIF (TG_OP = 'DELETE' AND TG_LEVEL = 'ROW') THEN
--audit_row.row_data = hstore(OLD.*) - excluded_cols;
audit_row.row_data = hstore(row_to_json(OLD)) - excluded_cols;
ELSIF (TG_OP = 'INSERT' AND TG_LEVEL = 'ROW') THEN
--audit_row.row_data = hstore(NEW.*) - excluded_cols;
audit_row.row_data = hstore(row_to_json(NEW)) - excluded_cols;
ELSIF (TG_LEVEL = 'STATEMENT' AND TG_OP IN ('INSERT','UPDATE','DELETE','TRUNCATE')) THEN
audit_row.statement_only = 't';
ELSE
RAISE EXCEPTION '[audit.if_modified_func] - Trigger func added as trigger for unhandled case: %, %',TG_OP, TG_LEVEL;
RETURN NULL;
END IF;
INSERT INTO audit.logged_actions VALUES (audit_row.*);
RETURN NULL;
The error obtained is:
Just remembering that the
hstore
, as link given in the reply, is part of the additional modules (also collectively called "contrib"), and to use it is necessary to install/compile such modules (packagepostgresql-contrib
in Ubuntu e.g. ) and then create the extension in your database with the commandCREATE EXTENSION hstore;
– nunks