Skip to content

Commit 7ee1864

Browse files
authored
time column type string formatting and test coverage (#891)
* time format test coverage and formatting * remove whitespace * drop comments, use require.NoError
1 parent 2e5c5ac commit 7ee1864

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

mysql/util.go

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -324,35 +324,40 @@ func FormatBinaryDateTime(n int, data []byte) ([]byte, error) {
324324

325325
func FormatBinaryTime(n int, data []byte) ([]byte, error) {
326326
if n == 0 {
327-
return []byte("0000-00-00"), nil
327+
return []byte("00:00:00"), nil
328328
}
329329

330330
var sign byte
331331
if data[0] == 1 {
332332
sign = byte('-')
333333
}
334334

335+
var bytes []byte
335336
switch n {
336337
case 8:
337-
return []byte(fmt.Sprintf(
338+
bytes = []byte(fmt.Sprintf(
338339
"%c%02d:%02d:%02d",
339340
sign,
340341
uint16(data[1])*24+uint16(data[5]),
341342
data[6],
342343
data[7],
343-
)), nil
344+
))
344345
case 12:
345-
return []byte(fmt.Sprintf(
346+
bytes = []byte(fmt.Sprintf(
346347
"%c%02d:%02d:%02d.%06d",
347348
sign,
348349
uint16(data[1])*24+uint16(data[5]),
349350
data[6],
350351
data[7],
351352
binary.LittleEndian.Uint32(data[8:12]),
352-
)), nil
353+
))
353354
default:
354355
return nil, errors.Errorf("invalid time packet length %d", n)
355356
}
357+
if bytes[0] == 0 {
358+
return bytes[1:], nil
359+
}
360+
return bytes, nil
356361
}
357362

358363
var (

mysql/util_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,31 @@ func TestCompareServerVersions(t *testing.T) {
2323
require.Equal(t, test.Expect, got)
2424
}
2525
}
26+
27+
func TestFormatBinaryTime(t *testing.T) {
28+
tests := []struct {
29+
Data []byte
30+
Expect string
31+
Error bool
32+
}{
33+
{Data: []byte{}, Expect: "00:00:00"},
34+
{Data: []byte{0, 0, 0, 0, 0, 0, 0, 10}, Expect: "00:00:10"},
35+
{Data: []byte{0, 0, 0, 0, 0, 0, 1, 40}, Expect: "00:01:40"},
36+
{Data: []byte{1, 0, 0, 0, 0, 0, 1, 40}, Expect: "-00:01:40"},
37+
{Data: []byte{1, 1, 0, 0, 0, 1, 1, 40}, Expect: "-25:01:40"},
38+
{Data: []byte{1, 1, 0, 0, 0, 1, 1, 40, 1, 2, 3, 0}, Expect: "-25:01:40.197121"},
39+
{Data: []byte{0}, Error: true},
40+
}
41+
42+
for _, test := range tests {
43+
n := len(test.Data)
44+
45+
got, err := FormatBinaryTime(n, test.Data)
46+
if test.Error {
47+
require.Error(t, err)
48+
} else {
49+
require.NoError(t, err)
50+
}
51+
require.Equal(t, test.Expect, string(got), "test case %v", test.Data)
52+
}
53+
}

0 commit comments

Comments
 (0)