Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
129153: eval: fix hlc_to_timestamp builtin r=azhu-crl a=michae2

Builtin function `hlc_to_timestamp` calls internal function `decimalToHLC` which was assuming all input decimals had -10 as the exponent. But some decimals may have other exponents. It's more robust to call `Int64()` on the floored decimal, which handles any exponent.

Fixes: cockroachdb#129152

Release note (bug fix): Fix a bug that would cause `hlc_to_timestamp` to return an incorrect timestamp for some input decimals.

Co-authored-by: Michael Erickson <[email protected]>
  • Loading branch information
craig[bot] and michae2 committed Aug 16, 2024
2 parents 9dd71dc + 9e84135 commit 446bc36
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
15 changes: 8 additions & 7 deletions pkg/sql/sem/eval/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -672,18 +672,19 @@ func DecimalToInexactDTimestampTZ(d *tree.DDecimal) (*tree.DTimestampTZ, error)
}

func decimalToHLC(d *tree.DDecimal) (hlc.Timestamp, error) {
var coef apd.BigInt
coef.Set(&d.Decimal.Coeff)
// The physical portion of the HLC is stored shifted up by 10^10, so shift
// it down and clear out the logical component.
coef.Div(&coef, big10E10)
if !coef.IsInt64() {
var floorD apd.Decimal
if _, err := tree.DecimalCtx.Floor(&floorD, &d.Decimal); err != nil {
return hlc.Timestamp{}, err
}

i, err := floorD.Int64()
if err != nil {
return hlc.Timestamp{}, pgerror.Newf(
pgcode.DatetimeFieldOverflow,
"timestamp value out of range: %s", d.String(),
)
}
return hlc.Timestamp{WallTime: coef.Int64()}, nil
return hlc.Timestamp{WallTime: i}, nil
}

// DecimalToInexactDTimestamp is the inverse of TimestampToDecimal. It converts
Expand Down
10 changes: 10 additions & 0 deletions pkg/sql/sem/eval/testdata/eval/builtins
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,13 @@ eval
hlc_to_timestamp(1627966319623050000.0000000000)
----
'2021-08-03 04:51:59.62305+00'

eval
hlc_to_timestamp(1627966319623050000)
----
'2021-08-03 04:51:59.62305+00'

eval
hlc_to_timestamp(1627966319623050000.00)
----
'2021-08-03 04:51:59.62305+00'

0 comments on commit 446bc36

Please sign in to comment.