2

I have table with a lot of columns. I want to create a function which returns all these column, with an additional column. Is there a way to do this type-safe (that is, without returning a record) without having to repeat all column names and types?

For example:

create table t
(
    t1 int,
    t2 int,
    t3 text,
    t4 boolean
);

create function extra_t() returns table(t1 int, t2 int, t3 text, t4 boolean, extra text) as
$$
    select t.*, 'example'::text from t;
$$ language sql

It's quite annoying that I have to repeat t1 int, t2 int, t3 text, t4 boolean in the function definition.

Katrin
  • 125
  • 4

1 Answers1

2

I am with you in your struggle, and I don't know of a good way to do this.

That said, this is a hacky way to do this. It does shift the burden of specifying individual fields in the return type to the actual function text, but it does make the whole thing a bit more digestible, in my opinion.

create table t2 (
  extra_text text
) inherits (t);

create or replace function extra_t() returns setof t2 as
$$
    select t.*, 'example'::text from t;
$$ language sql;

Like I said, it's not a good way. It's just a way.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
Hambone
  • 15,600
  • 8
  • 46
  • 69