Re: tables referenced from insert...returning

From: "Michael Shulman" <shulman(at)mathcamp(dot)org>
To: "Tom Lane" <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: tables referenced from insert...returning
Date: 2008-06-24 02:42:40
Message-ID: c3f821000806231942h279d5d50j7053c60455e1a81@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Mon, Jun 23, 2008 at 8:46 PM, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2008-06-24 02:54:56 Re: tables referenced from insert...returning
Previous Message Tom Lane 2008-06-24 01:46:58 Re: tables referenced from insert...returning