diff --git a/examples/url_shortener/main.go b/examples/url_shortener/main.go index 8380ef3f..c6576a3a 100644 --- a/examples/url_shortener/main.go +++ b/examples/url_shortener/main.go @@ -28,19 +28,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 }