Skip to content

Commit 85eb0cf

Browse files
committed
feat: Implement database.IsUniqueViolation
1 parent decf9ca commit 85eb0cf

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

coderd/database/errors.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package database
2+
3+
import (
4+
"errors"
5+
6+
"github.com/lib/pq"
7+
)
8+
9+
// UniqueConstraint represents a named unique constraint on a table.
10+
type UniqueConstraint string
11+
12+
// UniqueConstrain enums.
13+
// TODO(mafredri): Generate these from the database schema.
14+
const (
15+
UniqueConstraintAny UniqueConstraint = ""
16+
UniqueConstraintWorkspacesOwnerIDLowerIdx UniqueConstraint = "workspaces_owner_id_lower_idx"
17+
)
18+
19+
func IsUniqueViolation(err error, uniqueConstraint UniqueConstraint) bool {
20+
var pqErr *pq.Error
21+
if errors.As(err, &pqErr) {
22+
if pqErr.Code.Name() == "unique_violation" {
23+
if pqErr.Constraint == string(uniqueConstraint) || uniqueConstraint == UniqueConstraintAny {
24+
return true
25+
}
26+
}
27+
}
28+
29+
return false
30+
}

coderd/workspaces.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import (
1414

1515
"github.com/go-chi/chi/v5"
1616
"github.com/google/uuid"
17-
"github.com/lib/pq"
1817
"github.com/moby/moby/pkg/namesgenerator"
1918
"golang.org/x/sync/errgroup"
2019
"golang.org/x/xerrors"
@@ -513,10 +512,8 @@ func (api *API) patchWorkspace(rw http.ResponseWriter, r *http.Request) {
513512
})
514513
return
515514
}
516-
// Check if we triggered the one-unique-name-per-owner
517-
// constraint.
518-
var pqErr *pq.Error
519-
if errors.As(err, &pqErr) && pqErr.Code.Name() == "unique_violation" {
515+
// Check if the name was already in use.
516+
if database.IsUniqueViolation(err, database.UniqueConstraintWorkspacesOwnerIDLowerIdx) {
520517
httpapi.Write(rw, http.StatusConflict, codersdk.Response{
521518
Message: fmt.Sprintf("Workspace %q already exists.", req.Name),
522519
Validations: []codersdk.ValidationError{{
@@ -526,7 +523,6 @@ func (api *API) patchWorkspace(rw http.ResponseWriter, r *http.Request) {
526523
})
527524
return
528525
}
529-
530526
httpapi.Write(rw, http.StatusInternalServerError, codersdk.Response{
531527
Message: "Internal error updating workspace.",
532528
Detail: err.Error(),

0 commit comments

Comments
 (0)