Re: Getting the OID of inserted row in a rule

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Bradley Kieser <brad(at)kieser(dot)net>
Cc: pgsql-admin(at)postgresql(dot)org
Subject: Re: Getting the OID of inserted row in a rule
Date: 2004-09-22 15:26:43
Message-ID: 20040922152643.GA92429@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin

On Wed, Sep 22, 2004 at 02:21:42PM +0100, Bradley Kieser wrote:
> I have a rule on a view that needs to insert into two tables. The one
> table has a serial ID as its unique key. The second table links to the
> first one in one of its columns.
>
> I would prefer to keep this as a rule-based solution and not have to
> write a function as I hope to relicate the solution across many views.
>
> I need to either be able to select nextval() the ID for the first table
> and somehow store this in the rule (but I don't see that rules support
> variables) or I need to somehow obtain the OID from the first insert in
> order to select back the ID that was assigned during the insert and pass
> it to the second insert (trivial to do as the second insert is then
> simply a select-based insert, provided that I know the OID of that first
> row!).

The second insert should be able to use currval() to get the current
value of the sequence used in the first insert. Here's an example:

CREATE RULE v_ins AS ON INSERT TO v DO INSTEAD (
INSERT INTO a (xxx) VALUES (NEW.xxx);
INSERT INTO b (col1, col2, col3) VALUES (NEW.col1, NEW.col2, currval('a_id_seq'))
);

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message Bradley Kieser 2004-09-22 15:30:06 Re: Getting the OID of inserted row in a rule
Previous Message Tom Lane 2004-09-22 15:08:22 Re: Making a Persistent Postgres Connection