As PostgreSQL doesn't dump object creation date so I want to manually dump user creation date by using trigger and functions. I have created trigger and functions but it's not working.
CREATE TABLE user_audits (
usesysid INT GENERATED ALWAYS AS IDENTITY,
usename varchar NOT NULL,
created_on TIMESTAMP(6) NOT NULL
);
============================
CREATE OR REPLACE FUNCTION user_creation()
RETURNS TRIGGER
LANGUAGE PLPGSQL
AS
$$
BEGIN
IF NEW.usename <> OLD.usename THEN
INSERT INTO user_audits(usesysid,usename,created_on)
VALUES(usesysid,usename,now());
END IF;
RETURN NEW;
END;
$$
=================================
CREATE TRIGGER user_creation
BEFORE UPDATE
ON user
FOR EACH ROW
EXECUTE PROCEDURE user_creation();
This is important for audit purpose, for now I am using log file to check creation date but it will rotate after sometime. Please suggest the better way to dump user creation date in table so that I can retrieve the information anytime. Thanks
I created a similar excercise with the following tables:
user_tbltable having only a identity columnusersysidand theusernameuser_auditstable, slightly modified version of yours: where i added anididentity field. I removed the identity from theusersysidfield (since it'll be populated with the one coming fromuser_tbl)Now the function, I check if the
OLD.usernameis null, this means that is an insert, ifNEW.username <> OLD.usernamethen is an update.And finally the trigger, which is fired both on
INSERTorUPDATENow if I create two new rows and update one with the following
I end up with the
user_tblcontaining the 2 expected rowsand the
user_auditstables containing 3 rows (2 for the insert + 1 for the update)