Re: Partial foreign keys

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: rihad <rihad(at)mail(dot)ru>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Partial foreign keys
Date: 2010-02-28 20:01:14
Message-ID: 13007.1267387274@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

rihad <rihad(at)mail(dot)ru> writes:
> I want the effects of the above foo.key in every sense, but only for
> entries having foo.flag=true. So I think I'll write before-statement
> triggers to do just that instead of the key. But is data consistency
> still guaranteed as the foreign key in foo would otherwise do?

No. To take just the most obvious example, what happens when somebody
modifies or deletes the referenced row? Your trigger won't handle that
case because it won't be called.

In principle you could get most of the way there if you also hung an
ON UPDATE/DELETE trigger on the referenced table and had it do the
appropriate things. But even so, there would be race conditions that
are really insoluble in straightforward user triggers. The built-in
support for FK checking relies on triggers in these places, but the
triggers access some functionality that's not available at the SQL level
in order to handle concurrent updates correctly.

My advice is to rethink your data layout so that you don't need this.
One possibility is to keep the "flag=false" and "flag=true" rows in
two different tables, which could be made to look like one table
(at least for non-updating queries) via a view or inheritance.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Terry 2010-02-28 21:56:41 continuous copy/update one table to another
Previous Message rihad 2010-02-28 19:26:54 Re: Partial foreign keys