This is an automated email from the ASF dual-hosted git repository.
zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git
The following commit(s) were added to refs/heads/main by this push:
new ceae12de fix(arrow/decimal): fail clearly for Decimal128 and
Decimal256 scales past MaxScale (#1515)
ceae12de is described below
commit ceae12debdff3322f7f856cfdbdddbf67dfc5621
Author: Harrison Crosse <[email protected]>
AuthorDate: Wed Nov 11 16:22:33 2026 -0500
fix(arrow/decimal): fail clearly for Decimal128 and Decimal256 scales past
MaxScale (#1515)
### Rationale for this change
`Decimal128` and `Decimal256` parsing and formatting can panic when the
absolute scale exceeds `MaxScale` (38 and 76).
### What changes are included in this PR?
`FromString` returns a scale error, preserving earlier errors. Builders,
`array.FromJSON`, `scalar.ParseScalar` and CSV reading receive it.
`Num.ToBigFloat` panics with `scale out of range`, as `Num.ToString`
does, instead of an index error.
`utils.FormatDecimalG` takes the Arrow decimal type and returns the same
scale error. Scalar string casts return it, so `String` prints `...`.
Array `ValueStr` and `GetOneForMarshal` return `<scale out of range,
cannot format Decimal128 value>` or the `Decimal256` equivalent.
### Are these changes tested?
`TestFromStringScaleOutOfRange`, `TestToBigFloatRejectsInvalidScale`,
`TestDecimalScalarStringCastUsesExactScaling`,
`TestDecimal128GetOneForMarshal` and `TestDecimal256GetOneForMarshal`
fail on main and pass with this change.
With Go 1.26.10, `go test ./arrow/...` with pinned `arrow-testing` and
`parquet-testing`, focused `-race -tags assert,test` runs, vet, lint and
the Release Audit Tool passed.
### Are there any user-facing changes?
Yes. `Decimal128` and `Decimal256` arrays print the placeholder whenever
the absolute scale exceeds `MaxScale`. Previously, they panicked at
these scales up to 1000 and printed a value above 1000. `Decimal32`,
`Decimal64`, type creation and import are unchanged. There is no public
API change.
Closes https://github.com/apache/arrow-go/issues/1507.
---
arrow/array/decimal.go | 7 +++++--
arrow/array/decimal128_test.go | 20 ++++++++++++++++++++
arrow/array/decimal256_test.go | 10 ++++++++++
arrow/decimal128/decimal128.go | 9 +++++++++
arrow/decimal128/decimal128_test.go | 31 +++++++++++++++++++++++++++++++
arrow/decimal256/decimal256.go | 9 +++++++++
arrow/decimal256/decimal256_test.go | 31 +++++++++++++++++++++++++++++++
arrow/scalar/decimal.go | 6 +++++-
arrow/scalar/scalar.go | 14 +++++++++++---
arrow/scalar/scalar_test.go | 9 +++++++++
internal/utils/decimal_format.go | 32 +++++++++++++++++++++++++-------
11 files changed, 165 insertions(+), 13 deletions(-)
diff --git a/arrow/array/decimal.go b/arrow/array/decimal.go
index 86d2792e..8eed1606 100644
--- a/arrow/array/decimal.go
+++ b/arrow/array/decimal.go
@@ -96,8 +96,11 @@ func (a *baseDecimal[T]) GetOneForMarshal(i int) any {
}
typ := a.DataType().(arrow.DecimalType)
- n, scale := a.Value(i), typ.GetScale()
- return utils.FormatDecimalG(n, typ.GetPrecision(), scale)
+ s, err := utils.FormatDecimalG(a.Value(i), typ)
+ if err != nil {
+ return fmt.Sprintf("<scale out of range, cannot format
Decimal%d value>", typ.BitWidth())
+ }
+ return s
}
func (a *baseDecimal[T]) ValueAsAny(i int) any {
diff --git a/arrow/array/decimal128_test.go b/arrow/array/decimal128_test.go
index 6c917467..7d270987 100644
--- a/arrow/array/decimal128_test.go
+++ b/arrow/array/decimal128_test.go
@@ -281,6 +281,26 @@ func TestDecimal128GetOneForMarshal(t *testing.T) {
for i := range cases {
assert.Equalf(t, cases[i].want, arr.GetOneForMarshal(i),
"unexpected value at index %d", i)
}
+
+ for _, tc := range []struct {
+ scale int32
+ want string
+ }{
+ {-38, "1.2345e+42"},
+ {39, "<scale out of range, cannot format Decimal128 value>"},
+ {-39, "<scale out of range, cannot format Decimal128 value>"},
+ {1001, "<scale out of range, cannot format Decimal128 value>"},
+ } {
+ past := array.NewDecimal128Builder(mem,
&arrow.Decimal128Type{Precision: 38, Scale: tc.scale})
+ past.Append(decimal128.FromI64(12345))
+ pastArr := past.NewDecimal128Array()
+ assert.Equal(t, tc.want, pastArr.GetOneForMarshal(0), "scale
%d", tc.scale)
+ if tc.scale == 39 {
+ assert.Equal(t, tc.want, pastArr.ValueStr(0), "ValueStr
at scale %d", tc.scale)
+ }
+ pastArr.Release()
+ past.Release()
+ }
}
// TestDecimal128StringScaled is a regression test for apache/arrow-go#848:
diff --git a/arrow/array/decimal256_test.go b/arrow/array/decimal256_test.go
index c1da4f24..c8ac643b 100644
--- a/arrow/array/decimal256_test.go
+++ b/arrow/array/decimal256_test.go
@@ -290,4 +290,14 @@ func TestDecimal256GetOneForMarshal(t *testing.T) {
for i := range cases {
assert.Equalf(t, cases[i].want, arr.GetOneForMarshal(i),
"unexpected value at index %d", i)
}
+
+ const placeholder = "<scale out of range, cannot format Decimal256
value>"
+ for _, scale := range []int32{77, -77} {
+ past := array.NewDecimal256Builder(mem,
&arrow.Decimal256Type{Precision: 76, Scale: scale})
+ past.Append(decimal256.FromI64(12345))
+ pastArr := past.NewDecimal256Array()
+ assert.Equal(t, placeholder, pastArr.GetOneForMarshal(0),
"scale %d", scale)
+ pastArr.Release()
+ past.Release()
+ }
}
diff --git a/arrow/decimal128/decimal128.go b/arrow/decimal128/decimal128.go
index 41c59313..940a841e 100644
--- a/arrow/decimal128/decimal128.go
+++ b/arrow/decimal128/decimal128.go
@@ -284,11 +284,17 @@ func FromString(v string, prec, scale int32) (n Num, err
error) {
if out.MantExp(nil) > 127 {
return Num{}, errors.New("bitlen too large for
decimal128")
}
+ if scale < -MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for
decimal128, must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
var tmp big.Int
val, _ := out.Int(&tmp)
n = FromBigInt(val)
n, _ = n.Div(scaleMultipliers[-scale])
} else {
+ if scale > MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for
decimal128, must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
// Since we're going to truncate this to get an integer, we
need to round
// the value instead because of edge cases so that we match how
other implementations
// (e.g. C++) handles Decimal values. So if we're negative
we'll subtract 0.5 and if
@@ -353,6 +359,9 @@ func (n Num) ToFloat64(scale int32) float64 {
}
func (n Num) ToBigFloat(scale int32) *big.Float {
+ if scale < -MaxScale || scale > MaxScale {
+ panic("arrow/decimal128: scale out of range")
+ }
f := (&big.Float{}).SetInt(n.BigInt())
if scale < 0 {
f.SetPrec(128).Mul(f,
(&big.Float{}).SetInt(scaleMultipliers[-scale].BigInt()))
diff --git a/arrow/decimal128/decimal128_test.go
b/arrow/decimal128/decimal128_test.go
index 781fb9cf..6a829095 100644
--- a/arrow/decimal128/decimal128_test.go
+++ b/arrow/decimal128/decimal128_test.go
@@ -824,3 +824,34 @@ func TestToStringRejectsInvalidScale(t *testing.T) {
assert.Panics(t, func() { decimal128.FromI64(1).ToString(scale)
})
}
}
+
+func TestToBigFloatRejectsInvalidScale(t *testing.T) {
+ for _, scale := range []int32{39, -39, math.MinInt32} {
+ assert.PanicsWithValue(t, "arrow/decimal128: scale out of
range", func() { decimal128.FromI64(12345).ToBigFloat(scale) }, "scale %d",
scale)
+ }
+}
+
+func TestFromStringScaleOutOfRange(t *testing.T) {
+ for _, tc := range []struct {
+ s string
+ scale int32
+ want string
+ }{
+ {"1e-39", 39, "scale 39 out of range for decimal128, must be
between -38 and 38"},
+ {"1", -39, "scale -39 out of range for decimal128, must be
between -38 and 38"},
+ {"1", math.MinInt32, "scale -2147483648 out of range for
decimal128, must be between -38 and 38"},
+ } {
+ _, err := decimal128.FromString(tc.s, 38, tc.scale)
+ assert.EqualError(t, err, tc.want, "%s at scale %d", tc.s,
tc.scale)
+ }
+
+ n, err := decimal128.FromString("1e38", 38, -38)
+ require.NoError(t, err)
+ assert.Equal(t, decimal128.FromI64(1), n)
+
+ // Errors found before the scale is used take precedence.
+ _, err = decimal128.FromString("1e40", 38, -39)
+ assert.EqualError(t, err, "bitlen too large for decimal128")
+ _, err = decimal128.FromString("Inf", 38, 39)
+ assert.EqualError(t, err, "cannot convert Inf to decimal128")
+}
diff --git a/arrow/decimal256/decimal256.go b/arrow/decimal256/decimal256.go
index 9bf4c16f..314c9c0d 100644
--- a/arrow/decimal256/decimal256.go
+++ b/arrow/decimal256/decimal256.go
@@ -164,12 +164,18 @@ func FromString(v string, prec, scale int32) (n Num, err
error) {
if out.MantExp(nil) > 255 {
return Num{}, errors.New("bitlen too large for
decimal256")
}
+ if scale < -MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for
decimal256, must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
var tmp big.Int
val, _ := out.Int(&tmp)
n = FromBigInt(val)
n, _ = n.Div(scaleMultipliers[-scale])
} else {
+ if scale > MaxScale {
+ return Num{}, fmt.Errorf("scale %d out of range for
decimal256, must be between %d and %d", scale, -MaxScale, MaxScale)
+ }
out.Mul(out,
(&big.Float{}).SetInt(scaleMultipliers[scale].BigInt())).SetPrec(precInBits)
// Reject before rounding and converting, which would allocate
as many
// bits as the value has.
@@ -357,6 +363,9 @@ func (n Num) ToFloat64(scale int32) float64 {
}
func (n Num) ToBigFloat(scale int32) *big.Float {
+ if scale < -MaxScale || scale > MaxScale {
+ panic("arrow/decimal256: scale out of range")
+ }
f := (&big.Float{}).SetInt(n.BigInt())
if scale < 0 {
f.SetPrec(256).Mul(f,
(&big.Float{}).SetInt(scaleMultipliers[-scale].BigInt()))
diff --git a/arrow/decimal256/decimal256_test.go
b/arrow/decimal256/decimal256_test.go
index 68f9a7f5..3cb763f5 100644
--- a/arrow/decimal256/decimal256_test.go
+++ b/arrow/decimal256/decimal256_test.go
@@ -704,6 +704,37 @@ func TestToStringRejectsInvalidScale(t *testing.T) {
}
}
+func TestToBigFloatRejectsInvalidScale(t *testing.T) {
+ for _, scale := range []int32{77, -77, math.MinInt32} {
+ assert.PanicsWithValue(t, "arrow/decimal256: scale out of
range", func() { decimal256.FromI64(12345).ToBigFloat(scale) }, "scale %d",
scale)
+ }
+}
+
+func TestFromStringScaleOutOfRange(t *testing.T) {
+ for _, tc := range []struct {
+ s string
+ scale int32
+ want string
+ }{
+ {"1e-77", 77, "scale 77 out of range for decimal256, must be
between -76 and 76"},
+ {"1", -77, "scale -77 out of range for decimal256, must be
between -76 and 76"},
+ {"1", math.MinInt32, "scale -2147483648 out of range for
decimal256, must be between -76 and 76"},
+ } {
+ _, err := decimal256.FromString(tc.s, 76, tc.scale)
+ assert.EqualError(t, err, tc.want, "%s at scale %d", tc.s,
tc.scale)
+ }
+
+ n, err := decimal256.FromString("1e76", 76, -76)
+ require.NoError(t, err)
+ assert.Equal(t, decimal256.FromI64(1), n)
+
+ // Errors found before the scale is used take precedence.
+ _, err = decimal256.FromString("1e78", 76, -77)
+ assert.EqualError(t, err, "bitlen too large for decimal256")
+ _, err = decimal256.FromString("Inf", 76, 77)
+ assert.EqualError(t, err, "cannot convert Inf to decimal256")
+}
+
// Test issues from GH-38395
func TestHexFromString(t *testing.T) {
const decStr =
"11111111111111111111111111111111111111.00000000000000000000000000000000000000"
diff --git a/arrow/scalar/decimal.go b/arrow/scalar/decimal.go
index 89a264c2..7d478871 100644
--- a/arrow/scalar/decimal.go
+++ b/arrow/scalar/decimal.go
@@ -78,7 +78,11 @@ func (s *decimalScalar[T]) CastTo(to arrow.DataType)
(Scalar, error) {
dt := s.Type.(arrow.DecimalType)
if to.ID() == arrow.STRING {
- return NewStringScalar(utils.FormatDecimalG(s.Value,
dt.GetPrecision(), dt.GetScale())), nil
+ str, err := utils.FormatDecimalG(s.Value, dt)
+ if err != nil {
+ return nil, err
+ }
+ return NewStringScalar(str), nil
}
toDec, ok := to.(arrow.DecimalType)
diff --git a/arrow/scalar/scalar.go b/arrow/scalar/scalar.go
index 1f1129fe..94386022 100644
--- a/arrow/scalar/scalar.go
+++ b/arrow/scalar/scalar.go
@@ -38,6 +38,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/float16"
"github.com/apache/arrow-go/v18/arrow/internal/debug"
"github.com/apache/arrow-go/v18/arrow/memory"
+ "github.com/apache/arrow-go/v18/internal/utils"
)
// Scalar represents a single value of a specific DataType as opposed to
@@ -328,8 +329,11 @@ func (s *Decimal128) CastTo(to arrow.DataType) (Scalar,
error) {
}
return NewDecimal256Scalar(newVal, to), nil
case arrow.STRING:
- dt := s.Type.(*arrow.Decimal128Type)
- return NewStringScalar(s.Value.ToBigFloat(dt.Scale).Text('g',
int(dt.Precision))), nil
+ str, err := utils.FormatDecimalG(s.Value, dt)
+ if err != nil {
+ return nil, err
+ }
+ return NewStringScalar(str), nil
}
return nil, fmt.Errorf("cannot cast non-nil decimal128 scalar to type
%s", to)
@@ -384,7 +388,11 @@ func (s *Decimal256) CastTo(to arrow.DataType) (Scalar,
error) {
}
return NewDecimal256Scalar(newVal, to), nil
case arrow.STRING:
- return NewStringScalar(s.Value.ToBigFloat(dt.Scale).Text('g',
int(dt.Precision))), nil
+ str, err := utils.FormatDecimalG(s.Value, dt)
+ if err != nil {
+ return nil, err
+ }
+ return NewStringScalar(str), nil
}
return nil, fmt.Errorf("cannot cast non-nil decimal256 scalar to type
%s", to)
diff --git a/arrow/scalar/scalar_test.go b/arrow/scalar/scalar_test.go
index 609f4569..70a1a859 100644
--- a/arrow/scalar/scalar_test.go
+++ b/arrow/scalar/scalar_test.go
@@ -184,6 +184,15 @@ func TestDecimalScalarStringCastUsesExactScaling(t
*testing.T) {
cast256, err := decimal256Scalar.CastTo(arrow.BinaryTypes.String)
require.NoError(t, err)
assert.Equal(t,
"-0.1234567812345678123456781234567812345678123456781234567812345678123456781234",
cast256.String())
+
+ past128 := scalar.NewDecimal128Scalar(decimal128.FromI64(12345),
&arrow.Decimal128Type{Precision: 38, Scale: 39})
+ _, err = past128.CastTo(arrow.BinaryTypes.String)
+ assert.EqualError(t, err, "scale 39 out of range for decimal128, must
be between -38 and 38", "decimal128 cast at scale 39")
+ assert.Equal(t, "...", past128.String(), "decimal128 String at scale
39")
+ past256 := scalar.NewDecimal256Scalar(decimal256.FromI64(12345),
&arrow.Decimal256Type{Precision: 76, Scale: 77})
+ _, err = past256.CastTo(arrow.BinaryTypes.String)
+ assert.EqualError(t, err, "scale 77 out of range for decimal256, must
be between -76 and 76", "decimal256 cast at scale 77")
+ assert.Equal(t, "...", past256.String(), "decimal256 String at scale
77")
}
func TestDecimal32And64Scalars(t *testing.T) {
diff --git a/internal/utils/decimal_format.go b/internal/utils/decimal_format.go
index f0dbb01f..b020b536 100644
--- a/internal/utils/decimal_format.go
+++ b/internal/utils/decimal_format.go
@@ -21,18 +21,36 @@ import (
"math/big"
"strconv"
"strings"
+
+ "github.com/apache/arrow-go/v18/arrow"
+ "github.com/apache/arrow-go/v18/arrow/decimal128"
+ "github.com/apache/arrow-go/v18/arrow/decimal256"
)
-// FormatDecimalG formats an Arrow decimal in 'g' style. At absolute scales
-// above 1000, it rounds the exact coefficient and shifts the exponent,
-// avoiding conversion work quadratic in the scale. Exact ties round to even.
-func FormatDecimalG[T interface{ ToBigFloat(int32) *big.Float }](n T,
precision, scale int32) string {
+// FormatDecimalG formats n, a value of type typ, in 'g' style. It returns an
+// error only when typ is a Decimal128 or Decimal256 type whose scale is
outside
+// [-MaxScale, MaxScale]. At absolute scales above 1000, it rounds the exact
+// coefficient and shifts the exponent, avoiding conversion work quadratic in
+// the scale. Exact ties round to even.
+func FormatDecimalG[T interface{ ToBigFloat(int32) *big.Float }](n T, typ
arrow.DecimalType) (string, error) {
+ precision, scale := typ.GetPrecision(), typ.GetScale()
+ var maxScale int32
+ switch typ.ID() {
+ case arrow.DECIMAL128:
+ maxScale = decimal128.MaxScale
+ case arrow.DECIMAL256:
+ maxScale = decimal256.MaxScale
+ }
+ if maxScale > 0 && (scale < -maxScale || scale > maxScale) {
+ return "", fmt.Errorf("scale %d out of range for decimal%d,
must be between %d and %d", scale, typ.BitWidth(), -maxScale, maxScale)
+ }
+
if scale >= -1000 && scale <= 1000 {
- return n.ToBigFloat(scale).Text('g', int(precision))
+ return n.ToBigFloat(scale).Text('g', int(precision)), nil
}
coef := n.ToBigFloat(0)
if coef.Sign() == 0 {
- return coef.Text('g', int(precision))
+ return coef.Text('g', int(precision)), nil
}
// No decimal type has more than 77 coefficient digits, and a negative
// precision keeps 'g's shortest formatting.
@@ -42,5 +60,5 @@ func FormatDecimalG[T interface{ ToBigFloat(int32) *big.Float
}](n T, precision,
}
mant, exp, _ := strings.Cut(coef.Text('e', p), "e")
e, _ := strconv.ParseInt(exp, 10, 64)
- return fmt.Sprintf("%se%+03d",
strings.TrimRight(strings.TrimRight(mant, "0"), "."), e-int64(scale))
+ return fmt.Sprintf("%se%+03d",
strings.TrimRight(strings.TrimRight(mant, "0"), "."), e-int64(scale)), nil
}