diff --git a/mysql/util.go b/mysql/util.go index 5abe540bc..a6679d0f6 100644 --- a/mysql/util.go +++ b/mysql/util.go @@ -324,7 +324,7 @@ func FormatBinaryDateTime(n int, data []byte) ([]byte, error) { func FormatBinaryTime(n int, data []byte) ([]byte, error) { if n == 0 { - return []byte("0000-00-00"), nil + return []byte("00:00:00"), nil } var sign byte @@ -332,27 +332,32 @@ func FormatBinaryTime(n int, data []byte) ([]byte, error) { sign = byte('-') } + var bytes []byte switch n { case 8: - return []byte(fmt.Sprintf( + bytes = []byte(fmt.Sprintf( "%c%02d:%02d:%02d", sign, uint16(data[1])*24+uint16(data[5]), data[6], data[7], - )), nil + )) case 12: - return []byte(fmt.Sprintf( + bytes = []byte(fmt.Sprintf( "%c%02d:%02d:%02d.%06d", sign, uint16(data[1])*24+uint16(data[5]), data[6], data[7], binary.LittleEndian.Uint32(data[8:12]), - )), nil + )) default: return nil, errors.Errorf("invalid time packet length %d", n) } + if bytes[0] == 0 { + return bytes[1:], nil + } + return bytes, nil } var ( diff --git a/mysql/util_test.go b/mysql/util_test.go index 5851ed81e..22fbe39e4 100644 --- a/mysql/util_test.go +++ b/mysql/util_test.go @@ -23,3 +23,31 @@ func TestCompareServerVersions(t *testing.T) { require.Equal(t, test.Expect, got) } } + +func TestFormatBinaryTime(t *testing.T) { + tests := []struct { + Data []byte + Expect string + Error bool + }{ + {Data: []byte{}, Expect: "00:00:00"}, + {Data: []byte{0, 0, 0, 0, 0, 0, 0, 10}, Expect: "00:00:10"}, + {Data: []byte{0, 0, 0, 0, 0, 0, 1, 40}, Expect: "00:01:40"}, + {Data: []byte{1, 0, 0, 0, 0, 0, 1, 40}, Expect: "-00:01:40"}, + {Data: []byte{1, 1, 0, 0, 0, 1, 1, 40}, Expect: "-25:01:40"}, + {Data: []byte{1, 1, 0, 0, 0, 1, 1, 40, 1, 2, 3, 0}, Expect: "-25:01:40.197121"}, + {Data: []byte{0}, Error: true}, + } + + for _, test := range tests { + n := len(test.Data) + + got, err := FormatBinaryTime(n, test.Data) + if test.Error { + require.Error(t, err) + } else { + require.NoError(t, err) + } + require.Equal(t, test.Expect, string(got), "test case %v", test.Data) + } +}