Functions on tables

Поиск
Список
Период
Сортировка
От Brendan Jurd
Тема Functions on tables
Дата
Msg-id 37ed240d0612160952m3d2e58a6t890b7dbcafdb951a@mail.gmail.com
обсуждение исходный текст
Ответы Re: Functions on tables  (Tom Lane <tgl@sss.pgh.pa.us>)
Список pgsql-general
In the object-relational context, the definition of a "relation" is
much the same as the idea of a "class"; the columns in a table are
analogous to the attributes of a class.  The names of Postgres' system
catalogs reflect this correlation (pg_class, pg_attribute).

Likewise, each tuple within a relation is like an instance of the class.

So I was thinking, why is it we have such a direct representation of
class attributes (in the form of columns), but no equivalent
representation of class methods?

Say you have the following table:

CREATE TABLE person (
 id serial PRIMARY KEY,
 firstname text NOT NULL,
 lastname text NOT NULL
);

Then you define a function:

CREATE FUNCTION person_name(firstname text, lastname text) RETURNS text AS $$
 SELECT $1 || ' ' || $2;
$$ LANGUAGE SQL IMMUTABLE;

So now you can do

SELECT id, person_name(firstname, lastname) AS name FROM person ORDER BY name;

That works fine, but wouldn't it be far more elegant if you could do
this instead:

CREATE TABLE person (
 id SERIAL PRIMARY KEY,
 firstname TEXT NOT NULL,
 lastname TEXT NOT NULL,
 FUNCTION name() RETURNS text AS $$ SELECT firstname || ' ' ||
lastname; $$ LANGUAGE SQL IMMUTABLE
);

Now the function name() belongs to the "person" table: it is, in
effect, a method of the "person" class.  Which means we can do this:

SELECT id, name() FROM person ORDER BY name();

Just as with methods in an OO programming language, when you call
name() on a tuple of the "person" relation, it has access to the
attributes of that tuple (here firstname and lastname).  There is no
need to pass arguments to the function, nor any need to actually know
which attributes of "person" go into making up the return value of
name().  You could later decide to add an attribute for a person's
preferred name, or middle initial, and then factor that into the logic
of name() without the query author needing to know anything about it.

Of course there would be implementation challenges, and admittedly I
haven't considered those, but on the surface this feels like a good
idea.  It taps into some of the real usefulness of OOP, and it uses a
feature we already have: user-defined functions.

I look forward to your comments.

Regards,
BJ

В списке pgsql-general по дате отправления:

Предыдущее
От: m.c.wilkins@massey.ac.nz
Дата:
Сообщение: Re: updating a view
Следующее
От: Tom Lane
Дата:
Сообщение: Re: Functions on tables