Re: Avoid deadlocks on alter table

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
Cc: Christian Castelli <voodoo81people(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Avoid deadlocks on alter table
Date: 2016-07-05 15:24:17
Message-ID: 31624.1467732257@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com> writes:
> On 07/05/2016 06:30 AM, Christian Castelli wrote:
>> ALTER TABLE smartphone
>> ADD CONSTRAINT pk_smartphone PRIMARY KEY (id),
>> ADD CONSTRAINT fk1 FOREIGN KEY (id_contact)
>> REFERENCES contact (id) MATCH SIMPLE
>> ON UPDATE RESTRICT ON DELETE RESTRICT,
>> ADD CONSTRAINT fk_plan FOREIGN KEY (id_tf)
>> REFERENCES public.tariff_plan(id) MATCH SIMPLE
>> ON UPDATE RESTRICT ON DELETE RESTRICT,
>> ADD CONSTRAINT fk_ram FOREIGN KEY (ret_id)
>> REFERENCES ram (id) MATCH SIMPLE
>> ON UPDATE RESTRICT ON DELETE RESTRICT,
>> ADD CONSTRAINT u_imei UNIQUE (imei_code);

> Does the table smartphone have data in it when you do the above ALTER?

I doubt it would matter. The problem with this is that it needs to take
exclusive lock on each one of the referenced tables (so as to add a new
foreign-key enforcement trigger). So any other transaction that is
accessing any two of those tables in a different order than this does
creates a deadlock hazard.

> Have you looked at separating the FK creation and validation?:

I think it'd likely be enough to add the FKs one at a time, rather
than all in one transaction.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Sfiligoi, Igor 2016-07-05 16:21:56 Re: --EXTERNAL--Re: PSQL does not remove obvious useless joins
Previous Message J. Cassidy 2016-07-05 14:54:21 pg_dump fundenental question