From 2a5c602f5e4d007bb93105f74bb2095fbbbd715c Mon Sep 17 00:00:00 2001 From: Qishuai Liu Date: Fri, 6 Sep 2024 17:23:12 +0900 Subject: [PATCH] handle MySQL zero date --- cursor.go | 4 ++++ cursor_test.go | 1 + expression.go | 11 ++++++++--- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/cursor.go b/cursor.go index 0000fd5..0a5003f 100644 --- a/cursor.go +++ b/cursor.go @@ -53,6 +53,10 @@ func guessTimeLayout(s string) string { } func parseTime(s string) (time.Time, error) { + if strings.HasPrefix(s, "0000-00-00") { + // MySQL zero date + return time.Time{}, nil + } layout := guessTimeLayout(s) t, err := time.Parse(layout, s) if err != nil { diff --git a/cursor_test.go b/cursor_test.go index 039d9c8..5e954c2 100644 --- a/cursor_test.go +++ b/cursor_test.go @@ -219,6 +219,7 @@ func TestParseTime(t *testing.T) { {"2024-09-06 11:22:33.444", time.Date(2024, 9, 6, 11, 22, 33, 444000000, time.UTC)}, {"2024-09-06 11:22:33.444555666", time.Date(2024, 9, 6, 11, 22, 33, 444555666, time.UTC)}, {"2024-09-06T11:22:33.444555666Z", time.Date(2024, 9, 6, 11, 22, 33, 444555666, time.UTC)}, + {"0000-00-00 00:00:00", time.Time{}}, } for _, test := range tests { tm, err := parseTime(test.input) diff --git a/expression.go b/expression.go index 954e4e3..b2c687a 100644 --- a/expression.go +++ b/expression.go @@ -356,11 +356,16 @@ func getSQL(scope scope, value interface{}) (sql string, priority priority, err case CaseExpression: sql, err = value.(CaseExpression).End().GetSQL(scope) case time.Time: - tmStr := value.(time.Time).Format(mysqlTimeFormat) - sql = quoteString(tmStr) + tm := value.(time.Time) + if tm.IsZero() { + sql = "NULL" + } else { + tmStr := tm.Format(mysqlTimeFormat) + sql = quoteString(tmStr) + } case *time.Time: tm := value.(*time.Time) - if tm == nil { + if tm == nil || tm.IsZero() { sql = "NULL" } else { tmStr := tm.Format(mysqlTimeFormat)