From 4c3af63076c005e75436710bd06e83b9720862cc Mon Sep 17 00:00:00 2001 From: John Date: Sat, 1 Feb 2020 20:14:24 +0800 Subject: [PATCH] improve time string parsing for invalid datetime --- .example/database/gdb/mysql/gdb_value.go | 6 +----- database/gdb/gdb_unit_z_mysql_types_test.go | 6 +++--- os/gtime/gtime.go | 3 +++ os/gtime/gtime_z_unit_format_test.go | 8 ++++++++ 4 files changed, 15 insertions(+), 8 deletions(-) diff --git a/.example/database/gdb/mysql/gdb_value.go b/.example/database/gdb/mysql/gdb_value.go index a8adade8a..400323a16 100644 --- a/.example/database/gdb/mysql/gdb_value.go +++ b/.example/database/gdb/mysql/gdb_value.go @@ -8,10 +8,6 @@ func main() { db := g.DB() db.SetDebug(true) - one, e := db.Table("order.order o").LeftJoin("user.user u", "o.uid=u.id").Where("u.id", 1).One() - if e != nil { - panic(e) - } - g.Dump(one) + db.Table("user").Fields("DISTINCT id,nickname").Filter().All() } diff --git a/database/gdb/gdb_unit_z_mysql_types_test.go b/database/gdb/gdb_unit_z_mysql_types_test.go index 8baeabc6d..e537c0bb7 100644 --- a/database/gdb/gdb_unit_z_mysql_types_test.go +++ b/database/gdb/gdb_unit_z_mysql_types_test.go @@ -43,8 +43,8 @@ func Test_Types(t *testing.T) { "binary": []byte("abcdefgh"), "date": "2018-10-24", "time": "10:00:01", - "decimal": 123.456, - "double": 123.456, + "decimal": -123.456, + "double": -123.456, "bit": 2, "tinyint": true, "bool": false, @@ -61,7 +61,7 @@ func Test_Types(t *testing.T) { gtest.Assert(one["binary"].String(), data["binary"]) gtest.Assert(one["date"].String(), data["date"]) gtest.Assert(one["time"].String(), data["time"]) - gtest.Assert(one["decimal"].String(), 123.46) + gtest.Assert(one["decimal"].String(), -123.46) gtest.Assert(one["double"].String(), data["double"]) gtest.Assert(one["bit"].Int(), data["bit"]) gtest.Assert(one["tinyint"].Bool(), data["tinyint"]) diff --git a/os/gtime/gtime.go b/os/gtime/gtime.go index 2f36b0d89..7f46816e7 100644 --- a/os/gtime/gtime.go +++ b/os/gtime/gtime.go @@ -316,6 +316,9 @@ func StrToTime(str string, format ...string) (*Time, error) { } } } + if year <= 0 || month <= 0 || day <= 0 || hour < 0 || min < 0 || sec < 0 || nsec < 0 { + return nil, errors.New("invalid time string:" + str) + } // It finally converts all time to UTC time zone. return NewFromTime(time.Date(year, time.Month(month), day, hour, min, sec, nsec, local)), nil } diff --git a/os/gtime/gtime_z_unit_format_test.go b/os/gtime/gtime_z_unit_format_test.go index fa79a5e7f..743aead20 100644 --- a/os/gtime/gtime_z_unit_format_test.go +++ b/os/gtime/gtime_z_unit_format_test.go @@ -94,6 +94,14 @@ func Test_Format(t *testing.T) { }) } +func Test_Format_ZeroString(t *testing.T) { + gtest.Case(t, func() { + timeTemp, err := gtime.StrToTime("0000-00-00 00:00:00") + gtest.AssertNE(err, nil) + gtest.Assert(timeTemp.String(), "") + }) +} + func Test_FormatTo(t *testing.T) { gtest.Case(t, func() { timeTemp := gtime.Now()