Fix integer to_char() overflow with V format
When to_char() formatted an integer value with a V pattern, it could
return an incorrect result instead of reporting an overflow. V shifts
the decimal point by multiplying the input value by a power of ten before
formatting it, so, for example,
to_char(3, '9V999999999')
requires computing 3 * 10^9. This result does not fit in int4, but
the integer variant of to_char() performed the multiplication using a
plain int32 expression. The intermediate result could therefore
overflow, causing the function to output incorrect digits instead of
raising "integer out of range".
Use dtoi4() and int4mul() for this calculation so that both an
out-of-range multiplier and an out-of-range product are detected, as
with ordinary integer arithmetic. This also matches the existing int8
implementation, which uses dtoi8() and int8mul() for the same
operation.
After this change, to_char() with V format either returns the
correctly formatted result when the scaled value fits in int4, or
raises "integer out of range" when it does not.
Backpatch to all supported versions.
Reported-by: Andrey Rachitskiy <[email protected]>
Author: Andrey Rachitskiy <[email protected]>
Reviewed-by: MiĆosz Bieniek <[email protected]>
Reviewed-by: Fujii Masao <[email protected]>
Discussion:
https://postgr.es/m/cab8bmivefqzxovdzc3kzdn++xshmkez2t7dfgbu8+oum864...@mail.gmail.com
Backpatch-through: 14
Branch
------
REL_19_STABLE
Details
-------
https://git.postgresql.org/pg/commitdiff/9efc2f9d8964ec927ccdeb4d461ff8070b0e6255
Modified Files
--------------
src/backend/utils/adt/formatting.c | 16 +++++++++-------
src/test/regress/expected/int4.out | 27 +++++++++++++++++++++++++++
src/test/regress/sql/int4.sql | 9 +++++++++
3 files changed, 45 insertions(+), 7 deletions(-)