views:

172

answers:

2

I have a View that has several fields.

When i INSERT INTO a view I run a function based on INSERT parametrs. The function returns a value.

How can I retrieve The value from rule?

INSERT RETURNING Gives me:

ERROR:  cannot perform INSERT RETURNING on relation "full_subntes"
HINT:   You need an unconditional ON INSERT DO INSTEAD rule with a RETURNING clause.

Example:
CREATE TABLE test (
a VARCAHR primary key,
b VARCHAR,
);

CREATE VIEW test_v AS SELECT * FROM test;

CREATE OR REPLACE RULE Test_v_Insert AS ON INSERT TO Test_v
DO INSTEAD (
SELECT myFunction('param');
);

INSERT INTO test_v(a, b) VALUES ('a', 'b') RETURNING a, b;

Then I get an error described above.

A: 

In order to update a view in Postgres, you need to define a rule telling it to update the base table instead. It doesn't sound like you've created a rule yet. http://www.postgresql.org/docs/current/interactive/rules-update.html

Scott Bailey
I created a rule. But, I need to run a function result of with will be returned inside an insert rule.
Dmitry
A: 

Here is an example.

First, we create a test table:

CREATE TABLE test (a integer, b varchar, primary key (a));

Then, we create a view:

CREATE OR REPLACE VIEW test_view AS SELECT * FROM test;

Next, the update rule is created:

CREATE OR REPLACE RULE rl_test_view_update AS
    ON UPDATE TO test_view DO INSTEAD
    UPDATE test SET a = NEW.a, b = NEW.b
    WHERE test.a = old.a AND test.b = old.b;

And finally, here is the insert rule:

CREATE OR REPLACE RULE rl_test_view_insert AS
    ON INSERT TO test_view DO INSTEAD
    INSERT INTO test VALUES (NEW.a, NEW.b)
    RETURNING test.*;

Now you can insert some test data:

INSERT INTO test_view (a, b) VALUES (1,'John Doe') RETURNING a;

and check the tuples inserted:

SELECT * FROM test_view;
Paulo Centeno
I need to run a function value of with will be returned inside an insert rule.Simple insert returning woks fine.
Dmitry