Skip to content
Advertisement

Trigger before insert in PostgreSQL and except some columns

I’m trying to write a trigger for my table. This table has 50 columns and 3 of them are timestamp type. In the future I will insert new rows and they can be duplicate of existing, so I need to compute hash of each row. My idea is to compute row’s hash in each insertion and check it’s existing, that’s why I’m writing trigger. I’d like to compute hash and write it to my main table to the last column (I created it when create table). I have one problem – I need to compute hash not for whole row, I shouldn’t use 3 columns with timestamp type (for hashing of rows I should exclude 3 columns).

I’ve just started doing it and faced a problem – I don’t know how to exclude these columns for hashing.

Advertisement

Answer

If the column names are always the same, a redirection through a JSON value makes this a bit dynamic:

has_value is the column in the target table that should store the generated hash (I used a MD5 hash).

You could make this completely dynamic by querying pg_attribute with something along the lines of:

Then use the list of columns from that query to remove the keys from the JSONB value.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement