IsForeignKeyViolation checks if the error is due to a foreign key violation. If one or more specific foreign key constraints are given as arguments, the error must be caused by one of them. If no constraints are given, this function returns true for any foreign key violation.
(err error, foreignKeyConstraints ...ForeignKeyConstraint)
| 42 | // the error must be caused by one of them. If no constraints are given, |
| 43 | // this function returns true for any foreign key violation. |
| 44 | func IsForeignKeyViolation(err error, foreignKeyConstraints ...ForeignKeyConstraint) bool { |
| 45 | var pqErr *pq.Error |
| 46 | if errors.As(err, &pqErr) { |
| 47 | if pqErr.Code.Name() == "foreign_key_violation" { |
| 48 | if len(foreignKeyConstraints) == 0 { |
| 49 | return true |
| 50 | } |
| 51 | for _, fc := range foreignKeyConstraints { |
| 52 | if pqErr.Constraint == string(fc) { |
| 53 | return true |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | return false |
| 60 | } |
| 61 | |
| 62 | // IsCheckViolation checks if the error is due to a check violation. If one or |
| 63 | // more specific check constraints are given as arguments, the error must be |