Skip to content

Commit

Permalink
get sql state from interface (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
acoshift authored Dec 4, 2023
1 parent f892c09 commit 384f920
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 13 deletions.
15 changes: 8 additions & 7 deletions error.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ func contains(xs []string, x string) bool {
return false
}

type sqlState interface {
SQLState() string
}

// IsErrorCode checks is error has given code
func IsErrorCode(err error, code string) bool {
var pqErr *pq.Error
if errors.As(err, &pqErr) && string(pqErr.Code) == code {
return true
}
return false
sErr, ok := err.(sqlState)
return ok && sErr.SQLState() == code
}

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

// IsCharacterNotInRepertoire checks is error an character_not_in_repertoire
// IsCharacterNotInRepertoire checks is error a character_not_in_repertoire
func IsCharacterNotInRepertoire(err error) bool {
return IsErrorCode(err, "22021")
}
Expand All @@ -75,7 +76,7 @@ func IsQueryCanceled(err error) bool {
return IsErrorCode(err, "57014")
}

// IsSerializationFailure checks is error an serialization_failure error
// IsSerializationFailure checks is error a serialization_failure error
// (pq: could not serialize access due to read/write dependencies among transactions)
func IsSerializationFailure(err error) bool {
return IsErrorCode(err, "40001")
Expand Down
5 changes: 1 addition & 4 deletions tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ import (
"context"
"database/sql"
"errors"

"github.com/lib/pq"
)

// ErrAbortTx rollbacks transaction and return nil error
Expand Down Expand Up @@ -79,8 +77,7 @@ func RunInTxContext(ctx context.Context, db BeginTxer, opts *TxOptions, fn func(
if err == nil || errors.Is(err, ErrAbortTx) {
return nil
}
var pqErr *pq.Error
if retryable := errors.As(err, &pqErr) && (pqErr.Code == "40001"); !retryable {
if !IsSerializationFailure(err) {
return err
}
}
Expand Down
2 changes: 0 additions & 2 deletions tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"math/rand"
"sync"
"testing"
"time"

"github.com/acoshift/pgsql"
)
Expand Down Expand Up @@ -118,7 +117,6 @@ func TestTx(t *testing.T) {
}

wg := sync.WaitGroup{}
rand.Seed(time.Now().Unix())
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
Expand Down

0 comments on commit 384f920

Please sign in to comment.