Skip to content

Commit 30d9faf

Browse files
authored
Merge pull request #1080 from drakkan/sqlstate
error: add SQLState
2 parents 006a3f4 + ef3111e commit 30d9faf

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

error.go

+5
Original file line numberDiff line numberDiff line change
@@ -402,6 +402,11 @@ func (err *Error) Fatal() bool {
402402
return err.Severity == Efatal
403403
}
404404

405+
// SQLState returns the SQLState of the error.
406+
func (err *Error) SQLState() string {
407+
return string(err.Code)
408+
}
409+
405410
// Get implements the legacy PGError interface. New code should use the fields
406411
// of the Error struct directly.
407412
func (err *Error) Get(k byte) (v string) {

go18_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -334,3 +334,19 @@ func TestTxOptions(t *testing.T) {
334334
t.Errorf("Expected error to mention isolation level, got %q", err)
335335
}
336336
}
337+
338+
func TestErrorSQLState(t *testing.T) {
339+
r := readBuf([]byte{67, 52, 48, 48, 48, 49, 0, 0}) // 40001
340+
err := parseError(&r)
341+
var sqlErr errWithSQLState
342+
if !errors.As(err, &sqlErr) {
343+
t.Fatal("SQLState interface not satisfied")
344+
}
345+
if state := err.SQLState(); state != "40001" {
346+
t.Fatalf("unexpected SQL state %v", state)
347+
}
348+
}
349+
350+
type errWithSQLState interface {
351+
SQLState() string
352+
}

0 commit comments

Comments
 (0)