-
Notifications
You must be signed in to change notification settings - Fork 247
/
errors.go
65 lines (56 loc) · 2.12 KB
/
errors.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package common
import (
"errors"
"regexp"
"strings"
"github.com/jackc/pgx/v5/pgconn"
dscommon "github.com/authzed/spicedb/internal/datastore/common"
core "github.com/authzed/spicedb/pkg/proto/core/v1"
)
const (
pgUniqueConstraintViolation = "23505"
pgSerializationFailure = "40001"
)
var (
createConflictDetailsRegex = regexp.MustCompile(`^Key (.+)=\(([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)\) already exists`)
createConflictDetailsRegexWithoutCaveat = regexp.MustCompile(`^Key (.+)=\(([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)\) already exists`)
)
// ConvertToWriteConstraintError converts the given Postgres error into a CreateRelationshipExistsError
// if applicable. If not applicable, returns nils.
func ConvertToWriteConstraintError(livingTupleConstraint string, err error) error {
var pgerr *pgconn.PgError
if errors.As(err, &pgerr) && pgerr.Code == pgUniqueConstraintViolation && pgerr.ConstraintName == livingTupleConstraint {
found := createConflictDetailsRegex.FindStringSubmatch(pgerr.Detail)
if found != nil {
return dscommon.NewCreateRelationshipExistsError(&core.RelationTuple{
ResourceAndRelation: &core.ObjectAndRelation{
Namespace: strings.TrimSpace(found[2]),
ObjectId: strings.TrimSpace(found[3]),
Relation: strings.TrimSpace(found[4]),
},
Subject: &core.ObjectAndRelation{
Namespace: strings.TrimSpace(found[5]),
ObjectId: strings.TrimSpace(found[6]),
Relation: strings.TrimSpace(found[7]),
},
})
}
found = createConflictDetailsRegexWithoutCaveat.FindStringSubmatch(pgerr.Detail)
if found != nil {
return dscommon.NewCreateRelationshipExistsError(&core.RelationTuple{
ResourceAndRelation: &core.ObjectAndRelation{
Namespace: strings.TrimSpace(found[2]),
ObjectId: strings.TrimSpace(found[3]),
Relation: strings.TrimSpace(found[4]),
},
Subject: &core.ObjectAndRelation{
Namespace: strings.TrimSpace(found[5]),
ObjectId: strings.TrimSpace(found[6]),
Relation: strings.TrimSpace(found[7]),
},
})
}
return dscommon.NewCreateRelationshipExistsError(nil)
}
return nil
}