Logs in postgresql

Asked

Viewed 79 times

1

Good morning Everybody, I have a trigger to log in INSERT, UPDATE and DELETE in the postgresql, but the way I’m logging in, it’s as if the bank’s own user had done the operation. I needed to be saved the system user who modified them.

Creating a schema for the table CREATE SCHEMA logging;

Table creation

CREATE TABLE logging.logs (
        id              serial,
        data            timestamp without timezone DEFAULT now(),
        schema          text,
        tabela          text,
        operacao        text,
        usuario         text DEFAULT current_user <--- pegando o usuário do banco,
        valor_novo      json,
        valor_antigo    json
);

Creation of the function

CREATE FUNCTION change_trigger() RETURNS trigger AS $$
       BEGIN
         IF TG_OP = 'INSERT'
         THEN INSERT INTO logging.logs (
                tabela, schema, operacao, valor_novo
              ) VALUES (
                TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW)
              );
           RETURN NEW;
         ELSIF  TG_OP = 'UPDATE'
         THEN INSERT INTO logging.logs (
             tabela, schema, operacao, valor_novo, valor_antigo
           )
           VALUES (TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(NEW), row_to_json(OLD));
           RETURN NEW;
         ELSIF TG_OP = 'DELETE'
         THEN INSERT INTO logging.logs
             (tabela, schema, operacao, valor_antigo)
             VALUES (
               TG_RELNAME, TG_TABLE_SCHEMA, TG_OP, row_to_json(OLD)
             );
             RETURN OLD;
         END IF;
       END;
$$ LANGUAGE 'plpgsql' SECURITY DEFINER;

Creating the Trigger in the desired table

CREATE TRIGGER t BEFORE INSERT OR UPDATE OR DELETE ON tabela_exemplo
        FOR EACH ROW EXECUTE PROCEDURE change_trigger();

The user table is in the app schema, ie I access so -> app.users.

Thank you in advance.

  • If you don’t want the current_user from the bank then modify your commands INSERT and include usuario in the list of fields and the user value of the system you want to put in the table.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.