Add function to check if db error is a check constraint violation (#142)
This commit is contained in:
1 parent
6c2a17c845
commit
c110c86ee5
2 files changed
+54
No files matched your search
@@ -58,3 +58,20 @@ func IsUniqueError(err error) bool {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// IsCheckConstraintError returns a boolean indicating whether the error is
|
||||
// known to report a check constraint violation.
|
||||
func IsCheckConstraintError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var pqError *pq.Error
|
||||
if errors.As(err, &pqError) {
|
||||
if pqError.Code.Name() == "check_violation" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -43,3 +43,40 @@ func TestError_IsUnique(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestError_IsCheckConstraint(t *testing.T) {
|
||||
var tests = []struct {
|
||||
name string
|
||||
in error
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "nil-error",
|
||||
in: nil,
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "postgres-not-check-constraint",
|
||||
in: &pq.Error{
|
||||
Code: pq.ErrorCode("23505"),
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "postgres-is-check-constraint",
|
||||
in: &pq.Error{
|
||||
Code: pq.ErrorCode("23514"),
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
tt := tt
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
err := tt.in
|
||||
got := IsCheckConstraintError(err)
|
||||
assert.Equal(tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user