Add function to check if db error is a check constraint violation (#142)

pull/145/head
Michael Gaffney 6 years ago committed by GitHub
parent 6c2a17c845
commit c110c86ee5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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)
})
}
}

Loading…
Cancel
Save