Skip to content

Commit

Permalink
performance improvement for parseDateTime (go-sql-driver#1098)
Browse files Browse the repository at this point in the history
  • Loading branch information
chanxuehong authored and tz70s committed Sep 5, 2020
1 parent 0c21234 commit 2e93185
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 10 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Expand Up @@ -90,6 +90,7 @@ Vladimir Kovpak <cn007b at gmail.com>
Xiangyu Hu <xiangyu.hu at outlook.com>
Xiaobing Jiang <s7v7nislands at gmail.com>
Xiuming Chen <cc at cxm.cc>
Xuehong Chan <chanxuehong at gmail.com>
Zhenye Xie <xiezhenye at gmail.com>
Zhixin Wen <john.wenzhixin at gmail.com>

Expand Down
14 changes: 4 additions & 10 deletions utils.go
Expand Up @@ -113,20 +113,14 @@ func parseDateTime(str string, loc *time.Location) (t time.Time, err error) {
if str == base[:len(str)] {
return
}
t, err = time.Parse(timeFormat[:len(str)], str)
if loc == time.UTC {
return time.Parse(timeFormat[:len(str)], str)
}
return time.ParseInLocation(timeFormat[:len(str)], str, loc)
default:
err = fmt.Errorf("invalid time string: %s", str)
return
}

// Adjust location
if err == nil && loc != time.UTC {
y, mo, d := t.Date()
h, mi, s := t.Clock()
t, err = time.Date(y, mo, d, h, mi, s, t.Nanosecond(), loc), nil
}

return
}

func parseBinaryDateTime(num uint64, data []byte, loc *time.Location) (driver.Value, error) {
Expand Down
43 changes: 43 additions & 0 deletions utils_test.go
Expand Up @@ -14,6 +14,7 @@ import (
"database/sql/driver"
"encoding/binary"
"testing"
"time"
)

func TestLengthEncodedInteger(t *testing.T) {
Expand Down Expand Up @@ -291,3 +292,45 @@ func TestIsolationLevelMapping(t *testing.T) {
t.Fatalf("Expected error to be %q, got %q", expectedErr, err)
}
}

func TestParseDateTime(t *testing.T) {
// UTC loc
{
str := "2020-05-13 21:30:45"
t1, err := parseDateTime(str, time.UTC)
if err != nil {
t.Error(err)
return
}
t2 := time.Date(2020, 5, 13,
21, 30, 45, 0, time.UTC)
if !t1.Equal(t2) {
t.Errorf("want equal, have: %v, want: %v", t1, t2)
return
}
}
// non-UTC loc
{
str := "2020-05-13 21:30:45"
loc := time.FixedZone("test", 8*60*60)
t1, err := parseDateTime(str, loc)
if err != nil {
t.Error(err)
return
}
t2 := time.Date(2020, 5, 13,
21, 30, 45, 0, loc)
if !t1.Equal(t2) {
t.Errorf("want equal, have: %v, want: %v", t1, t2)
return
}
}
}

func BenchmarkParseDateTime(b *testing.B) {
str := "2020-05-13 21:30:45"
loc := time.FixedZone("test", 8*60*60)
for i := 0; i < b.N; i++ {
_, _ = parseDateTime(str, loc)
}
}

0 comments on commit 2e93185

Please sign in to comment.