Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix wrong result of cast(float as decimal) when overflow happens (#4380) #4391

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions dbms/src/Functions/FunctionsTiDBConversion.h
Original file line number Diff line number Diff line change
Expand Up @@ -1170,8 +1170,20 @@ struct TiDBConvertToDecimal
/// cast int/real as decimal
const typename ColumnVector<FromFieldType>::Container & vec_from = col_from->getData();

for (size_t i = 0; i < size; ++i)
vec_to[i] = toTiDBDecimal<FromFieldType, ToFieldType>(vec_from[i], prec, scale, context);
if constexpr (std::is_integral_v<FromFieldType>)
{
/// cast enum/int as decimal
for (size_t i = 0; i < size; ++i)
vec_to[i] = toTiDBDecimal<FromFieldType, ToFieldType>(vec_from[i], prec, scale, context);
}
else
{
/// cast real as decimal
static_assert(std::is_floating_point_v<FromFieldType>);
for (size_t i = 0; i < size; ++i)
// Always use Float64 to avoid overflow for vec_from[i] * 10^scale.
vec_to[i] = toTiDBDecimal<Float64, ToFieldType>(static_cast<Float64>(vec_from[i]), prec, scale, context);
}
}
else
{
Expand Down
8 changes: 8 additions & 0 deletions tests/fullstack-test/expr/cast_float_as_decimal.test
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
mysql> drop table if exists test.t1;
mysql> create table test.t1(c1 float);
mysql> insert into test.t1 values(3.40282e+37);
mysql> alter table test.t1 set tiflash replica 1;
func> wait_table test t1
mysql> set @@tidb_isolation_read_engines='tiflash'; set @@tidb_enforce_mpp = 1; select cast(c1 as decimal(50, 2)) from test.t1;
cast(c1 as decimal(50, 2))
34028199169636079590747176440761942016.00