Re: Record with a field consisting of table rows

From: Alban Hertroys <dalroi(at)solfertje(dot)student(dot)utwente(dot)nl>
To: Jon Smark <jon(dot)smark(at)yahoo(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Record with a field consisting of table rows
Date: 2011-01-13 19:21:30
Message-ID: 8C29A75C-3589-4993-9A70-DFE14900BB31@solfertje.student.utwente.nl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 13 Jan 2011, at 17:22, Jon Smark wrote:

> create type page_t AS
> (
> total int4,
> users user_t[]
> );
>
> create function get_page ()
> returns page_t
> language plpgsql as
> $$
> declare
> _page page_t;
> begin
> _page.total := select count (*) from users;
> select * into _page.users from users limit 10;
> return _page;
> end
> $$;

I think it would be easier to rewrite that to a set-returning function returning TABLE (...).

Something like this (untested):

create function get_page ()
returns setof table (total int, user users)
language plpgsql as
$$
declare
_total int;
begin
_total := select count (*) from users;

return query select _total AS total, u from users AS u limit 10;
end
$$;

In general it is considered a bad idea to rely on what * returns though, it's better to return the columns explicitly.

Which makes me wonder, is table cloning supported for these cases? For example:

create function get_page ()
returns setof table (LIKE users, total int)
...

Alban Hertroys

--
Screwing up is an excellent way to attach something to the ceiling.

!DSPAM:737,4d2f50bf11877227918328!

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Alban Hertroys 2011-01-13 19:38:10 Re: Record with a field consisting of table rows
Previous Message Pavel Stehule 2011-01-13 19:21:23 Re: Record with a field consisting of table rows