diff --git a/compiler/ztests/sql/timestamp-and-date.yaml b/compiler/ztests/sql/timestamp-and-date.yaml index 6279232f4e..c4a2884c75 100644 --- a/compiler/ztests/sql/timestamp-and-date.yaml +++ b/compiler/ztests/sql/timestamp-and-date.yaml @@ -1,4 +1,4 @@ -spq: values TIMESTAMP '2012-10-02 12:01:01', DATE '2012-10-02 12:01:01' +spq: values TIMESTAMP '2012-10-02 12:01:01', DATE '2012-10-02 12:01:01', DATE '1969-07-20 20:17:40' input: | null @@ -6,3 +6,4 @@ input: | output: | 2012-10-02T12:01:01Z 2012-10-02T00:00:00Z + 1969-07-20T00:00:00Z diff --git a/pkg/nano/duration.go b/pkg/nano/duration.go index 1e34c897fb..0c87adc282 100644 --- a/pkg/nano/duration.go +++ b/pkg/nano/duration.go @@ -103,7 +103,14 @@ func writeFixedPoint(b *strings.Builder, ns, scale int64) { } func (d Duration) Trunc(bin Duration) Duration { - return d / bin * bin + r := d % bin + if r < 0 { + r += max(bin, -bin) + if d < math.MinInt64+r { + return math.MinInt64 + } + } + return d - r } func (d Duration) MarshalJSON() ([]byte, error) { diff --git a/pkg/nano/time.go b/pkg/nano/time.go index 914a617226..d38236529f 100644 --- a/pkg/nano/time.go +++ b/pkg/nano/time.go @@ -82,7 +82,7 @@ func (t Ts) Time() time.Time { } func (t Ts) Trunc(bin Duration) Ts { - return Ts(Duration(t) / bin * bin) + return Ts(Duration(t).Trunc(bin)) } func (t Ts) Midnight() Ts { diff --git a/runtime/ztests/expr/function/bucket.yaml b/runtime/ztests/expr/function/bucket.yaml index e1772a2fa2..de387fa134 100644 --- a/runtime/ztests/expr/function/bucket.yaml +++ b/runtime/ztests/expr/function/bucket.yaml @@ -41,3 +41,64 @@ spq: SELECT CAST(TIMESTAMP '2020-05-26 15:27:47' AS DATE) AS d output: | {d:2020-05-26T00:00:00Z} + +--- + +# Timestamps before 1970 and negative durations round down, not toward zero, +# whatever the sign of the span. +spq: values bucket(t, bin) + +input: | + {t:1969-12-31T23:30:00Z,bin:1h} + {t:1969-07-20T20:17:40Z,bin:1d} + {t:-3s,bin:2s} + {t:-4s,bin:2s} + {t:-3s,bin:-2s} + {t:3s,bin:-2s} + +output: | + 1969-12-31T23:00:00Z + 1969-07-20T00:00:00Z + -4s + -4s + -4s + 2s + +--- + +# A constant span rounds column values and constants down before 1970 too. +spq: values bucket(this, 1h), bucket(1969-12-31T23:30:00Z, 1h) + +input: | + 1969-12-31T23:59:59Z + -1s + +output: | + 1969-12-31T23:00:00Z + 1969-12-31T23:00:00Z + -1h + 1969-12-31T23:00:00Z + +--- + +# A SQL cast to DATE gives the right day before 1970. +spq: SELECT CAST(TIMESTAMP '1969-07-20 20:17:40' AS DATE) AS d + +output: | + {d:1969-07-20T00:00:00Z} + +--- + +# A bucket that would start before the earliest timestamp or shortest +# duration starts there instead of wrapping around. +spq: values bucket(this, 100y) + +input: | + 1700-01-01T00:00:00Z + 1770-02-18T00:00:00Z + -292y171d23h47m16.854775807s + +output: | + 1677-09-21T00:12:43.145224192Z + 1770-02-18T00:00:00Z + -292y171d23h47m16.854775808s