pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: hubert depesz lubaczewski <depesz@depesz.com>
To: personal@rysmax.com
Cc: pgsql-bugs@postgresql.org
Subject: Re: BUG #14909: nextval() bug
Date: Wed, 15 Nov 2017 12:26:08 +0100
Message-ID: <20171115112608.GA32070@depesz.com> (raw)
In-Reply-To: <20171115105136.1473.62937@wrigleys.postgresql.org>
References: <20171115105136.1473.62937@wrigleys.postgresql.org>

On Wed, Nov 15, 2017 at 10:51:36AM +0000, personal@rysmax.com wrote:
> CREATE TABLE "user" (
>   id serial primary key not null,
>   email varchar(64) not null
> );
> INSERT INTO "user" (id, email) VALUES ('1', 'admin@example.com');
> INSERT INTO "user" (id, email) VALUES ('2', 'user@example.com');
> 
> All done without errors.
> 
> 
> 
> When i try to run the query bellow:
> 
> INSERT INTO "user" (email) VALUES ('test@example.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





view thread (2+ messages)

Message-ID: <20171115112608.GA32070@depesz.com>
Permalink:  ../20171115112608.GA32070@depesz.com/
Also on:    postgresql.org/message-id/20171115112608.GA32070@depesz.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-bugs@postgresql.org
  Cc: depesz@depesz.com, personal@rysmax.com
  Subject: Re: BUG #14909: nextval() bug
  In-Reply-To: <20171115112608.GA32070@depesz.com>
  References: <20171115105136.1473.62937@wrigleys.postgresql.org> <20171115112608.GA32070@depesz.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox