Reputation: 2415
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:
text::bytea
. It won't work correctly as explained here.Upvotes: 2
Views: 377
Reputation: 132
CREATE OR REPLACE FUNCTION cripto(TEXT )
RETURNS TEXT AS
$function$
DECLARE tText TEXT ;
BEGIN
SELECT sha256(convert_to($1, 'LATIN1')) INTO tText;
RETURN tText ;
END ;
$function$
IMMUTABLE
LANGUAGE plpgsql ;
CREATE TABLE cripto(
text TEXT ,
text_hash TEXT GENERATED ALWAYS AS ( cripto(text) ) STORED PRIMARY KEY
);
Upvotes: 3