Skip to content

Commit ef3111e

Browse files
committedMay 6, 2022
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
1 parent 006a3f4 commit ef3111e

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)
Please sign in to comment.