Skip to content

Commit

Permalink
util: Fix interval division with float rounds differently from Postgr…
Browse files Browse the repository at this point in the history
…eSQL

Before this commit, the nanos will be rounded in `MakeDuration`.
This commit round down nanos before `rounded` is called in the div of duration.

Fixes cockroachdb#66118

Release note (bug fix): Fixed a bug with PostgreSQL compatibility where
dividing an interval by a number would round to the nearest Microsecond
instead of always rounding down.
  • Loading branch information
TszKitLo40 committed Jun 11, 2021
1 parent d30ba59 commit 636a8b1
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
9 changes: 9 additions & 0 deletions pkg/sql/logictest/testdata/logic_test/interval
Original file line number Diff line number Diff line change
Expand Up @@ -367,3 +367,12 @@ subtest regression_62369

query error "10000000000000000000000000000000000": value out of range
SELECT INTERVAL '10000000000000000000000000000000000 year'

query T
SELECT i / 2 FROM ( VALUES
('0 days 0.253000 seconds'::interval),
(INTERVAL '0.000001'::interval)
) regression_66118(i)
----
00:00:00.126
00:00:00
5 changes: 4 additions & 1 deletion pkg/util/duration/duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -619,9 +619,12 @@ func (d Duration) MulFloat(x float64) Duration {
func (d Duration) DivFloat(x float64) Duration {
monthInt, monthFrac := math.Modf(float64(d.Months) / x)
dayInt, dayFrac := math.Modf((float64(d.Days) / x) + (monthFrac * DaysPerMonth))
// We ensure we round down nanoseconds when doing division to
// match PostgreSQL.
retNanos := time.Duration(float64(d.nanos)/x).Truncate(time.Millisecond)

return MakeDuration(
int64((float64(d.nanos)/x)+(dayFrac*float64(nanosInDay))),
int64(float64(retNanos.Nanoseconds())+(dayFrac*float64(nanosInDay))),
int64(dayInt),
int64(monthInt),
)
Expand Down
12 changes: 12 additions & 0 deletions pkg/util/duration/duration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,18 @@ func TestFloatMath(t *testing.T) {
Duration{Months: 2, Days: 34, nanos: nanosInHour * 4},
Duration{Days: 23, nanos: nanosInHour * 13},
},
{
Duration{Months: 0, Days: 0, nanos: nanosInSecond * 0.253000},
3.2,
Duration{Months: 0, Days: 0, nanos: nanosInSecond * 0.8096},
Duration{Months: 0, Days: 0, nanos: nanosInSecond * 0.079062},
},
{
Duration{Months: 0, Days: 0, nanos: nanosInSecond * 0.000001},
2.0,
Duration{Months: 0, Days: 0, nanos: nanosInSecond * 0.000002},
Duration{Months: 0, Days: 0, nanos: nanosInSecond * 0},
},
}

for i, test := range tests {
Expand Down

0 comments on commit 636a8b1

Please sign in to comment.