Re: Restrict FOREIGN KEY to a part of the referenced table

From: Richard Broersma <richard(dot)broersma(at)gmail(dot)com>
To: Matthias Nagel <matthias(dot)h(dot)nagel(at)gmail(dot)com>
Cc: sql pgsql <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Restrict FOREIGN KEY to a part of the referenced table
Date: 2013-04-12 19:52:16
Message-ID: CABvLTWFB4YSPq+=zThKsG6+oqPuauC91a8Yr=L-_6U_Gf-djCQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Thu, Apr 11, 2013 at 12:55 AM, Matthias Nagel <matthias(dot)h(dot)nagel(at)gmail(dot)com
> wrote:

>
> Working solution:
>
> CREATE TABLE child (
> id SERIAL NOT NULL,
> parent_id INT NOT NULL,
> parent_discriminator INT NOT NULL DEFAULT 42,
> attribute2 VARCHAR,
> ...,
> FOREIGN KEY ( parent_id, parent_discriminator ) REFERENCES parent ( id,
> discriminator ),
> CHECK ( parent_discriminator = 42 )
> );
>
>
> The third solution work, but I do not like it, because it adds an extra
> column to the table that always contains a constant value for the sole
> purpose to be able to use this column in the FOREIGN KEY clause.

True.

On the one hand this is a waste of memory and on the other hand it is not
> immediately obvious to an outside person what the purpose of this extra
> column and CHECK clause is. I am convinced that any administrator who
> follows me might get into problems to understand what this is supposed to
> be.
>

If you need to improve documentation for this you have two options that can
help the future admin:

replace: CHECK ( parent_discriminator = 42 )
with: CONSTRAINT "These children only like parents of type 42"
CHECK( parent_discriminator = 42)

or: COMMENT ON TABLE child "Your explanation goes here.";

If you need to hide this column from you uses, you can use a view.

--
Regards,
Richard Broersma Jr.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Robins Tharakan 2013-04-12 20:59:27 Clarity on how LOCK interacts with INHERIT
Previous Message Jasen Betts 2013-04-12 13:53:19 Re: Restrict FOREIGN KEY to a part of the referenced table