Re: complex referential integrity constraints - Mailing list pgsql-general

From Tom Lane
Subject Re: complex referential integrity constraints
Date
Msg-id 8196.1171822101@sss.pgh.pa.us
Whole thread Raw
In response to complex referential integrity constraints  ("Robert Haas" <Robert.Haas@dyntek.com>)
List pgsql-general
"Robert Haas" <Robert.Haas@dyntek.com> writes:
> ... The problem with this is that I have a very unsettled feeling about the
> foreign key constraints on this table.  The victim_id constraint is
> fine, but the attacker_id constraint is really inadequate, because the
> attacker CAN NEVER BE A SHEEP.

I think the only way to do this in SQL is to denormalize a bit.  If you
copy the animal_type field into the maulings table then you can apply a
check constraint there.  So

 FOREIGN KEY (attacker_id, attacker_type_id) REFERENCES animal (id, type_id)
 ON UPDATE CASCADE

 CHECK (attacker_type_id != 'sheep')

The thing that's still a bit annoying is that you'd have to hard-wire
the numerical code for SHEEP into the check constraint; you couldn't
really write it symbolically as I did above.  Perhaps you should further
denormalize and keep real animal type names not codes in the animal
type table, thus

CREATE TABLE animal_type (
    name            varchar(80) primary key
);

CREATE TABLE animal (
    id            serial,
    type                varchar(80) references animal_type,
    ...
);

whereupon the maulings table also has real type names not IDs.

No doubt some relational-theory maven will come along and slap your
wrist for doing this, but he should first explain how to do it without
denormalization...

Also, I think what you've really done here is created a "poor man's
enum".  There will probably be real enum types in PG 8.3, which would
offer a more efficient solution to the problem of representing animal
types.

            regards, tom lane

pgsql-general by date:

Previous
From: Guido Neitzer
Date:
Subject: Re: Database performance comparison paper.
Next
From: elein
Date:
Subject: Re: complex referential integrity constraints