Re: Unexpected behavior when combining `generated always` columns and update rules

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: Ciprian Craciun <ciprian(dot)craciun(at)gmail(dot)com>, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>, "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
Cc: "pgsql-general(at)lists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Unexpected behavior when combining `generated always` columns and update rules
Date: 2023-04-13 16:57:02
Message-ID: 263a7885-8001-89b8-17cc-29865c36c93d@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 4/13/23 09:27, Ciprian Craciun wrote:
> On Thu, Apr 13, 2023 at 5:32 PM David G. Johnston
> <david(dot)g(dot)johnston(at)gmail(dot)com> wrote:
>> ALSO rules behave like before triggers, not after triggers. The original command is appended to the end of the list of commands, not the start.
>
>
> As Tom observed, the documentation states that in case of update
> rules, the original query is executed at the end.
>
> However, regardless of the order of the execution between new and
> original query, as per the documentation the `new` table should
> contain the new values regardless.
>
> In fact, from my example above, one can see that the `y.x` is properly
> updated with the new value, meanwhile the `y.d` is the previous one
> (i.e. `old.d`).
>
> So, based on these observations, I think that `generated always`
> columns are actually computed on insertion, and thus they are not
> reflected in `new` on rules.

That is not the case:

create table x (x int, d int generated always as (x * 10) stored);
insert into x (x) values (1);
select * from x;

x | d
---+----
1 | 10

update x set x = 2 where x = 1;
select * from x;

x | d
---+----
2 | 20

What I believe is happening is that the generated always is not done
until the original query is run after the rule action. So at the time of
the rule action x.d is still 10.

What this points out is that you will lead a simpler life if you use
triggers instead of rules.

>
> Ciprian.
>
>

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2023-04-13 17:03:25 Re: Unexpected behavior when combining `generated always` columns and update rules
Previous Message Ciprian Craciun 2023-04-13 16:27:37 Re: Unexpected behavior when combining `generated always` columns and update rules