Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1ob1Pn-0007LD-Tj for pgsql-general@arkaria.postgresql.org; Wed, 21 Sep 2022 15:13:31 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1ob1Pl-0007bz-Mb for pgsql-general@arkaria.postgresql.org; Wed, 21 Sep 2022 15:13:29 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1ob1Pl-0007bo-Bx for pgsql-general@lists.postgresql.org; Wed, 21 Sep 2022 15:13:29 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1ob1Pc-000376-5i for pgsql-general@lists.postgresql.org; Wed, 21 Sep 2022 15:13:25 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 28LFCmdt1078306; Wed, 21 Sep 2022 11:12:48 -0400 From: Tom Lane To: Laurenz Albe cc: Louis Tian , "pgsql-general@lists.postgresql.org" Subject: Re: PostgreSQL Rule does not work with deferred constraint. In-reply-to: <0d52121503f0babc9ce3eeb0753067edb56d6e8e.camel@cybertec.at> References: <0d52121503f0babc9ce3eeb0753067edb56d6e8e.camel@cybertec.at> Comments: In-reply-to Laurenz Albe message dated "Wed, 21 Sep 2022 11:26:12 +0200" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <1078304.1663773168.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Wed, 21 Sep 2022 11:12:48 -0400 Message-ID: <1078305.1663773168@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Laurenz Albe writes: > I just tried your commands, and it works as you expect on my PostgreSQL = v15 database. It does fail for me, but I think it's a well-known trap rather than a bug (or at least, it's not something that anyone wishes to redesign the rule system to change). The problem is that *a rule is a macro* and therefore it's subject to multiple-evaluation hazards. Your volatile default expression does not play nice with that. Initially you have: insert into "children" values (default); Replacement of the "default" produces: insert into "children" values (gen_random_uuid()); Now the DO ALSO rule produces: insert into "parent" (id) values (gen_random_uuid()); The two insertions will compute different random UUIDs, and kaboom. We tend to recommend using triggers not rules to implement this sort of behavior; they are less prone to surprises. regards, tom lane