Describe the feature
A new error type like gorm.ErrUniqueViolation would allow handling errors related to unique violation.
Motivation
Since GORM allows handling common DB errors, it would be nice to support handling errors related to unique violation too.
Related Issues
- https://github.com/go-gorm/gorm/issues/4037
- https://github.com/go-gorm/gorm/issues/4135
Also this at StackOverflow:
GORM create record that might already exist
Comment From: silvioprog
Edit: it would be useful even if declared in the driver (sqlite, postgres, mysql etc.).
Comment From: sleepreading
This error type is widely used, so we all hope gorm will consider adding this feature instead of closing it, again!
Comment From: artlevitan
Use this function to check for errors in SQLite 3
func gormErrUniqueViolation(err error) bool {
e := errors.New("UNIQUE constraint failed")
return !errors.Is(err, e)
}
Example after the INSERT request:
// ...
err = db.Create(&data).Error
if err != nil { // Check SQL Errors
if gormErrUniqueViolation(err) { // UNIQUE constraint failed
// ...
return
}
// ...
}
// ...
Comment From: saeidee
Closing the issue since this feature has been add already. https://github.com/go-gorm/gorm/pull/6004