Re: tables referenced from insert...returning - Mailing list pgsql-general

From Michael Shulman
Subject Re: tables referenced from insert...returning
Date
Msg-id c3f821000806231942h279d5d50j7053c60455e1a81@mail.gmail.com
Whole thread Raw
In response to Re: tables referenced from insert...returning  (Tom Lane <tgl@sss.pgh.pa.us>)
Responses Re: tables referenced from insert...returning  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-general
On Mon, Jun 23, 2008 at 8:46 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Hmm ... that might be a bug, but in any case, wouldn't it be wiser to do
>
> CREATE RULE _insert AS ON INSERT TO tv DO INSTEAD
>  INSERT INTO test (name) VALUES (NEW.name) RETURNING test.*;

Well, what I'm really trying to do is write a rule for inserting into
a multi-table view which has a meaningful RETURNING clause.  Looking
back at the documentation for NEW, I see you are right that even if it
worked, this wouldn't do what I want.  Guess I'll have to try to
figure out something else.

> Multiple evaluations of NEW in the text of a rule are a great way
> to cause yourself trouble --- consider what happens if there's
> a volatile function such as nextval() involved.

Ouch!  I didn't realize that multiple references to NEW were actually
translated by the rule system into multiple *evaluations* of the
supplied arguments.  Are there reasons one might desire that behavior?

I can think of simple situations in which one would *not* want such
multiple evaluation.  For example, a rule on table1 which logs all
modifications of table1 to table1_log would be naturally written as

CREATE RULE log AS ON INSERT TO table1 DO ALSO
  INSERT INTO table1_log (new_value,...) VALUES (NEW.value,...);

(This is very close to the example of an ON UPDATE rule given in the
manual.)  But apparently if I then say

INSERT INTO table1 SET value = volatile_function();

the volatile function will be evaluated twice, and the value logged
may not be the same as the value actually inserted.  This seems
counterintuitive to me; I would expect the supplied arguments to be
evaluated once and the resulting values substituted wherever NEW
appears.

Mike

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: tables referenced from insert...returning
Next
From: Tom Lane
Date:
Subject: Re: tables referenced from insert...returning