views:

286

answers:

1

Do the following scheme for my database:

create sequence data_sequence;

create table data_table
{
    id integer primary key;
    field varchar(100);
};

create view data_view as
select id, field from data_table;

create function data_insert(_new data_view) returns data_view as
$$declare
    _id integer;
    _result data_view%rowtype;
begin
    _id := nextval('data_sequence');
    insert into data_table(id, field) values(_id, _new.field);
    select * into _result from data_view where id = _id;
return _result;
end;
$$
language plpgsql;

create rule insert as on insert to data_view do instead
select data_insert(new);

Then type in psql:

insert into data_view(field) values('abc');

Would like to see something like:

 id |  field
----+---------
  1 |  abc

Instead see:

 data_insert
-------------
 (1, "abc")

Is it possible to fix this somehow?

Thanks for any ideas.

Ultimate idea is to use this in other functions, so that I could obtain id of just inserted record without selecting for it from scratch. Something like:

insert into data_view(field) values('abc') returning id into my_variable

would be nice but doesn't work with error:

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

I don't really understand that HINT. I use PostgreSQL 8.4.

+2  A: 

What you want to do is already built into postgres. It allows you to include a RETURNING clause on INSERT statements.

CREATE TABLE data_table (
    id SERIAL,
    field VARCHAR(100),
    CONSTRAINT data_table_pkey PRIMARY KEY (id)
);

INSERT INTO data_table (field) VALUES ('testing') RETURNING id, field;

If you feel you must use a view, check this thread on the postgres mailing list before going any further.

h0tw1r3
Thanks. My simplified example above is different from a plain insertion. My logic require some processing between insert invocation (actually, to view, not a plain table), and actual physical insertion, such processing also includes the decision - whether to insert or not.So, the result I would like to see is 1 or none records about inserted data, including assigned record id.And I tried RETURNING, and it gave me a hint as wrote above. So, until I missed something in your answer - I am still looking a solution. Will review your link - thanks.