Re: Avoid deadlocks on alter table - Mailing list pgsql-general

From Tom Lane
Subject Re: Avoid deadlocks on alter table
Date
Msg-id 31624.1467732257@sss.pgh.pa.us
Whole thread Raw
In response to Re: Avoid deadlocks on alter table  (Adrian Klaver <adrian.klaver@aklaver.com>)
List pgsql-general
Adrian Klaver <adrian.klaver@aklaver.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


pgsql-general by date:

Previous
From: Adrian Klaver
Date:
Subject: Re: Avoid deadlocks on alter table
Next
From: "Sfiligoi, Igor"
Date:
Subject: Re: --EXTERNAL--Re: PSQL does not remove obvious useless joins