Re: BUG #1447: Sometimes rules don't work - Mailing list pgsql-bugs

From Tom Lane
Subject Re: BUG #1447: Sometimes rules don't work
Date
Msg-id 27649.1107041533@sss.pgh.pa.us
Whole thread Raw
In response to BUG #1447: Sometimes rules don't work  ("Olleg Samoylov" <olleg@mipt.ru>)
Responses Re: BUG #1447: Sometimes rules don't work
List pgsql-bugs
"Olleg Samoylov" <olleg@mipt.ru> writes:
> create rule history_i as on insert to history do (update abonent set
> money=money+new.money where abonent=new.abonent);

> insert into history (abonent,money) select abonent,-(money.money+5) as pay
> from
>     ( select abonent,sum(money) as money from history where money<0 group by
> abonent) money
>     where money.money+5>0;

What happens in the above is that the "new.money" placeholder is
replaced by the subselect from the INSERT command, and since the rule
fires after the insert itself is done, you get different results from
the second evaluation of the subselect.

You should be using a trigger for this sort of thing, not a rule.
Rules have their uses, but propagating copies of data from one place
to another is generally not one of them.  It's too easy to get bit by
the fact that a rule is a macro and thus subject to multiple-evaluation
gotchas.

            regards, tom lane

pgsql-bugs by date:

Previous
From: Michael Fuhr
Date:
Subject: Re: Error messages
Next
From: "John Hansen"
Date:
Subject: Bug in create operator and/or initdb