Skip to content

Commit

Permalink
handle MySQL zero date
Browse files Browse the repository at this point in the history
  • Loading branch information
lqs committed Sep 6, 2024
1 parent 65c4cf7 commit 2a5c602
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
4 changes: 4 additions & 0 deletions cursor.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
1 change: 1 addition & 0 deletions cursor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
11 changes: 8 additions & 3 deletions expression.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 2a5c602

Please sign in to comment.