Re: BUG #14909: nextval() bug

From: hubert depesz lubaczewski <depesz(at)depesz(dot)com>
To: personal(at)rysmax(dot)com
Cc: pgsql-bugs(at)postgresql(dot)org
Subject: Re: BUG #14909: nextval() bug
Date: 2017-11-15 11:26:08
Message-ID: 20171115112608.GA32070@depesz.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

On Wed, Nov 15, 2017 at 10:51:36AM +0000, personal(at)rysmax(dot)com wrote:
> CREATE TABLE "user" (
> id serial primary key not null,
> email varchar(64) not null
> );
> INSERT INTO "user" (id, email) VALUES ('1', 'admin(at)example(dot)com');
> INSERT INTO "user" (id, email) VALUES ('2', 'user(at)example(dot)com');
>
> All done without errors.
>
>
>
> When i try to run the query bellow:
>
> INSERT INTO "user" (email) VALUES ('test(at)example(dot)com');
>
> and got the next error in pgAdmin and from the PHP:
>
> ERROR: duplicate key value violates unique constraint "user_pkey"
> DETAIL: Key (id)=(1) already exists.
>
> but when i try to run this query 2 times the query executed without errors
> on 3rd time.
> I think this is a bug in nextval() function.

No, it's not.

when you insert providing value for id column, default (nextval) is not
called, so sequence is not updated.

So, when you finally try to insert without id, nextval is called and
returns first unused (from the point of view of sequence) value - 1.
Which already is in the table because you "forcibly" inserted it.

To avoid this problem you have to either:

1. run setval(...) after insertiing data with some forced ids
2. always use nextval/default for id column.

Best regards,

depesz

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message kevinsantiago-19 2017-11-15 23:08:39 BUG #14910: Imposible instalar postgres
Previous Message personal 2017-11-15 10:51:36 BUG #14909: nextval() bug