Files
sqlite/error_translator.go
Fabio Bonelli 2a60d4fe20 fix: translate SQLITE_CONSTRAINT_PRIMARYKEY to ErrDuplicatedKey (#152)
Translate the SQLITE_CONSTRAINT_PRIMARYKEY error code to
ErrDuplicatedKey as well for consistency.
2023-06-09 10:18:50 +08:00

40 lines
881 B
Go

package sqlite
import (
"encoding/json"
"gorm.io/gorm"
)
var errCodes = map[int]error{
1555: gorm.ErrDuplicatedKey,
2067: gorm.ErrDuplicatedKey,
768: gorm.ErrForeignKeyViolated,
}
type ErrMessage struct {
Code int `json:"Code"`
ExtendedCode int `json:"ExtendedCode"`
SystemErrno int `json:"SystemErrno"`
}
// Translate it will translate the error to native gorm errors.
// We are not using go-sqlite3 error type intentionally here because it will need the CGO_ENABLED=1 and cross-C-compiler.
func (dialector Dialector) Translate(err error) error {
parsedErr, marshalErr := json.Marshal(err)
if marshalErr != nil {
return err
}
var errMsg ErrMessage
unmarshalErr := json.Unmarshal(parsedErr, &errMsg)
if unmarshalErr != nil {
return err
}
if translatedErr, found := errCodes[errMsg.ExtendedCode]; found {
return translatedErr
}
return err
}