Skip to content

Commit 384f920

Browse files
authored
get sql state from interface (#38)
1 parent f892c09 commit 384f920

3 files changed

Lines changed: 9 additions & 13 deletions

File tree

error.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@ func contains(xs []string, x string) bool {
1616
return false
1717
}
1818

19+
type sqlState interface {
20+
SQLState() string
21+
}
22+
1923
// IsErrorCode checks is error has given code
2024
func IsErrorCode(err error, code string) bool {
21-
var pqErr *pq.Error
22-
if errors.As(err, &pqErr) && string(pqErr.Code) == code {
23-
return true
24-
}
25-
return false
25+
sErr, ok := err.(sqlState)
26+
return ok && sErr.SQLState() == code
2627
}
2728

2829
// IsErrorClass checks is error has given class
@@ -52,7 +53,7 @@ func IsInvalidTextRepresentation(err error) bool {
5253
return IsErrorCode(err, "22P02")
5354
}
5455

55-
// IsCharacterNotInRepertoire checks is error an character_not_in_repertoire
56+
// IsCharacterNotInRepertoire checks is error a character_not_in_repertoire
5657
func IsCharacterNotInRepertoire(err error) bool {
5758
return IsErrorCode(err, "22021")
5859
}
@@ -75,7 +76,7 @@ func IsQueryCanceled(err error) bool {
7576
return IsErrorCode(err, "57014")
7677
}
7778

78-
// IsSerializationFailure checks is error an serialization_failure error
79+
// IsSerializationFailure checks is error a serialization_failure error
7980
// (pq: could not serialize access due to read/write dependencies among transactions)
8081
func IsSerializationFailure(err error) bool {
8182
return IsErrorCode(err, "40001")

tx.go

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import (
44
"context"
55
"database/sql"
66
"errors"
7-
8-
"github.com/lib/pq"
97
)
108

119
// ErrAbortTx rollbacks transaction and return nil error
@@ -79,8 +77,7 @@ func RunInTxContext(ctx context.Context, db BeginTxer, opts *TxOptions, fn func(
7977
if err == nil || errors.Is(err, ErrAbortTx) {
8078
return nil
8179
}
82-
var pqErr *pq.Error
83-
if retryable := errors.As(err, &pqErr) && (pqErr.Code == "40001"); !retryable {
80+
if !IsSerializationFailure(err) {
8481
return err
8582
}
8683
}

tx_test.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import (
77
"math/rand"
88
"sync"
99
"testing"
10-
"time"
1110

1211
"github.com/acoshift/pgsql"
1312
)
@@ -118,7 +117,6 @@ func TestTx(t *testing.T) {
118117
}
119118

120119
wg := sync.WaitGroup{}
121-
rand.Seed(time.Now().Unix())
122120
for i := 0; i < 1000; i++ {
123121
wg.Add(1)
124122
go func() {

0 commit comments

Comments
 (0)