Re: Problem with rules and conditions

From: Jan Wieck <JanWieck(at)Yahoo(dot)com>
To: Tobias Hermansson <tobhe_nospm(at)hotmail(dot)com>
Cc: pgsql-hackers(at)postgresql(dot)org
Subject: Re: Problem with rules and conditions
Date: 2001-07-15 12:08:01
Message-ID: 200107151208.f6FC81m15526@jupiter.us.greatbridge.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Tobias Hermansson wrote:
> Hello,
>
> I have a problem with rules in postgres, it may be a bug, or maybe I'm doing
> something wrong. I'm running version 7.1.2 on a freebsd 4.3 box.
>
> Here is my table:
>
> CREATE TABLE customer (
> cono integer not null,
> Name varchar,
> ssn varchar(10),
> PRIMARY KEY (cono)
> );
>
> Here is the rule:
>
> CREATE RULE constraint_customer_ssn_insert
> AS ON INSERT
> TO customer
> WHERE NOT new.ssn IS NULL
> DO INSTEAD
> INSERT INTO customer (cono,name) VALUES (new.cono,new.name);
>
> When I execute "insert into customer values (1,'bogus',null);" the result is
> "ERROR: query rewritten 10 times, may contain cycles" is appeared.
>
> Is this suppose to trigger my rule? The condition is not fullfilled, the ssn
> value is null in the insert query. To me it seems like the where clause is
> skipped somehow...
>
> Can anybody help me find out why?

So you allways want to set customer.ssn to NULL on insert,
right?

You cannot have a rule action that does the same operation
(INSERT) on the same table (customer). This triggers the same
rule to get fired again, and that's an endless *rewrite*
loop. Note that the rewriting doesn't look at the values, it
allways splits the parsetree in your above rule and has to
apply the same rule on the new query again.

Use a trigger instead:

CREATE FUNCTION cust_ssn_ins () RETURNS opaque AS '
BEGIN
NEW.ssn := NULL;
RETURN NEW;
END;'
LANGUAGE 'plpgsql';

CREATE TRIGGER cust_ssn_ins BEFORE INSERT TO customer
FOR EACH ROW EXECUTE PROCEDURE cust_ssn_ins();

Jan

--

#======================================================================#
# It's easier to get forgiveness for being wrong than for being right. #
# Let's break this rule - forgive me. #
#================================================== JanWieck(at)Yahoo(dot)com #

_________________________________________________________
Do You Yahoo!?
Get your free @yahoo.com address at http://mail.yahoo.com

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Bruce Momjian 2001-07-15 14:35:18 Re: [PATCH] To remove EXTEND INDEX
Previous Message Tatsuo Ishii 2001-07-15 11:21:15 multibyte enhancement