On May 6, 2010, at 10:52 , Boszormenyi Zoltan wrote:
> =# create table parent (id serial primary key, t text);
> ...
> =# create table child () inherits (parent);
> ...
> =# create table refer (id serial primary key, parent_id integer
> ...
> =# insert into child (t) values ('a') returning id;
> ...
> =# select * from parent;
> id | t
> ----+---
> 1 | a
> (1 sor)
>
> =# insert into refer (parent_id) values (1);
> ERROR: insert or update on table "refer" violates foreign key
> constraint "refer_parent_id_fkey"
> DETAIL: Key (parent_id)=(1) is not present in table "parent".
>
> The use case for this was there were different news items,
> and there were another table for summaries, that could point
> to any of the news items table. Another use case could be
> a large partitioned table with an FK to the main table where
> the referring table might only contain very few "interesting" data.
Yeah, this is a long-standing issue with inheritance. Table inheritance in postgres isn't much more than an implicit
UNIONdone on selects plus some logic in ALTER TABLE to keep propagate structural changes. Indices and constraints
basicallyalways behave as if ONLY had been specified. I'm not even sure if the ids are globally unique in your example
-it might be that each child's "id serial" column gets its very own sequence.
One possible workaround is no create a table, say referred_ids, that contains all the ids from parent and all of its
children,kept up-to-date via triggers, and point the FK constraint to that table. That also allows for a global unique
constrainton the ids by definition a suitable unique or primary key constraint on referred_ids.
What lies at the heart of this problem is the lack of multi-table indices and hence multi-table unique constraints in
postgres.AFAIK with those in place the rest amounts to the removal of ONLY from the constraint check queries plus some
codeto propagate constraint triggers to child tables.
best regards,
Florian Pflug