[
https://issues.apache.org/jira/browse/CALCITE-7968?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel
]
Alessandro Solimando updated CALCITE-7968:
------------------------------------------
Affects Version/s: 1.42.0
> RexUtil.isLosslessCast returns true for a cast from DECIMAL(19, 0) to BIGINT
> ----------------------------------------------------------------------------
>
> Key: CALCITE-7968
> URL: https://issues.apache.org/jira/browse/CALCITE-7968
> Project: Calcite
> Issue Type: Bug
> Affects Versions: 1.42.0
> Reporter: Weihua Zhang
> Assignee: Alessandro Solimando
> Priority: Major
> Labels: pull-request-available
>
> [_SqlTypeUtil#integerBound_|https://github.com/apache/calcite/blob/a5557abef8aa8a83fe7241e4f3c11c95c30d2563/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java#L658-L664]
> computes the bounds of a DECIMAL with {_}SqlTypeName#getLimit{_}. For
> DECIMAL(p, 0),
> [_getLimit_|https://github.com/apache/calcite/blob/a5557abef8aa8a83fe7241e4f3c11c95c30d2563/core/src/main/java/org/apache/calcite/sql/type/SqlTypeName.java#L606-L612]
> computes -(10^p - 1) and 10^p - 1, and then replaces each bound that is
> outside the range of BIGINT with the corresponding bound of BIGINT.
> For p >= 19, _integerBound_ therefore returns the bounds of BIGINT, although
> DECIMAL(19, 0) holds values up to 9999999999999999999, beyond BIGINT's upper
> limit (9223372036854775807).
> [_RexUtil#isLosslessCast_|https://github.com/apache/calcite/blob/a5557abef8aa8a83fe7241e4f3c11c95c30d2563/core/src/main/java/org/apache/calcite/rex/RexUtil.java#L1988-L1993]
> decides a DECIMAL to integer cast by comparing these bounds, so it returns
> true for a cast from DECIMAL(19, 0) to BIGINT, and for any DECIMAL(p, 0) with
> p >= 19 in a type system that allows it.
> _isLosslessCast_ must not return false positives, as callers rely on this for
> correctness. For instance, an INSERT of a DECIMAL(19, 0) value that does not
> fit into a BIGINT column might store NULL instead of failing.
> Reproducer (for {_}RexLosslessCastTest{_}):
> {code:java}
> @Test void testLosslessCastDecimalToBigint() {
> final RelDataType bigIntType =
> typeFactory.createSqlType(SqlTypeName.BIGINT);
> final RelDataType dec_18_0 = typeFactory.createSqlType(SqlTypeName.DECIMAL,
> 18, 0);
> final RelDataType dec_19_0 = typeFactory.createSqlType(SqlTypeName.DECIMAL,
> 19, 0);
> assertThat(RexUtil.isLosslessCast(dec_18_0, bigIntType), is(true));
> assertThat(RexUtil.isLosslessCast(dec_19_0, bigIntType), is(false));
> }
> {code}
> The test currently fails as follows:
> {noformat}
> java.lang.AssertionError:
> Expected: is <false>
> but: was <true>
> {noformat}
> Proposed fix: compute the bounds of DECIMAL(p, 0) in _integerBound_ as -(10^p
> - 1) and 10^p - 1, without limiting them to the range of BIGINT.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)