Re: Using new.id in the WHERE condition of one UPDATE inside ON INSERT rule

From: Aron <auryn(at)wanadoo(dot)es>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Using new.id in the WHERE condition of one UPDATE inside ON INSERT rule
Date: 2010-03-01 16:30:05
Message-ID: 201003011730.05471.auryn@wanadoo.es
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Jueves 25 Febrero 2010 16:28:56 usted escribió:
> Aron <auryn(at)wanadoo(dot)es> writes:
> > I would like to avoid using "SELECT MAX(id) FROM my_table" (it doesn't
> > seem a good method), but if I use "new.id", I get new id values, not the
> > "id" inserted with the rule, and the condition is always false.
>
> "new.id" is a macro, which in this example will be expanded into a
> nextval() function call, which is why it doesn't work --- the nextval()
> in the WHERE condition will produce a different value from the one in
> the original INSERT. You would be far better off using a trigger here
> instead of a rule.
>
> regards, tom lane
>
Thank you very much.
I've used this trigger succesfully:

CREATE OR REPLACE FUNCTION copy_cost RETURNS "trigger" AS '
DECLARE
change_other BOOL;
BEGIN
IF (tg_op = ''UPDATE'') THEN
IF (new.id_other <> old.id_other) THEN
change_other = true;
ELSE
change_other = false;
END IF;
END IF;

IF (tg_op = ''INSERT'' AND new.my_cost IS NULL)
OR change_other) THEN
new.my_cost = (
SELECT my_other_cost
FROM my_other_table
WHERE id = new.id_other
);
END IF;
RETURN NEW;
END;
' LANGUAGE 'plpgsql';

CREATE TRIGGER copy_cost__trigger
BEFORE INSERT OR UPDATE ON my_table
FOR EACH ROW
EXECUTE PROCEDURE copy_cost();

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Gianvito Pio 2010-03-01 21:50:23 Create functions using a function
Previous Message Richard Huxton 2010-03-01 13:38:54 Re: kind of RULE on SELECT depending on existence of a WHERE condition