Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion pkg/expression/builtin_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -3204,7 +3204,19 @@ func (du *baseDateArithmetical) addDate(ctx EvalContext, date types.Time, year,
// fix https://github.com/pingcap/tidb/issues/11329
if goTime.Year() == 0 {
hour, minute, second := goTime.Clock()
date.SetCoreTime(types.FromDate(0, 0, 0, hour, minute, second, goTime.Nanosecond()/1000))
// Year/month intervals do calendar arithmetic, so when they drive the year down
// to 0 MySQL keeps the month and day, e.g.
// DATE_SUB('1000-01-01', INTERVAL 1000 YEAR) -> 0000-01-01 (issue #59789).
// Day/time intervals instead underflow past the minimum datetime and yield a
// zero date with the wrapped time, e.g.
// DATE_ADD('0001-01-01 00:00:00', INTERVAL -2 HOUR) -> 0000-00-00 22:00:00 (issue #11329).
// A nonzero year or month component is what distinguishes the calendar case;
// intervals without one (including a zero interval) keep the zero-date normalization.
if (year != 0 || month != 0) && day == 0 && nano == 0 {
date.SetCoreTime(types.FromDate(0, int(goTime.Month()), goTime.Day(), hour, minute, second, goTime.Nanosecond()/1000))
} else {
date.SetCoreTime(types.FromDate(0, 0, 0, hour, minute, second, goTime.Nanosecond()/1000))
}
return date, false, nil
}

Expand Down
3 changes: 3 additions & 0 deletions pkg/expression/builtin_time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2396,6 +2396,9 @@ func TestDateArithFuncs(t *testing.T) {
{"2001-02-28", -1, "2000-02-28"},
{"2004-02-29", 1, "2005-02-28"},
{"2005-02-28", -1, "2004-02-28"},
// A YEAR interval that drives the year down to 0 keeps the month and day,
// matching MySQL instead of zeroing them out. See issue #59789.
{"1000-01-01", -1000, "0000-01-01"},
}

for _, test := range testYears {
Expand Down