-
-
Notifications
You must be signed in to change notification settings - Fork 179
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: dependency issue with go-sqlite3 package (#143)
* fix: dependency issue with go-sqlite3 package * doc: documentation has been added --------- Co-authored-by: Saeid Saeidee <s.saeidee@sensysgatso.com>
- Loading branch information
Showing
1 changed file
with
22 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,21 +1,37 @@ | ||
package sqlite | ||
|
||
import ( | ||
"github.com/mattn/go-sqlite3" | ||
"encoding/json" | ||
|
||
"gorm.io/gorm" | ||
) | ||
|
||
var errCodes = map[string]sqlite3.ErrNoExtended{ | ||
var errCodes = map[string]int{ | ||
"uniqueConstraint": 2067, | ||
} | ||
|
||
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 { | ||
if sqliteErr, ok := err.(*sqlite3.Error); ok { | ||
if sqliteErr.ExtendedCode == errCodes["uniqueConstraint"] { | ||
return gorm.ErrDuplicatedKey | ||
} | ||
parsedErr, marshalErr := json.Marshal(err) | ||
if marshalErr != nil { | ||
return err | ||
} | ||
|
||
var errMsg ErrMessage | ||
unmarshalErr := json.Unmarshal(parsedErr, &errMsg) | ||
if unmarshalErr != nil { | ||
return err | ||
} | ||
|
||
if errMsg.ExtendedCode == errCodes["uniqueConstraint"] { | ||
return gorm.ErrDuplicatedKey | ||
} | ||
return err | ||
} |