I'm trying to create the following table in PostgreSQL 13:
CREATE TABLE cached (
text VARCHAR NOT NULL,
text_hash BYTEA GENERATED ALWAYS AS (sha256(convert_to(text, 'LATIN1'))) STORED PRIMARY KEY
);
However, I'm getting the following error:
generation expression is not immutable
I'm guessing that this is because convert_to is not immutable. How do I work around this? Is there a way of converting the text column to bytea in an immutable way?
Things I'd rather avoid:
- Casting to
text::bytea. It won't work correctly as explained here. - Using triggers.
convert_to(text, 'LATIN1')is as problematic as::bytea. What iftextuses a different collation? What if it's UTF8? That cast will mangle the text unless it's LATIN1 or all characters are in the US-ASCII range. Even English names can't be represented in the US-ASCII range, egCharlotte Brontëconvert_to(text, 'LATIN1')and mark itIMMUTABLEand then do(sha256(conv_txt(text))). You will have to accept the consequences if thetextstrays from the expected.digestfrom pgcrypto extension. As intext_hash BYTEA GENERATED ALWAYS AS (digest(text, 'sha256')) STORED PRIMARY KEY