ADD FOREIGN KEY locking

From: James Sewell <james(dot)sewell(at)lisasoft(dot)com>
To: PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: ADD FOREIGN KEY locking
Date: 2015-02-17 23:57:26
Message-ID: CANkGpBsVe=eS3NDaaHJGKJwPPyQxb_E_7caVSR2GnFkkb9LFAw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hello all,

When I add a FK with a statement like this:

ALTER TABLE a ADD FOREIGN KEY (id) REFERENCES b(id);

I see a lock on table b:

select locktype,mode,granted from pg_locks, pg_stat_activity where
relation::regclass::text = 'b' AND pg_locks.pid = pg_stat_activity.pid;

locktype | relation
mode | AccessShareLock
granted | t
query | SOME LONG RUNNING QUERY WHICH SELECTS FROM b

locktype | relation
mode | AccessExclusiveLock
granted | f
query | ALTER TABLE a ADD FOREIGN KEY (id) REFERENCES b(id);

This means that my add key won't complete until my long running query does.
That seems a bit odd to me? In this database there are lots of
datawarehouse type queries running, which makes it a bit hard for me to
schedule this operation.

Is this just a manifestation of adding the key being in an ALTER TABLE,
which always needs an AccessExclusiveLock? Or am I missing some edge case
when this lock would be required in this circumstance?

No real urgency on this question, I just found it a bit strange and thought
someone might be able to shed some light.

James Sewell,
Solutions Architect
______________________________________

Level 2, 50 Queen St, Melbourne VIC 3000

*P *(+61) 3 8370 8000 *W* www.lisasoft.com *F *(+61) 3 8370 8099

--

------------------------------
The contents of this email are confidential and may be subject to legal or
professional privilege and copyright. No representation is made that this
email is free of viruses or other defects. If you have received this
communication in error, you may not copy or distribute any part of it or
otherwise disclose its contents to anyone. Please advise the sender of your
incorrect receipt of this correspondence.

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message James Sewell 2015-02-18 00:06:38 Re: ADD FOREIGN KEY locking
Previous Message Jim Nasby 2015-02-17 23:49:40 Re: Configurable location for extension .control files