Functions on tables

From: "Brendan Jurd" <direvus(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Functions on tables
Date: 2006-12-16 17:52:11
Message-ID: 37ed240d0612160952m3d2e58a6t890b7dbcafdb951a@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2006-12-16 18:11:29 Re: Functions on tables
Previous Message Shachar Shemesh 2006-12-16 08:39:39 Re: [Oledb-dev] A major rewrite of the Postgres OLE DB Provider.