Re: Sequences question & problem

Поиск
Список
Период
Сортировка
От Michael Fuhr
Тема Re: Sequences question & problem
Дата
Msg-id 20050516141405.GA82765@winnie.fuhr.org
обсуждение исходный текст
Ответ на Sequences question & problem  ("Lada 'Ray' Lostak" <ray@unreal64.net>)
Список pgsql-general
On Mon, May 16, 2005 at 12:29:27PM +0200, Lada 'Ray' Lostak wrote:
>
>     I am having small trouble with sequences. I am inserting row into table,
> and I need to get value of  its 'id' column (sequencen type). As far I know
> it have to be done by
>
>     SELECT last_value FORM seq_name
>
>         (or next_val before insert).

The above queries are subject to race conditions.  For example, if
transaction A inserts a record, then transaction B inserts a record,
then transaction A queries the sequence, then transaction A will
get the sequence value that was given to transaction B, which
probably isn't what you want.  Use currval() or nextval() instead.

http://www.postgresql.org/docs/8.0/interactive/functions-sequence.html
http://www.postgresql.org/docs/faqs.FAQ.html#4.11.2
http://www.postgresql.org/docs/faqs.FAQ.html#4.11.3

> Normally, sequences are created by 'table' &  'column' & '_seq' eg.
> 'table_id_seq'.
>
> Now let's rename 'table' to 'table2'. Sequence name wan't renamed. And it's
> my problem... I can't simple assume 'sequence id' by table/column...

If you're using PostgreSQL 8.0 or later then you can get the sequence
name with the pg_get_serial_sequence() function:

test=> CREATE TABLE foo (id serial);
NOTICE:  CREATE TABLE will create implicit sequence "foo_id_seq" for serial column "foo.id"
CREATE TABLE
test=> ALTER TABLE foo RENAME TO foo2;
ALTER TABLE
test=> ALTER TABLE foo2 RENAME id TO id2;
ALTER TABLE
test=> SELECT pg_get_serial_sequence('foo2', 'id2');
 pg_get_serial_sequence
------------------------
 public.foo_id_seq
(1 row)

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

В списке pgsql-general по дате отправления:

Предыдущее
От: Margus Roo
Дата:
Сообщение: is in postgres solution
Следующее
От: Bruno Wolff III
Дата:
Сообщение: Re: Named Notation for Functions' Parameteres