Thread: AW: [HACKERS] Sequence objects have no global currval operator?

AW: [HACKERS] Sequence objects have no global currval operator?

From
Andreas Zeugswetter
Date:
>Bruce Momjian <maillist@candle.pha.pa.us> writes:
>> How about SELECT * FROM sequence_table_name?
>
>Ah, of course.  The man page for CREATE SEQUENCE only mentions getting
>the sequence parameters that way, but you can get the last_value as
>well, which is exactly what I need.

What do you think of making currval return exactly this, only in the
case where nextval was not yet called by this client ?

I don't think anybody does rely on currval returning null iff nextval was not yet called
in his current session.

Andreas



Re: AW: [HACKERS] Sequence objects have no global currval operator?

From
Tom Lane
Date:
Andreas Zeugswetter <andreas.zeugswetter@telecom.at> writes:
> What do you think of making currval return exactly this, only in the
> case where nextval was not yet called by this client ?

I don't think that would be helpful.  If what you want is last_value
then the *only* safe way to get it is to use SELECT last_value.
Using currval in the way you suggest would be asking for trouble ---
your code will work until you add a nextval somewhere in the same
client, and then it will fail.  Subtly.

As defined, currval is only useful for specialized uses, such as
assigning the same newly-allocated sequence number to multiple
fields or table rows.  For example you could do
    INSERT INTO table1 VALUES(nextval('seq'), ....);
    INSERT INTO table2 VALUES(currval('seq'), ....);
    INSERT INTO table3 VALUES(currval('seq'), ....);
This is perfectly correct and safe: all three tables will get the same
uniquely-allocated sequence number regardless of what any other clients
may be doing.  You could also read back the assigned value with
    SELECT nextval('seq');
and then insert the value literally into subsequent commands, but
that way requires an extra round trip to the server.

currval is not useful for inquiring about what other clients are doing,
and I think we are best off to leave it that way to avoid confusion.
I was only complaining because I didn't understand about last_value
at the start of this thread.

            regards, tom lane