entc/gen: catch constraint failures in delete operations (#2664)

This commit is contained in:
Ariel Mashraki
2022-06-19 14:34:32 +03:00
committed by GitHub
parent b89b13bbdb
commit abefaa7f24
105 changed files with 545 additions and 111 deletions

View File

@@ -9,7 +9,7 @@ import (
"strings"
)
// IsConstraintError returns true if the error resulted from a DB constraint violation
// 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)
@@ -18,12 +18,11 @@ func IsConstraintError(err error) bool {
// IsUniqueConstraintError reports if the error resulted from a DB uniqueness constraint violation.
// e.g. duplicate value in unique index.
func IsUniqueConstraintError(err error) bool {
uniquenessErrors := []string{
for _, s := range []string{
"Error 1062", // MySQL
"violates unique constraint", // Postgres
"UNIQUE constraint failed", // SQLite
}
for _, s := range uniquenessErrors {
} {
if strings.Contains(err.Error(), s) {
return true
}
@@ -31,15 +30,15 @@ func IsUniqueConstraintError(err error) bool {
return false
}
// IsForeignKeyConstraintError reports if the error resulted from a DB FK constraint violation.
// IsForeignKeyConstraintError reports if the error resulted from a database foreign-key constraint violation.
// e.g. parent row does not exist.
func IsForeignKeyConstraintError(err error) bool {
fkErrors := []string{
"Error 1452", // MySQL
for _, s := range []string{
"Error 1451", // MySQL (Cannot delete or update a parent row).
"Error 1452", // MySQL (Cannot add or update a child row).
"violates foreign key constraint", // Postgres
"FOREIGN KEY constraint failed", // SQLite
}
for _, s := range fkErrors {
} {
if strings.Contains(err.Error(), s) {
return true
}

View File

@@ -2342,6 +2342,28 @@ func TestIsConstraintError(t *testing.T) {
expectedFK: true,
expectedUnique: false,
},
{
name: "MySQL FK",
errMessage: "Error 1451: Cannot delete or update a parent row: a foreign key constraint " +
"fails (`test`.`groups`, CONSTRAINT `groups_group_infos_info` FOREIGN KEY (`group_info`) REFERENCES `group_infos` (`id`))",
expectedConstraint: true,
expectedFK: true,
expectedUnique: false,
},
{
name: "SQLite FK",
errMessage: `FOREIGN KEY constraint failed`,
expectedConstraint: true,
expectedFK: true,
expectedUnique: false,
},
{
name: "Postgres FK",
errMessage: `pq: update or delete on table "group_infos" violates foreign key constraint "groups_group_infos_info" on table "groups"`,
expectedConstraint: true,
expectedFK: true,
expectedUnique: false,
},
{
name: "MySQL Unique",
errMessage: `insert node to table "file_types": UNIQUE constraint failed: file_types.name ent: constraint failed: insert node to table "file_types": UNIQUE constraint failed: file_types.name`,