Postgres 12+ supports generated columns: https://www.postgresql.org/docs/current/ddl-generated-columns.html
From the docs, the syntax seems limited - it forces one to explicitly name the columns on which the generated column depends.
CREATE TABLE people (
...,
height_cm numeric,
height_in numeric GENERATED ALWAYS AS (height_cm / 2.54) STORED
);
Is there a way to pass the entire row to the generating function? Something like
CREATE TABLE people (
...,
height_cm numeric,
height_in numeric GENERATED ALWAYS AS generator_function(current_row) STORED
);
1 Answer 1
This doesn't seem possible.
If it did work, it could only work by first creating the table, then the function, then adding the generated column.
However, doing that:
CREATE TABLE people
(
id int,
height_cm numeric
);
create function generator_function(p_row people)
returns numeric
as
$$
select p_row.height_cm / 2.54;
$$
language sql
immutable;
alter table people
add height_in numeric GENERATED ALWAYS AS (generator_function(people)) STORED;
Results in:
ERROR: cannot use whole-row variable in column generation expression
Detail: This would cause the generated column to depend on its own value.
So, this does not seem to be possible.
-
1"This would cause the generated column to depend on its own value." Ah, that makes a lot of sense!Pragy Agarwal– Pragy Agarwal2022年07月31日 20:00:25 +00:00Commented Jul 31, 2022 at 20:00
Explore related questions
See similar questions with these tags.
x_tsvector()
convertors that take a row from tablex
and produce a tsvector. Sadly, postgres doesn't support fancy metaprogramming. :( dba.stackexchange.com/questions/302599/…