dialect/sql/sqlgraph: report check constraint violation with IsCheckConstraintError (#4404)

* feat(dialect): Support check constraint violation

* chore: Add unit tests for IsCheckConstraintError
This commit is contained in:
Henry Le
2025-06-20 15:11:59 +07:00
committed by GitHub
parent 86238d83fc
commit ace82484b8
2 changed files with 57 additions and 1 deletions

View File

@@ -12,7 +12,10 @@ import (
// IsConstraintError returns true if the error resulted from a database constraint violation.
func IsConstraintError(err error) bool {
var e *ConstraintError
return errors.As(err, &e) || IsUniqueConstraintError(err) || IsForeignKeyConstraintError(err)
return errors.As(err, &e) ||
IsUniqueConstraintError(err) ||
IsForeignKeyConstraintError(err) ||
IsCheckConstraintError(err)
}
// IsUniqueConstraintError reports if the error resulted from a DB uniqueness constraint violation.
@@ -51,3 +54,21 @@ func IsForeignKeyConstraintError(err error) bool {
}
return false
}
// IsCheckConstraintError reports if the error resulted from a database check constraint violation.
// e.g. a value does not satisfy a check condition.
func IsCheckConstraintError(err error) bool {
if err == nil {
return false
}
for _, s := range []string{
"Error 3819", // MySQL
"violates check constraint", // Postgres
"CHECK constraint failed", // SQLite
} {
if strings.Contains(err.Error(), s) {
return true
}
}
return false
}