Skip to content

Commit ae67cb2

Browse files
committed
chore: Refactor to allow matching on multiple constraints
1 parent 98ccff0 commit ae67cb2

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

coderd/database/errors.go

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,25 @@ type UniqueConstraint string
1212
// UniqueConstraint enums.
1313
// TODO(mafredri): Generate these from the database schema.
1414
const (
15-
UniqueConstraintAny UniqueConstraint = ""
16-
UniqueConstraintWorkspacesOwnerIDLowerIdx UniqueConstraint = "workspaces_owner_id_lower_idx"
15+
UniqueWorkspacesOwnerIDLowerIdx UniqueConstraint = "workspaces_owner_id_lower_idx"
1716
)
1817

19-
func IsUniqueViolation(err error, uniqueConstraint UniqueConstraint) bool {
18+
// IsUniqueViolation checks if the error is due to a unique violation.
19+
// If specific cunique constraints are given as arguments, the error
20+
// must be caused by one of them. If no constraints are given, this
21+
// function returns true on any unique violation.
22+
func IsUniqueViolation(err error, uniqueConstraints ...UniqueConstraint) bool {
2023
var pqErr *pq.Error
2124
if errors.As(err, &pqErr) {
2225
if pqErr.Code.Name() == "unique_violation" {
23-
if pqErr.Constraint == string(uniqueConstraint) || uniqueConstraint == UniqueConstraintAny {
26+
if len(uniqueConstraints) == 0 {
2427
return true
2528
}
29+
for _, uc := range uniqueConstraints {
30+
if pqErr.Constraint == string(uc) {
31+
return true
32+
}
33+
}
2634
}
2735
}
2836

coderd/workspaces.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,7 @@ func (api *API) patchWorkspace(rw http.ResponseWriter, r *http.Request) {
513513
return
514514
}
515515
// Check if the name was already in use.
516-
if database.IsUniqueViolation(err, database.UniqueConstraintWorkspacesOwnerIDLowerIdx) {
516+
if database.IsUniqueViolation(err, database.UniqueWorkspacesOwnerIDLowerIdx) {
517517
httpapi.Write(rw, http.StatusConflict, codersdk.Response{
518518
Message: fmt.Sprintf("Workspace %q already exists.", req.Name),
519519
Validations: []codersdk.ValidationError{{

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy