rules: evaluate inputs in advance - Mailing list pgsql-general

From Markus Schiltknecht
Subject rules: evaluate inputs in advance
Date
Msg-id 1147441878.18683.16.camel@fotomarburg
Whole thread Raw
Responses Re: rules: evaluate inputs in advance
List pgsql-general
Hi,

I was trying to create an updateable view. Suddenly I got foreign key
violations when using nextval('myseq').

As I understand, the rewriter does something similar to a simple text
replacement (I guess copying the plan tree nodes?) so that nextval gets
evaluated again for every rule that applies.

Is this desirable? Are there applications which need every rule to
reevaluate the input expressions? Or could that behaviour be changed so
that the input values for the rules get evaluated only once?

A simple example:

test=# CREATE TABLE test (id SERIAL PRIMARY KEY);
test=# CREATE VIEW view AS SELECT id FROM test;
test=# CREATE RULE rule1 AS ON INSERT TO view DO INSTEAD \
         INSERT INTO test (id) VALUES (NEW.id);
test=# CREATE RULE rule2 AS ON INSERT TO view DO ALSO \
         DELETE FROM test WHERE id = NEW.id;
test=# INSERT INTO view (id) VALUES (1);
test=# SELECT id FROM test;
 id
----
(0 rows)    -- that's what I was expecting...

test=# INSERT INTO view (id) VALUES (nextval('test_id_seq'));
test=# SELECT id FROM test;
 id
----
  1
(1 row)    -- this happens because rule2 evaluated nextval(..) again

test=# SELECT currval('test_id_seq');
 currval
---------
       2
(1 row)    -- confirming my observation.


Regards

Markus



pgsql-general by date:

Previous
From: Martijn van Oosterhout
Date:
Subject: Re: trigger TOASTing quicker?
Next
From: Martijn van Oosterhout
Date:
Subject: Re: rules: evaluate inputs in advance