I am trying to create a hashed column consisting of other column values to use as a unique constraint for a table in PG14. This is a simplified example of what I am going for:
CREATE TABLE test (
id CHARACTER VARYING,
code CHARACTER VARYING,
"deletedAt" TIMESTAMPTZ,
"hash" CHARACTER VARYING GENERATED ALWAYS AS
(((sha256((COALESCE("code", 'NULL')::text || date_part('epoch', COALESCE("deletedAt", '1990-01-01 00:00:00+00' AT TIME ZONE 'UTC'))::text)::bytea)::bytea)::text)) STORED,
PRIMARY KEY (id)
)
Which results in this error:
ERROR: generation expression is not immutable
After reading some other stack O posts I understand that the issue with creating this generated column is due to the fact that the deletedAt
column is timezone specific, thus not immutable since this setting can change. What I am trying to do is use the epoch date which I figured would not be timezone specific but I am still getting this error and adding in AT TIME ZONE 'UTC'
was a bit of a hail mary.
I had also seen that Postgres 14 has a built in function called hash_record_extended
which can do this hashing for me resulting in a bigint. This sounds great but I am curious on how to get my current case working.
Any help is much appreciated, thank you!