From 6cb47b91b34871133947b1b97075067a1ddc1a13 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Fri, 14 Jul 2017 08:57:25 -0500 Subject: [PATCH] Use insert on conflict for url shortener example fixes #290 --- examples/url_shortener/main.go | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/examples/url_shortener/main.go b/examples/url_shortener/main.go index f6a22c37..695a5be6 100644 --- a/examples/url_shortener/main.go +++ b/examples/url_shortener/main.go @@ -26,19 +26,9 @@ func afterConnect(conn *pgx.Conn) (err error) { return } - // There technically is a small race condition in doing an upsert with a CTE - // where one of two simultaneous requests to the shortened URL would fail - // with a unique index violation. As the point of this demo is pgx usage and - // not how to perfectly upsert in PostgreSQL it is deemed acceptable. _, err = conn.Prepare("putUrl", ` - with upsert as ( - update shortened_urls - set url=$2 - where id=$1 - returning * - ) - insert into shortened_urls(id, url) - select $1, $2 where not exists(select 1 from upsert) + insert into shortened_urls(id, url) values ($1, $2) + on conflict (id) do update set url=excluded.url `) return }