Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SQLState to MySQLError #1321

Merged
merged 3 commits into from Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -110,6 +110,7 @@ Ziheng Lyu <zihenglv at gmail.com>
Barracuda Networks, Inc.
Counting Ltd.
DigitalOcean Inc.
dyves labs AG
Facebook Inc.
GitHub Inc.
Google Inc.
Expand Down
9 changes: 7 additions & 2 deletions errors.go
Expand Up @@ -56,11 +56,16 @@ func SetLogger(logger Logger) error {

// MySQLError is an error type which represents a single MySQL error
type MySQLError struct {
Number uint16
Message string
Number uint16
SQLState [5]byte
Message string
}

func (me *MySQLError) Error() string {
if me.SQLState != [5]byte{} {
return fmt.Sprintf("Error %d (%s): %s", me.Number, me.SQLState, me.Message)
}

return fmt.Sprintf("Error %d: %s", me.Number, me.Message)
}

Expand Down
6 changes: 3 additions & 3 deletions errors_test.go
Expand Up @@ -43,13 +43,13 @@ func TestErrorsStrictIgnoreNotes(t *testing.T) {
}

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

differentCodeErr := &MySQLError{5678, "the server is on fire"}
differentCodeErr := &MySQLError{Number: 5678, Message: "the server is on fire"}
if errors.Is(infraErr, differentCodeErr) {
t.Fatalf("expected errors to be different: %+v %+v", infraErr, differentCodeErr)
}
Expand Down
11 changes: 6 additions & 5 deletions packets.go
Expand Up @@ -587,19 +587,20 @@ func (mc *mysqlConn) handleErrorPacket(data []byte) error {
return driver.ErrBadConn
}

me := &MySQLError{Number: errno}

pos := 3

// SQL State [optional: # + 5bytes string]
if data[3] == 0x23 {
//sqlstate := string(data[4 : 4+5])
copy(me.SQLState[:], data[4:4+5])
pos = 9
}

// Error Message [string]
return &MySQLError{
Number: errno,
Message: string(data[pos:]),
}
me.Message = string(data[pos:])

return me
}

func readStatus(b []byte) statusFlag {
Expand Down