Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expression: wrong result of timestampadd(month,1,date '2024-01-31') #53101

Merged
merged 5 commits into from
May 11, 2024
Merged
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
7 changes: 7 additions & 0 deletions pkg/expression/builtin_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -6232,6 +6232,13 @@ func addUnitToTime(unit string, t time.Time, v float64) (time.Time, bool, error)
return tb, true, nil
}
tb = t.AddDate(0, int(v), 0)

// For corner case: timestampadd(month,1,date '2024-01-31') = "2024-02-29", timestampadd(month,1,date '2024-01-30') = "2024-02-29"
// `tb.Month()` refers to the actual result, `t.Month()+v` refers to the expect result.
// Actual result may be greater than expect result, we need to judge and modify it.
for int(tb.Month())%12 != (int(t.Month())+int(v))%12 {
tb = tb.AddDate(0, 0, -1)
}
case "QUARTER":
if !validAddMonth(v*3, t.Year(), int(t.Month())) {
return tb, true, nil
Expand Down
12 changes: 12 additions & 0 deletions pkg/expression/builtin_time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2580,6 +2580,18 @@ func TestTimestampAdd(t *testing.T) {
{"MINUTE", 1.5, "1995-05-01 00:00:00", "1995-05-01 00:02:00"},
{"MINUTE", 1.5, "1995-05-01 00:00:00.000000", "1995-05-01 00:02:00"},
{"MICROSECOND", -100, "1995-05-01 00:00:00.0001", "1995-05-01 00:00:00"},

// issue41052
{"MONTH", 1, "2024-01-31", "2024-02-29 00:00:00"},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should've at least had one case for negative month.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should've at least had one case for negative month.

fixed in #54916

{"MONTH", 1, "2024-01-30", "2024-02-29 00:00:00"},
{"MONTH", 1, "2024-01-29", "2024-02-29 00:00:00"},
{"MONTH", 1, "2024-01-28", "2024-02-28 00:00:00"},
{"MONTH", 1, "2024-10-31", "2024-11-30 00:00:00"},
{"MONTH", 3, "2024-01-31", "2024-04-30 00:00:00"},
{"MONTH", 15, "2024-01-31", "2025-04-30 00:00:00"},
{"MONTH", 10, "2024-10-31", "2025-08-31 00:00:00"},
{"MONTH", 1, "2024-11-30", "2024-12-30 00:00:00"},
{"MONTH", 13, "2024-11-30", "2025-12-30 00:00:00"},
}

fc := funcs[ast.TimestampAdd]
Expand Down