Re: Catching unique_violation exception on specific column/index

From: Thomas Kellerer <spam_eater(at)gmx(dot)net>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Catching unique_violation exception on specific column/index
Date: 2018-06-11 10:30:13
Message-ID: 0fa3bd50-3ce2-2038-29da-48fa0a1f6b19@gmx.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Alexey Dokuchaev schrieb am 11.06.2018 um 12:10:
> I have a table with several UNIQUE and CHECK constraints. One of these
> UNIQUE constraints actually *can* be violated -- not on the table level,
> of course, but on the application level -- meaning, if the entry with
> particular foo_key is already in there, do not throw an exception, just
> silently do nothing.
>
> The usual approach ("EXCEPTION WHEN unique_violation THEN ... END") does
> not really cut it because I want to catch unique_violation only when it
> happens on "foo_key", and still rightfully complain on others. However,
> there is no "EXCEPTION WHEN unique_violation ON (foo_key)" or something.
> Is there a way to do this without using triggers and in a less ugly way
> than the code below?
>
> IF SQLERRM = 'duplicate key value violates unique constraint' ||
> ' "foo_key"' THEN
> RAISE NOTICE '%: %', SQLSTATE, SQLERRM;
> ELSE
> RAISE EXCEPTION '%: %', SQLSTATE, SQLERRM;
> END IF;
>
> ./danfe

What's wrong with:

INSERT ...
ON CONFLICT (foo_key) DO NOTHING

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alexey Dokuchaev 2018-06-11 10:41:38 Re: Catching unique_violation exception on specific column/index
Previous Message Alexey Dokuchaev 2018-06-11 10:10:33 Catching unique_violation exception on specific column/index