Re: implicit lock in RULE ?

From: Fritz Lehmann-Grube <fritzlg(at)gmx(dot)de>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Fritz Lehmann-Grube <lehmannf(at)math(dot)TU-Berlin(dot)DE>, pgsql-novice(at)postgresql(dot)org
Subject: Re: implicit lock in RULE ?
Date: 2003-04-26 19:14:54
Message-ID: 3EAADAAE.54172745@gmx.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

Thanks Tom,
that solves my problem...

Tom Lane schrieb:
>
> Fritz Lehmann-Grube <lehmannf(at)math(dot)TU-Berlin(dot)DE> writes:
> > I tried
>
> > CREATE RULE new_vc_thread AS ON INSERT TO images
> > WHERE new.vc_thread = 0
> > DO
> > (
> > BEGIN;
> > LOCK vc_threads;
> > INSERT INTO vc_threads(name) VALUES(new.name);
> > UPDATE images SET vc_thread = currval('vc_threads_id_seq') WHERE vc_thread=0;
> > COMMIT;
> > );
>
> > but got a syntax error - OK.
>
> > But how can I work around it ?
>
> Drop the BEGIN, the LOCK, and the COMMIT. Read the discussion of
> sequence functions at
> http://www.ca.postgresql.org/users-lounge/docs/7.3/postgres/functions-sequence.html
> to see why you don't need any LOCK to protect the currval() value.

I had hoped for something exactly like this. Though I had searched for
it in the RULE system.
So SEQUENCES are threadsafe inside sessions !

>
> A more serious problem with the above is that it will fail to do what
> you want for multiple-row insertion commands --- the INSERT will
> correctly insert multiple rows into vc_threads, but when control comes
> to the UPDATE, all of the freshly added images rows will be updated to
> link to the last of those vc_threads rows, because you only have one
> currval() value to work with.

I must admid, I hadn't thought about that. But it's no problem, because
I can guarantee SINGLE ROW inserts at a time at least per session.

>
> You'd be better off doing this as a trigger, not a rule. The syntax
> hurdle is a bit higher (you need to learn a little bit of pl/pgsql)

I know, but my "contract" tells me to produce code "as standard SQL as
possible" (sorry. They think we might want to be able to port to oracle
or something - though we can't, we're open source. See www.mumie.net or
www.math.tu-berlin.de/multiverse )- TRIGGERS are, as much as RULES, but
pl/pgsql is not. (Am I right ? I'd be glad to use more pl/pgsql)

> but the mental model of what's going on is far simpler. Triggers
> work on one row at a time --- rules don't.
>
> regards, tom lane

thank you, Fritz Lehmann-Grube

In response to

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Josh Berkus 2003-04-26 19:17:39 Re: subselects?
Previous Message nolan 2003-04-26 18:58:59 Re: Date format errors