Skip to content

Commit ad9fa14

Browse files
authored
Add SQLState to MySQLError (go-sql-driver#1321)
Report SQLState in MySQLError to allow library users to distinguish user-defined from client / server errors.
1 parent eff3908 commit ad9fa14

File tree

4 files changed

+17
-10
lines changed

4 files changed

+17
-10
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ Ziheng Lyu <zihenglv at gmail.com>
110110
Barracuda Networks, Inc.
111111
Counting Ltd.
112112
DigitalOcean Inc.
113+
dyves labs AG
113114
Facebook Inc.
114115
GitHub Inc.
115116
Google Inc.

errors.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -56,11 +56,16 @@ func SetLogger(logger Logger) error {
5656

5757
// MySQLError is an error type which represents a single MySQL error
5858
type MySQLError struct {
59-
Number uint16
60-
Message string
59+
Number uint16
60+
SQLState [5]byte
61+
Message string
6162
}
6263

6364
func (me *MySQLError) Error() string {
65+
if me.SQLState != [5]byte{} {
66+
return fmt.Sprintf("Error %d (%s): %s", me.Number, me.SQLState, me.Message)
67+
}
68+
6469
return fmt.Sprintf("Error %d: %s", me.Number, me.Message)
6570
}
6671

errors_test.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,13 @@ func TestErrorsStrictIgnoreNotes(t *testing.T) {
4343
}
4444

4545
func TestMySQLErrIs(t *testing.T) {
46-
infraErr := &MySQLError{1234, "the server is on fire"}
47-
otherInfraErr := &MySQLError{1234, "the datacenter is flooded"}
46+
infraErr := &MySQLError{Number: 1234, Message: "the server is on fire"}
47+
otherInfraErr := &MySQLError{Number: 1234, Message: "the datacenter is flooded"}
4848
if !errors.Is(infraErr, otherInfraErr) {
4949
t.Errorf("expected errors to be the same: %+v %+v", infraErr, otherInfraErr)
5050
}
5151

52-
differentCodeErr := &MySQLError{5678, "the server is on fire"}
52+
differentCodeErr := &MySQLError{Number: 5678, Message: "the server is on fire"}
5353
if errors.Is(infraErr, differentCodeErr) {
5454
t.Fatalf("expected errors to be different: %+v %+v", infraErr, differentCodeErr)
5555
}

packets.go

+6-5
Original file line numberDiff line numberDiff line change
@@ -587,19 +587,20 @@ func (mc *mysqlConn) handleErrorPacket(data []byte) error {
587587
return driver.ErrBadConn
588588
}
589589

590+
me := &MySQLError{Number: errno}
591+
590592
pos := 3
591593

592594
// SQL State [optional: # + 5bytes string]
593595
if data[3] == 0x23 {
594-
//sqlstate := string(data[4 : 4+5])
596+
copy(me.SQLState[:], data[4:4+5])
595597
pos = 9
596598
}
597599

598600
// Error Message [string]
599-
return &MySQLError{
600-
Number: errno,
601-
Message: string(data[pos:]),
602-
}
601+
me.Message = string(data[pos:])
602+
603+
return me
603604
}
604605

605606
func readStatus(b []byte) statusFlag {

0 commit comments

Comments
 (0)