Re: Dynamically accessing columns from a row type in a trigger - Mailing list pgsql-general

From Adrian Klaver
Subject Re: Dynamically accessing columns from a row type in a trigger
Date
Msg-id 068f5479-5b58-6084-1141-fd320b722782@aklaver.com
Whole thread Raw
In response to Dynamically accessing columns from a row type in a trigger  ("Rhys A.D. Stewart" <rhys.stewart@gmail.com>)
Responses Re: Dynamically accessing columns from a row type in a trigger
List pgsql-general
On 8/12/23 13:09, Rhys A.D. Stewart wrote:
> Greetings all,
> 
> I am writing a trigger and would like to know how to dynamically
> access a column from the "OLD" variable. pk_col is the column name
> from the table.
> 
> I've come up with either doing this:
> EXECUTE format('SELECT $1.%1$I', pk_col) INTO pk_val USING OLD;

Got focused on pk_val = OLD[pk_col] and missed the low hanging fruit:

pk_val = OLD.pk_col

> 
> which looks a bit excessive, or this
> 
> pk_val = to_jsonb(OLD.*)->pk_col
> 
> which looks cleaner, but then I am having to incur a little overhead
> by using the to_jsonb function. Ideally, something like this would be
> great:
> 
> pk_val = OLD[pk_col]
> 
> but evidently we can't subscript ROW types.
> 
> Am I missing out on a simpler or more elegant solution?
> 
> Rhys
> Peace & Love | Live Long & Prosper
> 
> 

-- 
Adrian Klaver
adrian.klaver@aklaver.com




pgsql-general by date:

Previous
From: Adrian Klaver
Date:
Subject: Re: Dynamically accessing columns from a row type in a trigger
Next
From: Miles Elam
Date:
Subject: Re: A Good Beginner's Book