Re: Virtual generated columns - Mailing list pgsql-hackers

From Peter Eisentraut
Subject Re: Virtual generated columns
Date
Msg-id 51c29cda-6933-4a22-b31a-4a0f783880ca@eisentraut.org
Whole thread Raw
In response to Re: Virtual generated columns  (jian he <jian.universality@gmail.com>)
List pgsql-hackers
On 14.11.24 09:48, jian he wrote:
> inspired by not-null and check check_modified_virtual_generated again.
> 
> in plpgsql_exec_trigger, we can:
>          /*
>           * In BEFORE trigger, stored generated columns are not computed yet,
>           * so make them null in the NEW row.  (Only needed in UPDATE branch;
>           * in the INSERT case, they are already null, but in UPDATE, the field
>           * still contains the old value.)  Alternatively, we could construct a
>           * whole new row structure without the generated columns, but this way
>           * seems more efficient and potentially less confusing.
>           */
>          if (tupdesc->constr && tupdesc->constr->has_generated_stored &&
>              TRIGGER_FIRED_BEFORE(trigdata->tg_event))
>          {
>              for (int i = 0; i < tupdesc->natts; i++)
>              {
>                  if (TupleDescAttr(tupdesc, i)->attgenerated ==
> ATTRIBUTE_GENERATED_STORED ||
>                      TupleDescAttr(tupdesc, i)->attgenerated ==
> ATTRIBUTE_GENERATED_VIRTUAL)
>                      expanded_record_set_field_internal(rec_new->erh,
>                                                         i + 1,
>                                                         (Datum) 0,
>                                                         true,    /* isnull */
>                                                         false, false);
>              }
>          }
> then we don't need check_modified_virtual_generated at all.
> 
> this will align with the stored generated column behave for
> BEFORE UPDATE/INSERT FOR EACH ROW trigger. that is
> you are free to assign the virtual generated column any value,
> but at the plpgsql_exec_trigger, we will rewrite it to null.
> 
> also i understand correctly.
> later if we want to implement virtual generated column with not-null then
> check_modified_virtual_generated needs to be removed?

The purpose of check_modified_virtual_generated() for trigger functions 
written in C.  The prevent someone from inserting real values into the 
trigger tuples, because they would then be processed by the rest of the 
system, which would be incorrect.

Higher-level languages such as plpgsql should handle that themselves, by 
preventing setting generated columns in trigger functions.  The presence 
of check_modified_virtual_generated() is still a backstop for those, but 
shouldn't really be necessary.



pgsql-hackers by date:

Previous
From: Peter Eisentraut
Date:
Subject: Re: Virtual generated columns
Next
From: Dean Rasheed
Date:
Subject: Re: revamp row-security tracking