Skip to content

Commit cb7f946

Browse files
saeideeSaeid Saeideejinzhu
authored
feat: foreign key violatation error (go-gorm#150)
Co-authored-by: Saeid Saeidee <[email protected]> Co-authored-by: Jinzhu <[email protected]>
1 parent 86ba643 commit cb7f946

File tree

3 files changed

+8
-5
lines changed

3 files changed

+8
-5
lines changed

error_translator.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ import (
66
"gorm.io/gorm"
77
)
88

9-
var errCodes = map[string]int{
10-
"uniqueConstraint": 2067,
9+
var errCodes = map[int]error{
10+
2067: gorm.ErrDuplicatedKey,
11+
768: gorm.ErrForeignKeyViolated,
1112
}
1213

1314
type ErrMessage struct {
@@ -30,8 +31,8 @@ func (dialector Dialector) Translate(err error) error {
3031
return err
3132
}
3233

33-
if errMsg.ExtendedCode == errCodes["uniqueConstraint"] {
34-
return gorm.ErrDuplicatedKey
34+
if translatedErr, found := errCodes[errMsg.ExtendedCode]; found {
35+
return translatedErr
3536
}
3637
return err
3738
}

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ go 1.20
44

55
require (
66
github.com/mattn/go-sqlite3 v1.14.17
7-
gorm.io/gorm v1.25.0
7+
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55
88
)
99

1010
require (

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,5 @@ github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6
66
github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
77
gorm.io/gorm v1.25.0 h1:+KtYtb2roDz14EQe4bla8CbQlmb9dN3VejSai3lprfU=
88
gorm.io/gorm v1.25.0/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=
9+
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55 h1:sC1Xj4TYrLqg1n3AN10w871An7wJM0gzgcm8jkIkECQ=
10+
gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=

0 commit comments

Comments
 (0)