feat: Unique Constraint Violation error translator for different drivers (#6004)

* feat: duplicated key error translator for different drivers

* test: removed the dependency

* test: fixed broken tests

* refactor: added ErrorTransltor interface

* style: applied styler

---------

Co-authored-by: Saeid Saeidee <s.saeidee@sensysgatso.com>
This commit is contained in:
Saeid Kanishka 2023-03-06 07:03:31 +01:00 committed by GitHub
parent f3874339ef
commit 85eaf9eeda
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 36 additions and 1 deletions

View File

@ -45,4 +45,6 @@ var (
ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match") ErrInvalidValueOfLength = errors.New("invalid association values, length doesn't match")
// ErrPreloadNotAllowed preload is not allowed when count is used // ErrPreloadNotAllowed preload is not allowed when count is used
ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used") ErrPreloadNotAllowed = errors.New("preload is not allowed when count is used")
// ErrDuplicatedKey occurs when there is a unique key constraint violation
ErrDuplicatedKey = errors.New("duplicated key not allowed")
) )

View File

@ -347,6 +347,10 @@ func (db *DB) Callback() *callbacks {
// AddError add error to db // AddError add error to db
func (db *DB) AddError(err error) error { func (db *DB) AddError(err error) error {
if errTranslator, ok := db.Dialector.(ErrorTranslator); ok {
err = errTranslator.Translate(err)
}
if db.Error == nil { if db.Error == nil {
db.Error = err db.Error = err
} else if err != nil { } else if err != nil {

View File

@ -86,3 +86,7 @@ type Rows interface {
Err() error Err() error
Close() error Close() error
} }
type ErrorTranslator interface {
Translate(err error) error
}

View File

@ -0,0 +1,19 @@
package tests_test
import (
"errors"
"testing"
"gorm.io/gorm"
"gorm.io/gorm/utils/tests"
)
func TestDialectorWithErrorTranslatorSupport(t *testing.T) {
translatedErr := errors.New("translated error")
db, _ := gorm.Open(tests.DummyDialector{TranslatedErr: translatedErr})
err := db.AddError(errors.New("some random error"))
if !errors.Is(err, translatedErr) {
t.Fatalf("expected err: %v got err: %v", translatedErr, err)
}
}

View File

@ -8,7 +8,9 @@ import (
"gorm.io/gorm/schema" "gorm.io/gorm/schema"
) )
type DummyDialector struct{} type DummyDialector struct {
TranslatedErr error
}
func (DummyDialector) Name() string { func (DummyDialector) Name() string {
return "dummy" return "dummy"
@ -92,3 +94,7 @@ func (DummyDialector) Explain(sql string, vars ...interface{}) string {
func (DummyDialector) DataTypeOf(*schema.Field) string { func (DummyDialector) DataTypeOf(*schema.Field) string {
return "" return ""
} }
func (d DummyDialector) Translate(err error) error {
return d.TranslatedErr
}