3

I have a table test_data with 4 columns as shown below. I want to create a JSONB generated column with data from these columns. Below is what I have tried but keep on getting this error:

ERROR: generation expression is not immutable SQL state: 42P17

name VARCHAR(50) mixed_stuff JSONB other_stuff JSONB created TIMESTAMP combined JSONB
CREATE TABLE test_data(name VARCHAR(50), mixed_stuff JSONB, other_stuff JSONB, created TIMESTAMP WITHOUT TIMEZONE default(now() at time zone 'utc'));

ALTER TABLE test_data
add combined JSONB GENERATED ALWAYS AS (jsonb_build_object('name',name) || "mixed_stuff" || "other_stuff" || jsonb_build_object('created',created)) STORED;
1

1 Answer 1

2

Generated columns can only use immutable functions (docs) while jsonb_build_object() is only marked as stable (run \df+ jsonb_build_object in psql to check).

As a workaround one can define a wrapper function marked as immutable (but beware of consequences depending on your usage scenario):

CREATE FUNCTION jsonb_build_object_imm(VARIADIC input anyarray) RETURNS JSONB AS $$
  SELECT jsonb_build_object(VARIADIC input)
$$
LANGUAGE SQL IMMUTABLE PARALLEL SAFE;

The reason why jsonb_build_object() is only stable because to_json() is only stable as many other type conversions -- compare with json_object() which takes only strings and is marked as immutable.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.