Skip to content

Commit

Permalink
time column type string formatting and test coverage (#891)
Browse files Browse the repository at this point in the history
* time format test coverage and formatting

* remove whitespace

* drop comments, use require.NoError
  • Loading branch information
jnewmano authored Jun 18, 2024
1 parent 2e5c5ac commit 7ee1864
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
15 changes: 10 additions & 5 deletions mysql/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -324,35 +324,40 @@ 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
if data[0] == 1 {
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 (
Expand Down
28 changes: 28 additions & 0 deletions mysql/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit 7ee1864

Please sign in to comment.