Re: FK check implementation - Mailing list pgsql-general

From Tom Lane
Subject Re: FK check implementation
Date
Msg-id 24799.1412951564@sss.pgh.pa.us
Whole thread Raw
In response to FK check implementation  (Nick Barnes <nickbarnes01@gmail.com>)
Responses Re: FK check implementation
List pgsql-general
Nick Barnes <nickbarnes01@gmail.com> writes:
> I'm looking at the code behind the foreign key checks in ri_triggers.c, and
> something's got me a little confused.

> In both cases (FK insert/update checking the PK, and PK update/delete
> checking the FK) the check is done with a SELECT ... FOR KEY SHARE.

> This makes perfect sense for PK checks, but in the FK check, it seems
> pointless at best; if it actually manages to find something to lock, it
> will fail the check and error out moments later. And in any case, I don't
> see how the key fields in the FK relation (to which the KEY SHARE lock
> applies) are even relevant to the constraint in question.

> What am I missing?

Race conditions.

Example case: you're trying to delete the row for PK 'foo', while
concurrently somebody is inserting a row that references foo.  With
no locking, neither of you will see the other action, hence both
will conclude their action is ok and commit.  Presto: FK violation.

The point of the FOR SHARE lock (which also goes along with some
cute games played with the query's snapshot) is to make sure there
aren't uncommitted changes that would result in an FK violation.
We could possibly have done it another way but that would just have
resulted in two generally-similar mechanisms.

            regards, tom lane


pgsql-general by date:

Previous
From: Merlin Moncure
Date:
Subject: Re: PostgreSQL server won't start, corrupt?
Next
From: Emi Lu
Date:
Subject: org.postgresql.copy.CopyManager which JDBC version ?