From: | Sebastien FLAESCH <sf(at)4js(dot)com> |
---|---|
To: | "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com> |
Cc: | pgsql-sql <pgsql-sql(at)lists(dot)postgresql(dot)org> |
Subject: | Re: Get last generated serial sequence and set it up when explicit value is used |
Date: | 2020-11-20 10:23:24 |
Message-ID: | 4279b691-5699-4e83-2337-e1a4f30553bd@4js.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
On 11/20/20 9:49 AM, David G. Johnston wrote:
> On Friday, November 20, 2020, Sebastien FLAESCH <sf(at)4js(dot)com <mailto:sf(at)4js(dot)com>> wrote:
>
> Is there any way to avoid the error produced by currval()?
>
>
> No
>
> Ideally, currval() should return zero when no serial was produced yet.
>
>
> I’d accept null, zero is a valid value.
>
>
> Is it possible to write that in a simple SQL expression so it can be used in
> the RETURNING clause of my INSERTs ?
>
>
> Not that I can think of. Maybe as the docs suggest, just do an unconditional setval()? You might be able to combine that with a non-default
> isolation level (guessing here) to get close-enough behavior. You are fighting the existing design of the feature, looking for an in-between position
> of fast-and-concurrent (existing) and fully serialized (where this would be mostly trivial to implement). I don’t know of such a method.
>
> David J.
>
Thanks David for your comments.
I will give a chance to:
insert into table1 (name) values ('aaaa')
returning pkey, (select last_value from table1_pkey_seq);
Followed by a setval('seq',pkey,true), if pkey > last_value ...
In fact I wonder how PostgreSQL actually executes such statement.
To me, it should be an atomic operation so I guess the
(SELECT last_value FROM seq-name)
Should either return the new serial produced by this current INSERT,
or a new serial produced previously by the INSERT in another session,
when the current INSERT do not produce a new serial value.
But it should not return a new serial value that was produced
by another session between the actual local INSERT and the SELECT
last_val sub-query in the RETURNING clause...
Anyway, doing the setval(...pkey...) when pkey value is greater than
the last_value, should also be ok if a new last_value was produced
by another session in-between...
Does that make sense?
Seb
From | Date | Subject | |
---|---|---|---|
Next Message | Sebastien FLAESCH | 2020-11-20 17:00:10 | perform setval() fails? |
Previous Message | David G. Johnston | 2020-11-20 08:49:44 | Re: Get last generated serial sequence and set it up when explicit value is used |