Re: Polymorphic function calls - Mailing list pgsql-hackers

From Sergey Konoplev
Subject Re: Polymorphic function calls
Date
Msg-id CAL_0b1ucG8epj_HQc3GgKeORU88Abraysq8nX=-Ke=mrMhcYZA@mail.gmail.com
Whole thread Raw
In response to Polymorphic function calls  (knizhnik <knizhnik@garret.ru>)
Responses Re: Polymorphic function calls
List pgsql-hackers
On Sun, Dec 29, 2013 at 8:44 AM, knizhnik <knizhnik@garret.ru> wrote:
> create function volume(r base_table) returns integer as $$ begin return
> r.x*r.y; end; $$ language plpgsql strict stable;
> create function volume(r derived_table) returns integer as $$ begin return
> r.x*r.y*r.z; end; $$ language plpgsql strict stable;

[...]

> Execution plans of first and second queries are very similar.
> The difference is that type of r_1 in first query is "base_table".
> It is obvious that query should return fixed set of columns, so
>
>     select * from base_table;
>
> can not return "z" column.
> But passing direved_table type instead of base_table type to volume()
> function for record belonging to derived_table seems to be possible and not
> contradicting something, isn't it?

Correct.

Postgres chooses a function based on the passed signature. When you
specify base_table it will choose volume(base_table) and for
base_table it will be volume(derived_table) as well.

FYI, there is a common practice to follow the DRY principle with
inheritance and polymorphic functions in Postgres. On your example it
might be shown like this:

create function volume(r base_table) returns integer as $$ begin
return r.x*r.y;
end; $$ language plpgsql strict stable;

create function volume(r derived_table) returns integer as $$ begin
return volume(r::base_table) *r.z;
end; $$ language plpgsql strict stable;

-- 
Kind regards,
Sergey Konoplev
PostgreSQL Consultant and DBA

http://www.linkedin.com/in/grayhemp
+1 (415) 867-9984, +7 (901) 903-0499, +7 (988) 888-1979
gray.ru@gmail.com



pgsql-hackers by date:

Previous
From: Tom Lane
Date:
Subject: Re: [COMMITTERS] pgsql: Upgrade to Autoconf 2.69
Next
From: Kevin Grittner
Date:
Subject: Re: [BUG FIX] Version number expressed in octal form by mistake