Skip to content

Commit

Permalink
Feature sqlstate support (#215)
Browse files Browse the repository at this point in the history
* feat: add error code for undefined column

* Add gorm.ErrInvalidField error for 42703 SQLSTATE.
* Add test for new supported error code.

Signed-off-by: alireza <alirezaarzehgar82@gmail.com>

* refactor: remove unnecessary json struct tags

new json fields names was same as struct field names.
It's default behavior of json package and we don't need them.

Signed-off-by: alireza <alirezaarzehgar82@gmail.com>

---------

Signed-off-by: alireza <alirezaarzehgar82@gmail.com>
  • Loading branch information
alirezaarzehgar committed Oct 10, 2023
1 parent f538e03 commit b3c309a
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
7 changes: 4 additions & 3 deletions error_translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@ import (
var errCodes = map[string]error{
"23505": gorm.ErrDuplicatedKey,
"23503": gorm.ErrForeignKeyViolated,
"42703": gorm.ErrInvalidField,
}

type ErrMessage struct {
Code string `json:"Code"`
Severity string `json:"Severity"`
Message string `json:"Message"`
Code string
Severity string
Message string
}

// Translate it will translate the error to native gorm errors.
Expand Down
8 changes: 7 additions & 1 deletion error_translator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package postgres

import (
"errors"
"testing"

"github.com/jackc/pgx/v5/pgconn"
"gorm.io/gorm"
"testing"
)

func TestDialector_Translate(t *testing.T) {
Expand All @@ -30,6 +31,11 @@ func TestDialector_Translate(t *testing.T) {
args: args{err: &pgconn.PgError{Code: "23503"}},
want: gorm.ErrForeignKeyViolated,
},
{
name: "it should return gorm.ErrInvalidField error if the status code is 42703",
args: args{err: &pgconn.PgError{Code: "42703"}},
want: gorm.ErrInvalidField,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit b3c309a

Please sign in to comment.