Re: Allow composite foreign keys to reference a superset of unique constraint columns? - Mailing list pgsql-hackers

From Laurenz Albe
Subject Re: Allow composite foreign keys to reference a superset of unique constraint columns?
Date
Msg-id ce3b0c02b70c844a73d63249c4878d0b939dbefa.camel@cybertec.at
Whole thread Raw
In response to Re: Allow composite foreign keys to reference a superset of unique constraint columns?  (Paul Martinez <hellopfm@gmail.com>)
List pgsql-hackers
On Tue, 2021-08-17 at 10:45 -0700, Paul Martinez wrote:
> On Tue, Aug 17, 2021 at 8:41 AM Jack Christensen <jack@jncsoftware.com> wrote:
> > The only way to ensure a user can only be a member of a group in the same
> > tenant is to user_group_memberships.tenant_id be part of the foreign key. And
> > that will only work with a unique key on id and tenant_id in both users and
> > user_groups. It's a bit inelegant to create multiple extra indexes to ensure
> > consistency when existing indexes are enough to ensure uniqueness.
> 
> You could accomplish this by using composite primary keys on the users and
> user_groups tables:
> 
> CREATE TABLE users (
>   id serial,
>   tenant_id int REFERENCES tenants(id),
>   PRIMARY KEY (tenant_id, id)
> );

That is not a proper solution, because it does not guarantee uniqueness of
the "id" column, which is typically what you want.

So I think Jack's example illustrates the benefit of this proposal well.

On the other hand, the SQL standard requires that a foreign key references
a unique constraint, see chapter 11.8 <referential constraint definition>,
Syntax Rules 3) a):

 "If the <referenced table and columns> specifies a <reference column list>,
  then there shall be a one-to-one correspondence between the set of
  <column name>s contained in that <reference column list> and the set of
  <column name>s contained in the <unique column list> of a unique constraint
  of the referenced table such that corresponding <column name>s are equivalent."

So while I personally agree that the proposed feature is useful, I am not
sure if it is useful enough to break the standard in a way that may be
incompatible with future extensions of the standard.

Yours,
Laurenz Albe




pgsql-hackers by date:

Previous
From: Peter Geoghegan
Date:
Subject: Re: The Free Space Map: Problems and Opportunities
Next
From: "houzj.fnst@fujitsu.com"
Date:
Subject: RE: pgsql: pgstat: Bring up pgstat in BaseInit() to fix uninitialized use o