1

I have this table definition in pgAdmin4:

CREATE TABLE IF NOT EXISTS cdr_event
(
    id bigint primary key generated always as identity,
    start_time timestamptz NOT NULL DEFAULT now(),
    end_time timestamptz NULL,
    group_id VARCHAR(10) NOT NULL,
    environment VARCHAR(10) NOT NULL,     
    level VARCHAR(10) NOT NULL,           
    schema VARCHAR(30) NOT NULL,      
    instance INTEGER NOT NULL,            
    hive_instance_db_name VARCHAR(100) GENERATED ALWAYS AS (group_id||'_'||environment||'_'||level||'_'||schema||'_'||instance) STORED,
    hive_static_db_name VARCHAR(100) GENERATED ALWAYS AS (group_id||'_'||environment||'_'||level||'_'||schema) STORED,
);

this fails with

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

Why does postgres consider the concat mutable when the dependent columns are all NOT NULL? This thread suggests it should work

Is there anyway to create a concat-ed generated column without creating a custom concat function?

Thanks

1 Answer 1

4

Try keeping the involved columns of the same type, e.g. casting instance to text should do the trick:

CREATE TABLE IF NOT EXISTS cdr_event
(
    id bigint primary key generated always as identity,
    start_time timestamptz NOT NULL DEFAULT now(),
    end_time timestamptz NULL,
    group_id VARCHAR(10) NOT NULL,
    environment VARCHAR(10) NOT NULL,     
    level VARCHAR(10) NOT NULL,           
    schema VARCHAR(30) NOT NULL,      
    instance INTEGER NOT NULL,            
    hive_instance_db_name VARCHAR(100) GENERATED ALWAYS AS (group_id||'_'||environment||'_'||level||'_'||schema||'_'||instance::text) STORED,
    hive_static_db_name VARCHAR(100) GENERATED ALWAYS AS (group_id||'_'||environment||'_'||level||'_'||schema) STORED
);

Consider using text instead of varchar.

Demo: db<>fiddle

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

4 Comments

Only instance is the problem. And casting it to text will do. No need to cut off schema. I'm still wondering why the implicit cast would be considered not immutable though?
@stickybit that's right! I oversaw it was an integer .. thanks for pointing out. +1 just edited my answer
@stickybit I'm still wondering the same thing and still searching for an explanation :D
@JimJones thanks, that works. yeah i tested the concat worked as a select, using the implicit cast. Seems weird you need to cast it here. hey ho

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.