Re: Polymorphic "setof record" function? - Mailing list pgsql-general

From Merlin Moncure
Subject Re: Polymorphic "setof record" function?
Date
Msg-id b42b73150901150459y2a9cb793gc65d72e37b6a056c@mail.gmail.com
Whole thread Raw
In response to Re: Polymorphic "setof record" function?  (Christian Schröder <cs@deriva.de>)
List pgsql-general
On Thu, Jan 15, 2009 at 4:57 AM, Christian Schröder <cs@deriva.de> wrote:
> Merlin Moncure wrote:
>>> them.
>>>  I need something like:
>>>   select * from myfunc('mytable') as x(like mytable)
>>>  or
>>>   select * from myfunc('mytable') as x(mytable%TYPE)
>>>
>>>  Is there any solution for PostgreSQL 8.2?
>>>
>>
>> Unfortunately to the best of my knowledge there is no way to do this.
>>  I think what you want is to have sql functions that specialize on
>> type in the way that templates do in C++.
>>
>
> That would certainly be the best solution, but I would also be happy with
> some syntactic sugar: The function may still be declared as returning a set
> of records, so that I would still have to declare their actual return type
> in the query. However, I would like to have an easy way to express: "the
> record will have the same structure as table x".

There is a circuitous way to do this that sometimes works.  Declare
your function to return text and do this inside the function body (for
example):

create or replace function func() returns text as
$$
  select foo::text from foo limit 5;
$$ language sql;

select func::foo from (select func()) q;

Couple of notes here:
*) obviously, the idea here is to use dynamic-sql to return different
table types based on inputs
*) can only upcast to one table per function call (but can return
varying record types based if left in text)
*) record::text casts I think were introduced in 8.3.  There is a more
complex way to do it in 8.2 that is probably not worth the effort.
*) record::text casts are not really reflexive.  null fields are an
issue or example.

merlin

pgsql-general by date:

Previous
From: Sam Mason
Date:
Subject: Re: Select CASE when null ?
Next
From: "A. Kretschmer"
Date:
Subject: Question regarding new windowing functions in 8.4devel