From ef3111ea5aefd45f868ed58012b1d0d0dd162982 Mon Sep 17 00:00:00 2001 From: Nicola Murino Date: Fri, 6 May 2022 18:11:14 +0200 Subject: [PATCH] error: add SQLState SQLState is also implemented in pgx. This change allow to get the SQL state without importing lib/pq, see for example here https://github.com/cockroachdb/cockroach-go/blob/e1659d1d3580897bce4cea1181724872d792ce53/crdb/tx.go#L232 --- error.go | 5 +++++ go18_test.go | 16 ++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/error.go b/error.go index 5cfe9c6e..21b3d933 100644 --- a/error.go +++ b/error.go @@ -402,6 +402,11 @@ func (err *Error) Fatal() bool { return err.Severity == Efatal } +// SQLState returns the SQLState of the error. +func (err *Error) SQLState() string { + return string(err.Code) +} + // Get implements the legacy PGError interface. New code should use the fields // of the Error struct directly. func (err *Error) Get(k byte) (v string) { diff --git a/go18_test.go b/go18_test.go index bcc02006..6166db27 100644 --- a/go18_test.go +++ b/go18_test.go @@ -334,3 +334,19 @@ func TestTxOptions(t *testing.T) { t.Errorf("Expected error to mention isolation level, got %q", err) } } + +func TestErrorSQLState(t *testing.T) { + r := readBuf([]byte{67, 52, 48, 48, 48, 49, 0, 0}) // 40001 + err := parseError(&r) + var sqlErr errWithSQLState + if !errors.As(err, &sqlErr) { + t.Fatal("SQLState interface not satisfied") + } + if state := err.SQLState(); state != "40001" { + t.Fatalf("unexpected SQL state %v", state) + } +} + +type errWithSQLState interface { + SQLState() string +}