Re: RULES and QUALIFICATION for INSERT

From: "Albe Laurenz" <laurenz(dot)albe(at)wien(dot)gv(dot)at>
To: "srdjan *EXTERN*" <srdjan(dot)matic(at)anche(dot)no>
Cc: <pgsql-general(at)postgresql(dot)org>
Subject: Re: RULES and QUALIFICATION for INSERT
Date: 2008-03-26 13:11:36
Message-ID: D960CB61B694CF459DCFB4B0128514C201E677E5@exadv11.host.magwien.gv.at
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

srdjan wrote:
>>> -- I've got 2 tables and one view
>>> CREATE TABLE a (name varchar(20) primary key, num integer);
>>> CREATE TABLE b (town varchar(15), name varchar(20) references a(name));
>>>
>>> insert into a values ('tom',5);
>>> insert into a values ('paul',99);
>>> insert into a values ('jack',1234);
>>> insert into b values ('london','tom');
>>> insert into b values ('rome','paul');
>>>
>>> CREATE VIEW vvv AS SELECT * FROM a NATURAL JOIN b;
>>>
>>> -- I've crated a rule in this way
>>>
>>> CREATE RULE rrr AS ON INSERT TO vvv
>>> WHERE NEW.name = 'tom'
>>> DO INSTEAD
>>> INSERT INTO a VALUES (NEW.name, NEW.num);
>>>
>>>
>>> Trying a simple INSERT INTO vvv, I receive this message:
>>> ERROR: cannot insert into a view
>>> HINT: You need an unconditional ON INSERT DO INSTEAD rule.
>>
>> What is the desired response to
>>
>> INSERT INTO vvv (name, town, num) VALUES ('Karl', 'Leipzig', 18);
>>
>> Should this generate an error message, do nothing, or insert something?
>
> It's not important, but maybe an error message would be preferred.

You'll have to create a "dummy" unconditional DO INSTEAD rule,
as explained in
http://www.postgresql.org/docs/current/static/sql-createrule.html

The 'do nothing' case is simpler:

CREATE RULE vvv_dummy AS
ON INSERT TO vvv
DO INSTEAD NOTHING;
CREATE RULE vvv_ins AS
ON INSERT TO vvv WHERE NEW.name = 'tom'
DO INSTEAD INSERT INTO a VALUES (NEW.name, NEW.num);

If you want error messages if NEW.name is not 'tom', add a third rule:

CREATE RULE vvv_err AS
ON INSERT TO vvv WHERE NEW.name != 'tom' OR NEW.name IS NULL
DO INSTEAD SELECT 0/0;

Use something else than "SELECT 0/0" if you want a more intelligent error message.

Yours,
Laurenz Albe

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Alvaro Herrera 2008-03-26 13:21:17 Re: Reindex does not finish 8.2.6
Previous Message josep porres 2008-03-26 12:59:15 Re: pgplsql, how to save row variable to a table row