gorm icon indicating copy to clipboard operation
gorm copied to clipboard

Please add "gorm.ErrUniqueViolation" support

Open silvioprog opened this issue 2 years ago • 2 comments

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

  1. https://github.com/go-gorm/gorm/issues/4037
  2. https://github.com/go-gorm/gorm/issues/4135

Also this at StackOverflow:

GORM create record that might already exist

silvioprog avatar Aug 28 '22 02:08 silvioprog

Edit: it would be useful even if declared in the driver (sqlite, postgres, mysql etc.).

silvioprog avatar Aug 28 '22 02:08 silvioprog

This error type is widely used, so we all hope gorm will consider adding this feature instead of closing it, again!

sleepreading avatar Aug 29 '22 05:08 sleepreading

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
		}
		// ...
	}
// ...

artlevitan avatar Jan 08 '23 12:01 artlevitan

Closing the issue since this feature has been add already. https://github.com/go-gorm/gorm/pull/6004

saeidee avatar May 31 '23 20:05 saeidee