HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to pass the current row to Generated Column function in Postgres?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
generatedthepostgrespasscolumnfunctioncurrenthowrow

Problem

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
);

Solution

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.

Code Snippets

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;

Context

StackExchange Database Administrators Q#315057, answer score: 6

Revisions (0)

No revisions yet.