pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: mtesfaye@gmail.com
Cc: pgsql-bugs@postgresql.org
Subject: Re: BUG #7662: INSERT rule doesn't work as expected
Date: Thu, 15 Nov 2012 12:04:48 -0500
Message-ID: <17774.1352999088@sss.pgh.pa.us> (raw)
In-Reply-To: <E1TZ2cE-0001oY-1M@wrigleys.postgresql.org>
References: <E1TZ2cE-0001oY-1M@wrigleys.postgresql.org>

mtesfaye@gmail.com writes:
> ON INSERT RULE doesn't always work as expected.
> The reasoning for this particular rule was to add the new value to an
> existing value if it is determined that the key already exists.

> CREATE OR REPLACE RULE "dup_add_test_r_rule" AS 
>   ON INSERT TO test_r
>   WHERE 
>     EXISTS(SELECT 1 FROM test_r a WHERE a.id=NEW.id) 
>     DO INSTEAD 
>        (UPDATE test_r a SET val=a.val+NEW.val WHERE a.id=NEW.id);

Per the manual:

	For ON INSERT rules, the original query (if not suppressed by INSTEAD)
	is done before any actions added by rules. This allows the actions to
	see the inserted row(s). 

So the behavior in your example is 

(1) The EXISTS test fails, so the INSERT is allowed to execute.

(2) Now the EXISTS test passes, so the UPDATE is allowed to execute.

This might not be what you wished would happen, but it's not a bug;
it's the way rules are defined to work.  You might have better luck
with a BEFORE INSERT trigger.

			regards, tom lane




view thread (2+ messages)

Message-ID: <17774.1352999088@sss.pgh.pa.us>
Permalink:  ../17774.1352999088@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/17774.1352999088@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-bugs@postgresql.org
  Cc: tgl@sss.pgh.pa.us, mtesfaye@gmail.com
  Subject: Re: BUG #7662: INSERT rule doesn't work as expected
  In-Reply-To: <17774.1352999088@sss.pgh.pa.us>
  References: <E1TZ2cE-0001oY-1M@wrigleys.postgresql.org> <17774.1352999088@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox