Re: Bug: Rule actions see wrong values for generated columns (NEW.gen reads OLD value)

From: Chao Li <li(dot)evan(dot)chao(at)gmail(dot)com>
To: Richard Guo <guofenglinux(at)gmail(dot)com>
Cc: SATYANARAYANA NARLAPURAM <satyanarlapuram(at)gmail(dot)com>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>, Peter Eisentraut <peter(at)eisentraut(dot)org>
Subject: Re: Bug: Rule actions see wrong values for generated columns (NEW.gen reads OLD value)
Date: 2026-04-13 07:21:05
Message-ID: 22B4A33A-99F3-46F5-BE0C-426A9E1D9ABA@gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

> On Apr 13, 2026, at 10:35, Richard Guo <guofenglinux(at)gmail(dot)com> wrote:
>
> On Mon, Apr 13, 2026 at 10:59 AM SATYANARAYANA NARLAPURAM
> <satyanarlapuram(at)gmail(dot)com> wrote:
>> NEW.<generated_coulmn> is resolved to the OLD row's value
>> for update or NULL for insert cases in a DO ALSO rule action for
>> generated columns. This bug affects both stored and virtual
>> generated columns. Reporting here to see if this is a known issue
>> with generated columns.
>
> I didn't find related item in open items. This does not seem to be a
> known issue. I think we should fix it anyway.
>
> cc-ing Peter.
>
> - Richard
>

Hi Richard and Satya,

I reproduced the bug following Satya’s procedure and spent some time debugging it.

I think the issue is that rewriteTargetListIU() removes generated columns from the target list, as described by this comment:
```
if (att_tup->attgenerated)
{
/*
* virtual generated column stores a null value; stored generated
* column will be fixed in executor
*/
new_tle = NULL;
}
```

Later, when the rule action is rewritten, ReplaceVarsFromTargetList() cannot find a target list entry for NEW.gen. For UPDATE rules, the missing NEW column is handled with REPLACEVARS_CHANGE_VARNO, so it falls back to referencing the original target relation row, which gives the old value.

One possible fix is to build a new target list that adds generated columns back when there are rules to fire. I tried the solution locally with some quick and dirty code and it seems to fix both stored and virtual generated columns for me.

Do either of you plan to propose a patch for this? If so, please go ahead and I can review it. Otherwise, I can propose a patch in a couple of days.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

In response to

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Hayato Kuroda (Fujitsu) 2026-04-13 07:23:39 RE: parallel data loading for pgbench -i
Previous Message vignesh C 2026-04-13 07:10:06 Re: Use XLogRecPtrIsValid() instead of negated XLogRecPtrIsInvalid