The use of trigger to simplify the population of timestamp during update (PostgreSQL)

Often in development, we will want to include Created and Updated columns in each of our table, for tracking and recording purpose. However, if you are like me, we cannot avoid interacting with the database outside of our code, be it we want to insert or update a record manually.

In case of PostgreSQL database, we can use function and trigger to track a particular column in a table. The function is for us to ensure that there is a new value for the Updated column, but we would not want to override a value is one is provided, we just want to ensure the Updated column is up-to-date, just in case none is provided.

Firstly, we need to create a function to provide a new value for the Updated column, if one is not given.

CREATE OR REPLACE FUNCTION UPDATED_CHANGED() RETURNS TRIGGER
    AS $$
begin
 IF NEW.UPDATED<= OLD.UPDATED THEN
    NEW.UPDATED:= NOW() AT TIME ZONE 'UTC';
   END IF;
   
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Here, we are comparing between the old Updated column's value with the new value, then assign the current date/time if necessary. Next, we should create a trigger for the table that contains the column, let's say I have a table called Foo,



CREATE TRIGGER TRIGGER_UPDATED_CHANGED
BEFORE UPDATE ON FOO
FOR EACH ROW
EXECUTE PROCEDURE UPDATED_CHANGED();

There we go, whenever there is an update to any of the record(s) in Foo, a new value would be assigned to Updated, if none is provided during update operation.

Comments

Popular posts from this blog

ASP.NET Core service locator pattern

Ways to perform eager loading via NHibernate

Caching and generic query using NHibernate [.NET Core]