Skip to content

Commit a1da1fe

Browse files
committed
feat: Implement database.IsUniqueViolation
1 parent 3f8e780 commit a1da1fe

File tree

2 files changed

+32
-6
lines changed

2 files changed

+32
-6
lines changed

coderd/database/errors.go

+30
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

+2-6
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"
@@ -520,10 +519,8 @@ func (api *API) patchWorkspace(rw http.ResponseWriter, r *http.Request) {
520519
})
521520
return
522521
}
523-
// Check if we triggered the one-unique-name-per-owner
524-
// constraint.
525-
var pqErr *pq.Error
526-
if errors.As(err, &pqErr) && pqErr.Code.Name() == "unique_violation" {
522+
// Check if the name was already in use.
523+
if database.IsUniqueViolation(err, database.UniqueConstraintWorkspacesOwnerIDLowerIdx) {
527524
httpapi.Write(rw, http.StatusConflict, codersdk.Response{
528525
Message: fmt.Sprintf("Workspace %q already exists.", req.Name),
529526
Validations: []codersdk.ValidationError{{
@@ -533,7 +530,6 @@ func (api *API) patchWorkspace(rw http.ResponseWriter, r *http.Request) {
533530
})
534531
return
535532
}
536-
537533
httpapi.Write(rw, http.StatusInternalServerError, codersdk.Response{
538534
Message: "Internal error updating workspace.",
539535
Detail: err.Error(),

0 commit comments

Comments
 (0)