Re: Constraint to ensure value does NOT exist in another table?

From: "Gauthier, Dave" <dave(dot)gauthier(at)intel(dot)com>
To: Peter Geoghegan <peter(at)2ndquadrant(dot)com>
Cc: Igor Neyman <ineyman(at)perceptron(dot)com>, Mike Christensen <mike(at)kitchenpc(dot)com>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: Constraint to ensure value does NOT exist in another table?
Date: 2011-06-16 14:16:18
Message-ID: 482E80323A35A54498B8B70FF2B8798004CED8A08B@azsmsx504.amr.corp.intel.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I preferred the check constraint mainly because of the feedback "violation" messages. Other, more traditional constraints exist on other columns of the table. The names of those constraints contain information about the nature of the violation. I wanted to standardize the way I detected these violations and parse out the information. So I just added check constraints with names that followed the naming convention and always look for traditional constraint violation messages in my perl/DBI script.

No, no explicit locking, but as I said, the table being querried is static.

-----Original Message-----
From: Peter Geoghegan [mailto:peter(at)2ndquadrant(dot)com]
Sent: Thursday, June 16, 2011 9:56 AM
To: Gauthier, Dave
Cc: Igor Neyman; Mike Christensen; pgsql-general(at)postgresql(dot)org
Subject: Re: [GENERAL] Constraint to ensure value does NOT exist in another table?

On 16 June 2011 14:41, Gauthier, Dave <dave(dot)gauthier(at)intel(dot)com> wrote:
> I've dealt with something similar by using a check constraint and a stored procedure.  The check constraint calls a stored procedure, passing it (in your case) the key you want to make sure doesn't exist in some other table.  The stored procedures queries that other table for the key and passes back a YES/NO flag that the check constraint detects and acts on (constraint violated or not).
>
> I'm not using this to check a prim/foreign key relationship for my app, and the table that the stored procedure is querying is a ref table that is very static.  This approach may not be bullet proof for checking key relationships in dynamic tables.  I'll let others speak to that.

Did you use explicit locking? If not, you likely have a race
condition. The same applies to any sort of enforcement of business
rules inside triggers (or, indeed, check constraints). Check
constraints are generally intended to enforce simple, immutable rules
(i.e. that only reference the tuple that the rule is enforced on). I
would have used a trigger instead.

--
Peter Geoghegan       http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training and Services

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Grzegorz Jaśkiewicz 2011-06-16 15:05:19 Re: PostgreSQL 9.0 or 9.1 ?
Previous Message Achilleas Mantzios 2011-06-16 14:06:31 PostgreSQL 9.0 or 9.1 ?