IsUniqueViolation checks if the error is due to a unique violation. If one or more specific unique 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 unique violation.
(err error, uniqueConstraints ...UniqueConstraint)
| 20 | // the error must be caused by one of them. If no constraints are given, |
| 21 | // this function returns true for any unique violation. |
| 22 | func IsUniqueViolation(err error, uniqueConstraints ...UniqueConstraint) bool { |
| 23 | var pqErr *pq.Error |
| 24 | if errors.As(err, &pqErr) { |
| 25 | if pqErr.Code.Name() == "unique_violation" { |
| 26 | if len(uniqueConstraints) == 0 { |
| 27 | return true |
| 28 | } |
| 29 | for _, uc := range uniqueConstraints { |
| 30 | if pqErr.Constraint == string(uc) { |
| 31 | return true |
| 32 | } |
| 33 | } |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | return false |
| 38 | } |
| 39 | |
| 40 | // IsForeignKeyViolation checks if the error is due to a foreign key violation. |
| 41 | // If one or more specific foreign key constraints are given as arguments, |