Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 0D8C01337B81 for ; Tue, 4 Jan 2011 11:21:41 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 33084-01 for ; Tue, 4 Jan 2011 15:21:32 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 928DA1337B47 for ; Tue, 4 Jan 2011 11:21:32 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id p04FLTBb009849; Tue, 4 Jan 2011 10:21:30 -0500 (EST) To: Florian Weimer cc: kakarukeys , pgsql-performance@postgresql.org Subject: Re: adding foreign key constraint locks up table In-reply-to: <8239p8rd2f.fsf@mid.bfk.de> References: <75218696-61be-4730-89f6-dd6058fa9eda@a28g2000prb.googlegroups.com> <82ei926j3p.fsf@mid.bfk.de> <19238.1293548900@sss.pgh.pa.us> <8239p8rd2f.fsf@mid.bfk.de> Comments: In-reply-to Florian Weimer message dated "Tue, 04 Jan 2011 13:52:24 +0000" Date: Tue, 04 Jan 2011 10:21:29 -0500 Message-ID: <9848.1294154489@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201101/11 X-Sequence-Number: 41798 Florian Weimer writes: > * Tom Lane: >> ALTER ADD FOREIGN KEY must lock both tables to add triggers to them. > But why is such a broad lock needed? If the table was created in the > current transaction and is empty, the contents of the foreign key > table should not matter. It's not about content, it's about having reproducible results. We cannot commit an ADD TRIGGER operation when there are table-modifying queries already in progress, because they might (will) fail to notice the trigger. If you don't believe this is a problem, consider the following sequence of events: 1. Session 1 issues "DELETE FROM pk WHERE true". It fetches the table definition, sees there are no triggers, and begins to execute the DELETE. Now it goes to sleep for awhile. 2. Session 2 issues ALTER TABLE fk ADD FOREIGN KEY pk. If it doesn't take a lock on pk that would exclude the concurrent DELETE, it can fall through and commit before session 1 makes any more progress. 3. Session 2 inserts some rows in fk. They are valid since the matching rows in pk are valid (and not yet even marked for deletion). 4. Session 1 wakes up and finishes its DELETE. Not knowing there is any committed trigger on pk, it performs no FK checking. Now you have rows in fk that violate the foreign key constraint. regards, tom lane