Skip to content

Commit

Permalink
extract and document serialization failure check
Browse files Browse the repository at this point in the history
  • Loading branch information
vito committed Nov 20, 2018
1 parent 587081a commit 85dd068
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions storage/sql/sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,21 @@ func matchLiteral(s string) *regexp.Regexp {
return regexp.MustCompile(`\b` + regexp.QuoteMeta(s) + `\b`)
}

// Detect a serialization failure, which should trigger retrying the
// transaction according to PostgreSQL docs:
//
// https://www.postgresql.org/docs/current/transaction-iso.html#XACT-SERIALIZABLE
//
// "applications using this level must be prepared to retry transactions due to
// serialization failures"
func isRetryableSerializationFailure(err error) bool {
if pqErr, ok := err.(*pq.Error); ok {
return pqErr.Code.Name() == "serialization_failure"
}

return false
}

var (
// The "github.com/lib/pq" driver is the default flavor. All others are
// translations of this.
Expand Down Expand Up @@ -67,8 +82,7 @@ var (
}

if err := fn(tx); err != nil {
if pqErr, ok := err.(*pq.Error); ok && pqErr.Code.Name() == "serialization_failure" {
// serialization error; retry
if isRetryableSerializationFailure(err) {
continue
}

Expand All @@ -77,8 +91,7 @@ var (

err = tx.Commit()
if err != nil {
if pqErr, ok := err.(*pq.Error); ok && pqErr.Code.Name() == "serialization_failure" {
// serialization error; retry
if isRetryableSerializationFailure(err) {
continue
}

Expand Down

0 comments on commit 85dd068

Please sign in to comment.