Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id CA96E1336971 for ; Wed, 24 Nov 2010 22:25:18 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 34311-05 for ; Thu, 25 Nov 2010 02:25:12 +0000 (UTC) Received: from news.hub.org (news.hub.org [200.46.204.72]) by mail.postgresql.org (Postfix) with ESMTP id 917C71337B4E for ; Wed, 24 Nov 2010 22:25:11 -0400 (AST) Received: from news.hub.org (news.hub.org [200.46.204.72]) by news.hub.org (8.14.4/8.14.4) with ESMTP id oAP2PBvj086146 for ; Wed, 24 Nov 2010 22:25:11 -0400 (AST) (envelope-from news@news.hub.org) Received: (from news@localhost) by news.hub.org (8.14.4/8.14.4/Submit) id oAP2C0kC061303 for pgsql-sql@postgresql.org; Wed, 24 Nov 2010 22:12:00 -0400 (AST) (envelope-from news) X-Newsgroups: pgsql.sql From: KM Subject: Re: atomic multi-threaded upsert References: <4CED72BB.3070905@gmail.com> User-Agent: slrn/pre1.0.0-18 (Linux) Message-ID: <4cedc5f0$0$22107$742ec2ed@news.sonic.net> Date: 25 Nov 2010 02:12:00 GMT Lines: 34 Organization: Sonic.Net X-Complaints-To: abuse@sonic.net To: pgsql-sql@postgresql.org X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.79 tagged_above=-5 required=5 tests=BAYES_50=0.8, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201011/58 X-Sequence-Number: 34796 On 2010-11-24, "Mikhail V. Puzanov" wrote: > Next, I execute the following two queries for that table: > > -- increment and get the counter if exists > UPDATE sequences SET counter = counter + 1 > WHERE section = 'testSection' AND name = 'testKey' > RETURNING counter; > > -- insert new counter if not exists > INSERT INTO sequences ( section, name, counter ) > SELECT 'testSection', 'testKey', 0 > WHERE NOT EXISTS ( > SELECT * FROM sequences > WHERE section = 'testSection' AND name = 'testKey' > ); > ERROR: duplicate key value violates unique constraint "idx_sequences_sn" > > 1) That looks weird actually, should the INSERT ... NOT EXISTS (...) be > executed > in atomic fashion? Also, AFAIK, UNIQUE INDEX locks rows before > insert (or not?). > Can it be related to JDBC? > Or it's the result of MVCC conflict resolution? Perhaps - Thread A UPDATEs, affecting no row. Thread B UPDATEs, affecting no row. Thread A INSERTs one row. Autocommit is on, so it commits the INSERT. Thread B attempts INSERT and fails on the duplicate. -- KM