From a3dc0b646b9a04f3ab4a6375405fa5d90fcdffcc Mon Sep 17 00:00:00 2001 From: Bastien Riviere Date: Mon, 29 Jan 2024 21:37:27 +0100 Subject: [PATCH] fix: return URL if it already exists --- internal/api/handler.go | 6 ------ internal/db/query.sql.go | 2 +- sql/query.sql | 2 +- 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/internal/api/handler.go b/internal/api/handler.go index 93e693a..0911afc 100644 --- a/internal/api/handler.go +++ b/internal/api/handler.go @@ -50,12 +50,6 @@ func (h *handler) CreateShortURL(ctx context.Context, req *oas.CreateShortURLReq LongUrl: req.URL, }) if err != nil { - // No row == conflict since we do a "ON CONFLICT DO NOTHING" - if errors.Is(err, pgx.ErrNoRows) { - return &oas.CreateShortURLBadRequest{ - Message: oas.NewOptString("URL already exist."), - }, nil - } return nil, fmt.Errorf("failed to insert url: %w", err) } diff --git a/internal/db/query.sql.go b/internal/db/query.sql.go index 3f7feb8..0ba675c 100644 --- a/internal/db/query.sql.go +++ b/internal/db/query.sql.go @@ -24,7 +24,7 @@ func (q *Queries) GetURLByHash(ctx context.Context, hash string) (Url, error) { const insertURL = `-- name: InsertURL :one INSERT INTO urls (hash, long_url) VALUES ($1, $2) -ON CONFLICT (hash) DO NOTHING +ON CONFLICT (hash) DO UPDATE SET hash = EXCLUDED.hash -- force row to be returned RETURNING id, hash, long_url ` diff --git a/sql/query.sql b/sql/query.sql index e7d8aca..57f19ce 100644 --- a/sql/query.sql +++ b/sql/query.sql @@ -5,5 +5,5 @@ WHERE hash = $1; -- name: InsertURL :one INSERT INTO urls (hash, long_url) VALUES ($1, $2) -ON CONFLICT (hash) DO NOTHING +ON CONFLICT (hash) DO UPDATE SET hash = EXCLUDED.hash -- force row to be returned RETURNING *;