Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id E39D79FB4F1 for ; Sat, 14 Oct 2006 20:49:03 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 56840-08 for ; Sat, 14 Oct 2006 20:48:57 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from tigger.fuhr.org (tigger.fuhr.org [63.214.45.158]) by postgresql.org (Postfix) with ESMTP id A9BFB9FB4D8 for ; Sat, 14 Oct 2006 20:48:56 -0300 (ADT) Received: from winnie.fuhr.org (winnie.fuhr.org [10.1.0.1]) by tigger.fuhr.org (8.13.8/8.13.8) with ESMTP id k9ENmkBg004418 (version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=OK); Sat, 14 Oct 2006 17:48:48 -0600 (MDT) Received: from winnie.fuhr.org (localhost [127.0.0.1]) by winnie.fuhr.org (8.13.8/8.13.8) with ESMTP id k9ENmjup020554; Sat, 14 Oct 2006 17:48:45 -0600 (MDT) (envelope-from mfuhr@winnie.fuhr.org) Received: (from mfuhr@localhost) by winnie.fuhr.org (8.13.8/8.13.8/Submit) id k9ENmiHS020553; Sat, 14 Oct 2006 17:48:44 -0600 (MDT) (envelope-from mfuhr) Date: Sat, 14 Oct 2006 17:48:44 -0600 From: Michael Fuhr To: PostgreSQL SQL List Cc: Joost Kraaijeveld Subject: Re: Foreign key reference counting strategy? Message-ID: <20061014234844.GA20342@winnie.fuhr.org> References: <1160828741.28838.9.camel@panoramix> <4530EB84.4050904@logix-tt.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <4530EB84.4050904@logix-tt.com> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.142 tagged_above=0 required=5 tests=AWL, SPF_PASS X-Spam-Level: X-Archive-Number: 200610/134 X-Sequence-Number: 26523 On Sat, Oct 14, 2006 at 03:52:04PM +0200, Markus Schaber wrote: > Joost Kraaijeveld wrote: > > Is there a strategy to implement reference counting for foreign keys so > > that if the last reference to the key is deleted, the record is deleted > > also? > > Create an "after delete" trigger on the referencing table that checks > whether there still are records with the same key (IF EXISTS()), and > deletes the referenced row otherwise. In a concurrent environment that delete can fail with a foreign key constraint violation because IF EXISTS won't see uncommitted changes in other transactions. If changes in another transaction reference the same key then the delete will block until the other transaction commits or rolls back; if the other transaction commits then the delete will fail. In PL/pgSQL you can trap that failure with an EXCEPTION clause that catches foreign_key_violation. -- Michael Fuhr