Yaoxuan Wu created FLINK-41761:
----------------------------------
Summary: CAST(CAST(x AS DOUBLE) AS STRING) is simplified to CAST(x
AS STRING) on master (Calcite 1.41 upgrade; fixed by CALCITE-7870)
Key: FLINK-41761
URL: https://issues.apache.org/jira/browse/FLINK-41761
Project: Flink
Issue Type: Bug
Components: Table SQL / Planner
Affects Versions: 2.4.0
Reporter: Yaoxuan Wu
On master, a cast to STRING of a widening numeric cast drops the inner cast, so
the string is formatted from the original type instead of the intermediate one.
No error is raised. 2.3.0 returns the expected values.
{code:sql}
CREATE TEMPORARY VIEW v AS
SELECT i, d, CAST(s AS FLOAT) AS f
FROM (VALUES (2, CAST(1.50 AS DECIMAL(5, 2)), '-4.673360024033773')) AS t(i, d,
s);
SELECT CAST(CAST(i AS DOUBLE) AS STRING) FROM v; -- '2', expected '2.0'
SELECT CAST(CAST(i AS DECIMAL(12, 2)) AS STRING) FROM v; -- '2', expected
'2.00'
SELECT CAST(CAST(d AS DECIMAL(10, 4)) AS STRING) FROM v; -- '1.50', expected
'1.5000'
SELECT CAST(CAST(f AS DOUBLE) AS STRING) FROM v; -- '-4.67336',
expected '-4.6733598709106445'
{code}
Checked in batch mode. The optimized plan of the first query is
{{Calc(select=[CAST(i AS VARCHAR(2147483647)) AS EXPR$0])}}. Because
projections are merged before simplification, the inner cast can also come from
another projection: with a table source (for example PyFlink's from_elements),
{{SELECT CAST(x AS STRING) FROM (SELECT CAST(f AS DOUBLE) AS x FROM src)}}
returns '-4.67336' as well.
Reproduced on master (2.4-SNAPSHOT, built 2026-11-19). 2.3.0 (Calcite 1.36) is
not affected.
Cause: since the upgrade to Calcite 1.41.0 (FLINK-39859),
RexUtil#isLosslessCast (extended by CALCITE-7174) treats INT -> DOUBLE, FLOAT
-> DOUBLE, INT -> DECIMAL and DECIMAL -> wider DECIMAL as lossless casts.
RexSimplify#simplifyCast (in Flink's copy of
org.apache.calcite.rex.RexSimplify) removes a lossless inner cast whenever the
outer cast can be applied to the original operand ("B" case: isLosslessCast of
the inner cast plus SqlTypeCoercionRule#canApplyFrom), including when the outer
target is a character type, where the result depends on the intermediate type.
This is CALCITE-7870, fixed in Calcite 1.43.0 (commit a2e574ec27: the "B" case
is removed, and approximate numeric -> character casts are no longer lossless).
Flink master is still on Calcite 1.41.0 with its own copy of RexSimplify and
RexUtil, so the fix would need to be ported there, unless the Calcite upgrade
reaches 1.43.0 before the 2.4 release.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)