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 f0ae1c85 feat(arrow/scalar): add Decimal32 and Decimal64 scalars 
(#1501)
f0ae1c85 is described below

commit f0ae1c859d88d5c2125e7fd58c84dd6a1fb599d7
Author: Harrison Crosse <[email protected]>
AuthorDate: Tue Nov 10 14:26:33 2026 -0500

    feat(arrow/scalar): add Decimal32 and Decimal64 scalars (#1501)
    
    ### Rationale for this change
    
    `decimal32` and `decimal64` lack scalar types, so extraction, casting
    and parsing fail or panic.
    
    ### What changes are included in this PR?
    
    `Decimal32` and `Decimal64` alias one unexported generic type, as
    `array.Decimal32` does. I can switch to concrete structs, or move
    `Decimal128` and `Decimal256` onto it in a separate PR that keeps their
    casts.
    
    `CastTo` supports string and equal or wider decimals. Like `Decimal128`
    and `Decimal256`, `Validate` doesn't check precision.
    
    The new scalars expose four bugs. `Decimal32FromString` and
    `Decimal64FromString` reject malformed text, infinities and values that
    don't fit, instead of panicking or wrapping. `ToBigFloat` preserves
    signs beyond scale ±18. `decimal256.Rescale` returns errors instead of
    panicking. Parsing and `ToBigFloat` bugs affect array output, `FromJSON`
    and builders on main.
    
    `MakeScalarParam` now returns decimal scalars for these types, not
    `Uint32` or `String`, and rejects mismatched decimal values.
    
    ### Are these changes tested?
    
    `TestFromString`, `TestDecimalToReal` and `TestRescale` fail or panic on
    main. `TestDecimal32And64Scalars` covers the issue's cases.
    
    `go test ./arrow/...`, `-race -tags assert,test` runs, lint and the
    Release Audit Tool passed.
    
    ### Are there any user-facing changes?
    
    Yes. New types and constructors: `Decimal32`, `Decimal64`,
    `NewDecimal32Scalar`, `NewDecimal64Scalar`.
    
    Closes https://github.com/apache/arrow-go/issues/1497.
---
 arrow/array/decimal.go              |   3 +-
 arrow/compute/scalar_nested.go      |   6 +-
 arrow/compute/scalar_nested_test.go | 117 +++++------------------------------
 arrow/decimal/decimal.go            |  74 ++++++++++++++++------
 arrow/decimal/decimal_test.go       |  69 ++++++++++++++++++++-
 arrow/decimal256/decimal256.go      |  26 +++++---
 arrow/decimal256/decimal256_test.go |  31 ++++++++++
 arrow/scalar/append.go              |   4 ++
 arrow/scalar/decimal.go             | 119 ++++++++++++++++++++++++++++++++++++
 arrow/scalar/parse.go               |  29 +++++++++
 arrow/scalar/scalar.go              |   6 ++
 arrow/scalar/scalar_test.go         | 104 +++++++++++++++++++++++++++++++
 internal/utils/decimal_format.go    |  46 ++++++++++++++
 13 files changed, 495 insertions(+), 139 deletions(-)

diff --git a/arrow/array/decimal.go b/arrow/array/decimal.go
index 92d049f4..86d2792e 100644
--- a/arrow/array/decimal.go
+++ b/arrow/array/decimal.go
@@ -28,6 +28,7 @@ import (
        "github.com/apache/arrow-go/v18/arrow/internal/debug"
        "github.com/apache/arrow-go/v18/arrow/memory"
        "github.com/apache/arrow-go/v18/internal/json"
+       "github.com/apache/arrow-go/v18/internal/utils"
 )
 
 type baseDecimal[T interface {
@@ -96,7 +97,7 @@ func (a *baseDecimal[T]) GetOneForMarshal(i int) any {
 
        typ := a.DataType().(arrow.DecimalType)
        n, scale := a.Value(i), typ.GetScale()
-       return n.ToBigFloat(scale).Text('g', int(typ.GetPrecision()))
+       return utils.FormatDecimalG(n, typ.GetPrecision(), scale)
 }
 
 func (a *baseDecimal[T]) ValueAsAny(i int) any {
diff --git a/arrow/compute/scalar_nested.go b/arrow/compute/scalar_nested.go
index 23d1c56d..31dfa80f 100644
--- a/arrow/compute/scalar_nested.go
+++ b/arrow/compute/scalar_nested.go
@@ -94,8 +94,7 @@ type listElementFunction struct {
 
 func listElementScalarResultSupported(typ arrow.DataType, nullResult bool) 
bool {
        switch typ.ID() {
-       case arrow.BINARY_VIEW, arrow.STRING_VIEW, arrow.LIST_VIEW, 
arrow.LARGE_LIST_VIEW,
-               arrow.DECIMAL32, arrow.DECIMAL64:
+       case arrow.BINARY_VIEW, arrow.STRING_VIEW, arrow.LIST_VIEW, 
arrow.LARGE_LIST_VIEW:
                return false
        case arrow.EXTENSION:
                return 
listElementScalarResultSupported(typ.(arrow.ExtensionType).StorageType(), 
nullResult)
@@ -132,8 +131,7 @@ func listElementScalarArrayValueSupported(values 
arrow.Array, index int) bool {
        }
 
        switch values := values.(type) {
-       case *array.BinaryView, *array.StringView, *array.ListView, 
*array.LargeListView,
-               *array.Decimal32, *array.Decimal64:
+       case *array.BinaryView, *array.StringView, *array.ListView, 
*array.LargeListView:
                return false
        case array.ExtensionArray:
                return listElementScalarArrayValueSupported(values.Storage(), 
index)
diff --git a/arrow/compute/scalar_nested_test.go 
b/arrow/compute/scalar_nested_test.go
index 4030c188..7dc66f3c 100644
--- a/arrow/compute/scalar_nested_test.go
+++ b/arrow/compute/scalar_nested_test.go
@@ -900,24 +900,29 @@ func TestListElementDecimalArrayChildren(t *testing.T) {
        mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
        defer mem.AssertSize(t, 0)
 
+       decimal32Type := &arrow.Decimal32Type{Precision: 6, Scale: 2}
+       decimal64Type := &arrow.Decimal64Type{Precision: 12, Scale: 2}
        tests := []struct {
                name string
                typ  arrow.DataType
                add  func(array.Builder, int32)
+               want scalar.Scalar
        }{
                {
                        name: "decimal32",
-                       typ:  &arrow.Decimal32Type{Precision: 6, Scale: 2},
+                       typ:  decimal32Type,
                        add: func(builder array.Builder, value int32) {
                                
builder.(*array.Decimal32Builder).Append(decimal.Decimal32(value))
                        },
+                       want: scalar.NewDecimal32Scalar(4, decimal32Type),
                },
                {
                        name: "decimal64",
-                       typ:  &arrow.Decimal64Type{Precision: 12, Scale: 2},
+                       typ:  decimal64Type,
                        add: func(builder array.Builder, value int32) {
                                
builder.(*array.Decimal64Builder).Append(decimal.Decimal64(value))
                        },
+                       want: scalar.NewDecimal64Scalar(4, decimal64Type),
                },
        }
 
@@ -954,48 +959,17 @@ func TestListElementDecimalArrayChildren(t *testing.T) {
                        defer actual.Release()
                        require.NoError(t, array.ValidateFull(actual))
                        assert.True(t, array.Equal(expected, actual), 
"expected: %s\ngot: %s", expected, actual)
-               })
-       }
-}
-
-func TestListElementScalarListWithUnsupportedDecimalValues(t *testing.T) {
-       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
-       defer mem.AssertSize(t, 0)
-
-       tests := []struct {
-               name string
-               typ  arrow.DataType
-       }{
-               {name: "decimal32", typ: &arrow.Decimal32Type{Precision: 6, 
Scale: 2}},
-               {name: "decimal64", typ: &arrow.Decimal64Type{Precision: 12, 
Scale: 2}},
-       }
-
-       for _, tc := range tests {
-               t.Run(tc.name, func(t *testing.T) {
-                       builder := array.NewBuilder(mem, tc.typ)
-                       switch b := builder.(type) {
-                       case *array.Decimal32Builder:
-                               b.Append(decimal.Decimal32(123))
-                       case *array.Decimal64Builder:
-                               b.Append(decimal.Decimal64(123))
-                       default:
-                               t.Fatalf("unexpected builder type %T", builder)
-                       }
-                       values := builder.NewArray()
-                       builder.Release()
-                       defer values.Release()
 
-                       list := scalar.NewListScalar(values)
+                       list := scalar.NewListScalar(expected)
                        defer list.Release()
-                       result, err := compute.ListElement(
+                       scalarResult, err := compute.ListElement(
                                context.Background(),
                                &compute.ScalarDatum{Value: list},
-                               &compute.ScalarDatum{Value: 
scalar.NewInt64Scalar(0)},
+                               &compute.ScalarDatum{Value: 
scalar.NewInt64Scalar(1)},
                        )
-                       if err == nil && result != nil {
-                               result.Release()
-                       }
-                       require.ErrorIs(t, err, arrow.ErrNotImplemented)
+                       require.NoError(t, err)
+                       defer scalarResult.Release()
+                       assert.True(t, scalar.Equals(tc.want, 
scalarResult.(*compute.ScalarDatum).Value))
                })
        }
 }
@@ -1549,59 +1523,6 @@ func 
TestListElementDenseUnionScalarWithActiveUnsupportedChild(t *testing.T) {
        require.ErrorIs(t, err, arrow.ErrNotImplemented)
 }
 
-func TestListElementDenseUnionScalarWithActiveUnsupportedDecimalChild(t 
*testing.T) {
-       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
-       defer mem.AssertSize(t, 0)
-
-       for _, tc := range []struct {
-               name string
-               typ  arrow.DataType
-               add  func(array.Builder)
-       }{
-               {
-                       name: "decimal32",
-                       typ:  &arrow.Decimal32Type{Precision: 6, Scale: 2},
-                       add: func(builder array.Builder) {
-                               
builder.(*array.Decimal32Builder).Append(decimal.Decimal32(123))
-                       },
-               },
-               {
-                       name: "decimal64",
-                       typ:  &arrow.Decimal64Type{Precision: 12, Scale: 2},
-                       add: func(builder array.Builder) {
-                               
builder.(*array.Decimal64Builder).Append(decimal.Decimal64(123))
-                       },
-               },
-       } {
-               t.Run(tc.name, func(t *testing.T) {
-                       unionType := arrow.DenseUnionOf(
-                               []arrow.Field{{Name: "value", Type: tc.typ, 
Nullable: true}},
-                               []arrow.UnionTypeCode{0},
-                       )
-                       builder := array.NewListBuilder(mem, unionType)
-                       values := 
builder.ValueBuilder().(*array.DenseUnionBuilder)
-                       builder.Append(true)
-                       values.Append(0)
-                       tc.add(values.Child(0))
-                       input := builder.NewArray()
-                       builder.Release()
-                       defer input.Release()
-
-                       listValue := 
scalar.NewListScalar(input.(*array.List).ListValues())
-                       defer listValue.Release()
-                       result, err := compute.ListElement(
-                               context.Background(),
-                               &compute.ScalarDatum{Value: listValue},
-                               &compute.ScalarDatum{Value: 
scalar.NewInt64Scalar(0)},
-                       )
-                       if err == nil && result != nil {
-                               result.Release()
-                       }
-                       require.ErrorIs(t, err, arrow.ErrNotImplemented)
-               })
-       }
-}
-
 func TestListElementDenseUnionScalarWithActiveNullUnsupportedChild(t 
*testing.T) {
        mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
        defer mem.AssertSize(t, 0)
@@ -1618,14 +1539,6 @@ func 
TestListElementDenseUnionScalarWithActiveNullUnsupportedChild(t *testing.T)
                        name: "string_view",
                        typ:  arrow.BinaryTypes.StringView,
                },
-               {
-                       name: "decimal32",
-                       typ:  &arrow.Decimal32Type{Precision: 6, Scale: 2},
-               },
-               {
-                       name: "decimal64",
-                       typ:  &arrow.Decimal64Type{Precision: 12, Scale: 2},
-               },
                {
                        name: "list_view",
                        typ:  arrow.ListViewOf(arrow.PrimitiveTypes.Int32),
@@ -2237,8 +2150,6 @@ func TestListElementValidatesScalarIndexForEmptyInputs(t 
*testing.T) {
 
 func TestListElementNullScalarDenseUnionChildren(t *testing.T) {
        for _, unsupported := range []arrow.DataType{
-               &arrow.Decimal32Type{Precision: 6, Scale: 2},
-               &arrow.Decimal64Type{Precision: 12, Scale: 2},
                arrow.ListViewOf(arrow.PrimitiveTypes.Int32),
                arrow.LargeListViewOf(arrow.PrimitiveTypes.Int32),
        } {
@@ -2366,7 +2277,7 @@ func TestListElementNullStructScalarWithDenseUnionChild(t 
*testing.T) {
                        mem := 
memory.NewCheckedAllocator(memory.DefaultAllocator)
                        defer mem.AssertSize(t, 0)
                        fields := []arrow.Field{
-                               {Name: "unsupported", Type: 
&arrow.Decimal32Type{Precision: 6, Scale: 2}, Nullable: true},
+                               {Name: "unsupported", Type: 
arrow.ListViewOf(arrow.PrimitiveTypes.Int32), Nullable: true},
                                {Name: "number", Type: 
arrow.PrimitiveTypes.Int32, Nullable: true},
                        }
                        childID := 1
diff --git a/arrow/decimal/decimal.go b/arrow/decimal/decimal.go
index 4d6563cc..f62ea5a9 100644
--- a/arrow/decimal/decimal.go
+++ b/arrow/decimal/decimal.go
@@ -182,6 +182,12 @@ func decimalFromString[T interface {
 
        var out *big.Float
        out, _, err = big.ParseFloat(v, 10, nbits, big.ToNearestEven)
+       if err != nil {
+               return
+       }
+       if out.IsInf() {
+               return n, fmt.Errorf("cannot convert %s to decimal%d", v, nbits)
+       }
 
        if scale < 0 {
                var tmp big.Int
@@ -190,12 +196,21 @@ func decimalFromString[T interface {
                        return n, fmt.Errorf("bitlen too large for decimal%d", 
nbits)
                }
 
-               n = T(val.Int64() / int64(math.Pow10(int(-scale))))
+               // |val| < 2^64 < 10^20, so a larger divisor gives the same 
quotient.
+               div := new(big.Int).Exp(big.NewInt(10), 
big.NewInt(min(-int64(scale), 20)), nil)
+               n = T(val.Quo(val, div).Int64())
        } else {
-               var precInBits = 
uint(math.Round(float64(prec+scale+1)/math.Log10(2))) + 1
-
-               p := 
(&big.Float{}).SetInt(big.NewInt(int64(math.Pow10(int(scale)))))
-               out.SetPrec(precInBits).Mul(out, p)
+               // Clamp before converting, since converting an out of range 
float to
+               // uint is implementation specific. SetPrec caps at big.MaxPrec 
anyway.
+               bitsNeeded := math.Round(float64(int64(prec)+int64(scale)+1) / 
math.Log10(2))
+               var precInBits = uint(min(max(bitsNeeded, 0), big.MaxPrec-1)) + 
1
+
+               mulPow10(out.SetPrec(precInBits), int64(scale))
+               // Reject before rounding and converting, which would allocate 
as many
+               // bits as the value has.
+               if out.IsInf() || out.MantExp(nil) > int(nbits) {
+                       return n, fmt.Errorf("bitlen too large for decimal%d", 
nbits)
+               }
                if out.Signbit() {
                        out.Sub(out, pt5)
                } else {
@@ -204,7 +219,9 @@ func decimalFromString[T interface {
 
                var tmp big.Int
                val, _ := out.Int(&tmp)
-               if val.BitLen() > int(nbits) {
+               // This also rejects the signed minimum, which fits the storage 
but has
+               // more digits than the maximum precision allows.
+               if val.BitLen() >= int(nbits) {
                        return n, fmt.Errorf("bitlen too large for decimal%d", 
nbits)
                }
                n = T(val.Int64())
@@ -307,23 +324,42 @@ func (n Decimal64) ToFloat64(scale int32) float64 {
 }
 
 func (n Decimal32) ToBigFloat(scale int32) *big.Float {
-       f := (&big.Float{}).SetInt64(int64(n))
-       if scale < 0 {
-               f.SetPrec(32).Mul(f, (&big.Float{}).SetInt64(intPow(10, 
-int64(scale))))
-       } else {
-               f.SetPrec(32).Quo(f, (&big.Float{}).SetInt64(intPow(10, 
int64(scale))))
-       }
-       return f
+       return mulPow10(new(big.Float).SetInt64(int64(n)).SetPrec(32), 
-int64(scale))
 }
 
 func (n Decimal64) ToBigFloat(scale int32) *big.Float {
-       f := (&big.Float{}).SetInt64(int64(n))
-       if scale < 0 {
-               f.SetPrec(64).Mul(f, (&big.Float{}).SetInt64(intPow(10, 
-int64(scale))))
-       } else {
-               f.SetPrec(64).Quo(f, (&big.Float{}).SetInt64(intPow(10, 
int64(scale))))
+       return mulPow10(new(big.Float).SetInt64(int64(n)).SetPrec(64), 
-int64(scale))
+}
+
+// mulPow10 sets f to f * 10^exp, rounded to f's precision, and returns f. For
+// precisions up to 64 bits the result is within one unit in the last place.
+// 10^exp is applied as an exact 2^exp and then 5^|exp|, computed at 128 bits
+// by repeated squaring so the work stays bounded. Splitting the power keeps it
+// from overflowing before the result does. A result outside big.Float's
+// exponent range becomes ±Inf or 0.
+func mulPow10(f *big.Float, exp int64) *big.Float {
+       if f.Sign() == 0 {
+               // 5^|exp| may overflow to infinity, and 0 * Inf panics.
+               return f
+       }
+
+       k := exp
+       if k < 0 {
+               k = -k
+       }
+       pow := new(big.Float).SetPrec(128).SetInt64(1)
+       for base := new(big.Float).SetPrec(128).SetInt64(5); k > 0; k >>= 1 {
+               if k&1 == 1 {
+                       pow.Mul(pow, base)
+               }
+               base.Mul(base, base)
+       }
+
+       f.SetMantExp(f, int(exp))
+       if exp < 0 {
+               return f.Quo(f, pow)
        }
-       return f
+       return f.Mul(f, pow)
 }
 
 func cmpDec[T Decimal32 | Decimal64](lhs, rhs T) int {
diff --git a/arrow/decimal/decimal_test.go b/arrow/decimal/decimal_test.go
index 55635762..8793d4fc 100644
--- a/arrow/decimal/decimal_test.go
+++ b/arrow/decimal/decimal_test.go
@@ -158,17 +158,26 @@ func TestDecimalToReal(t *testing.T) {
                        // exact comparisons would succeed on most platforms, 
but not all power-of-ten
                        // factors are exactly representable in binary floating 
point, so we'll use
                        // approx and ensure that the values are within 4 ULP 
(unit of least precision)
-                       for scale := int32(-9); scale <= 9; scale++ {
+                       for scale := int32(-19); scale <= 19; scale++ {
                                checkApproxDecimaltoFloat("1", 
math.Pow10(-int(scale)), scale)
                                checkApproxDecimaltoFloat("123", 
float64(123)*math.Pow10(-int(scale)), scale)
                        }
 
-                       for scale := int32(-18); scale <= 18; scale++ {
+                       for scale := int32(-19); scale <= 19; scale++ {
                                checkApproxDecimal64toFloat("1", 
math.Pow10(-int(scale)), scale)
                                checkApproxDecimal64toFloat("123", 
float64(123)*math.Pow10(-int(scale)), scale)
                        }
                })
        })
+
+       assert.Zero(t, decimal.Decimal32(0).ToBigFloat(math.MinInt32).Sign())
+       assert.Zero(t, decimal.Decimal64(0).ToBigFloat(math.MinInt32).Sign())
+       // 10^646456993 overflows big.Float, but 10^-646456993 doesn't.
+       assert.Equal(t, 1, decimal.Decimal32(1).ToBigFloat(646456993).Sign())
+       assert.Equal(t, 1, decimal.Decimal64(1).ToBigFloat(646456993).Sign())
+       // 10^28 is not exactly representable with 64 bits of precision.
+       want := 
new(big.Float).SetPrec(64).SetRat(new(big.Rat).SetFrac(big.NewInt(3), 
new(big.Int).Exp(big.NewInt(10), big.NewInt(28), nil)))
+       assert.Zero(t, want.Cmp(decimal.Decimal64(3).ToBigFloat(28)))
 }
 
 func TestDecimalFromFloat(t *testing.T) {
@@ -308,6 +317,62 @@ func TestFromString(t *testing.T) {
                        assert.Equal(t, ex64, n64)
                })
        }
+
+       for _, s := range []string{"abc", "Inf", "-inf"} {
+               _, err := decimal.Decimal32FromString(s, 8, 2)
+               assert.Error(t, err, s)
+               _, err = decimal.Decimal64FromString(s, 8, 2)
+               assert.Error(t, err, s)
+       }
+
+       for _, s := range []string{"2147483648", "4294967295"} {
+               _, err := decimal.Decimal32FromString(s, 9, 0)
+               assert.Error(t, err, s)
+       }
+       _, err := decimal.Decimal64FromString("9223372036854775808", 18, 0)
+       assert.Error(t, err)
+
+       for _, tc := range []struct {
+               s     string
+               scale int32
+               want  decimal.Decimal64
+       }{
+               {"9223372036854775808", -1, 922337203685477580},
+               {"10000000000000000000", -19, 1},
+               {"18000000000000000000", -20, 0},
+               {"1", math.MinInt32, 0},
+       } {
+               n64, err := decimal.Decimal64FromString(tc.s, 18, tc.scale)
+               require.NoError(t, err, tc.s)
+               assert.Equal(t, tc.want, n64, tc.s)
+       }
+
+       for _, tc := range []struct {
+               s           string
+               prec, scale int32
+               want        int64
+               wantErr     bool
+       }{
+               {"1e-18", 9, 19, 10, false},
+               {"1e-18", 9, 20, 100, false},
+               {"-1e-76", 1, 76, -1, false},
+               {"3000000000", 9, -2, 30000000, false},
+               {"1e-18", 1, 20, 0, true},
+               {"1", 9, 100000000, 0, true},
+               {"1", 9, math.MaxInt32, 0, true},
+       } {
+               n32, err := decimal.Decimal32FromString(tc.s, tc.prec, tc.scale)
+               n64, err64 := decimal.Decimal64FromString(tc.s, tc.prec, 
tc.scale)
+               if tc.wantErr {
+                       assert.Error(t, err, tc.s)
+                       assert.Error(t, err64, tc.s)
+                       continue
+               }
+               require.NoError(t, err, tc.s)
+               require.NoError(t, err64, tc.s)
+               assert.Equal(t, decimal.Decimal32(tc.want), n32, tc.s)
+               assert.Equal(t, decimal.Decimal64(tc.want), n64, tc.s)
+       }
 }
 
 func TestCmp(t *testing.T) {
diff --git a/arrow/decimal256/decimal256.go b/arrow/decimal256/decimal256.go
index 0b45d2e7..cbc28c8d 100644
--- a/arrow/decimal256/decimal256.go
+++ b/arrow/decimal256/decimal256.go
@@ -495,29 +495,35 @@ func (n Num) ReduceScaleBy(reduce int32, round bool) Num {
        return FromBigInt(result)
 }
 
-func (n Num) rescaleWouldCauseDataLoss(deltaScale int32, multiplier Num) (out 
Num, loss bool) {
+func (n Num) rescaleWouldCauseDataLoss(deltaScale int64, multiplier Num) (out 
Num, loss bool) {
        if deltaScale < 0 {
                var remainder Num
                out, remainder = n.Div(multiplier)
                return out, remainder != Num{}
        }
 
-       out = n.Mul(multiplier)
-       if n.Sign() < 0 {
-               loss = n.Less(out)
-       } else {
-               loss = out.Less(n)
+       result := n.BigInt()
+       result.Mul(result, multiplier.BigInt())
+       if result.BitLen() > 255 {
+               return Num{}, true
        }
-       return
+       return FromBigInt(result), false
 }
 
 func (n Num) Rescale(original, newscale int32) (out Num, err error) {
-       if original == newscale {
+       if original == newscale || n == (Num{}) {
                return n, nil
        }
 
-       deltaScale := newscale - original
-       absDeltaScale := int32(math.Abs(float64(deltaScale)))
+       deltaScale := int64(newscale) - int64(original)
+       absDeltaScale := deltaScale
+       if absDeltaScale < 0 {
+               absDeltaScale = -absDeltaScale
+       }
+       // Scaling any nonzero value by 10^77 or more overflows or drops every 
digit.
+       if absDeltaScale >= int64(len(scaleMultipliers)) {
+               return Num{}, errors.New("rescale data loss")
+       }
 
        multiplier := scaleMultipliers[absDeltaScale]
        var wouldHaveLoss bool
diff --git a/arrow/decimal256/decimal256_test.go 
b/arrow/decimal256/decimal256_test.go
index 5112cb4a..2143ff58 100644
--- a/arrow/decimal256/decimal256_test.go
+++ b/arrow/decimal256/decimal256_test.go
@@ -235,6 +235,37 @@ func TestDiv(t *testing.T) {
        }
 }
 
+func TestRescale(t *testing.T) {
+       fiveE76 := decimal256.FromBigInt(new(big.Int).Mul(big.NewInt(5), 
new(big.Int).Exp(big.NewInt(10), big.NewInt(76), nil)))
+       for _, tc := range []struct {
+               n                  int64
+               original, newScale int32
+               want               decimal256.Num
+               wantErr            bool
+       }{
+               {111, 0, 2, decimal256.FromI64(11100), false},
+               {-11100, 2, 0, decimal256.FromI64(-111), false},
+               {555, 2, 1, decimal256.Num{}, true},
+               {5, 0, 76, fiveE76, false},
+               {-6, 0, 76, decimal256.Num{}, true},
+               {0, -9, 76, decimal256.Num{}, false},
+               {0, 76, -9, decimal256.Num{}, false},
+               {12, 0, 77, decimal256.Num{}, true},
+               {-12, 77, 0, decimal256.Num{}, true},
+               {10, math.MinInt32, math.MaxInt32, decimal256.Num{}, true},
+       } {
+               t.Run(fmt.Sprintf("%d_%d_%d", tc.n, tc.original, tc.newScale), 
func(t *testing.T) {
+                       got, err := 
decimal256.FromI64(tc.n).Rescale(tc.original, tc.newScale)
+                       if tc.wantErr {
+                               assert.EqualError(t, err, "rescale data loss")
+                               return
+                       }
+                       require.NoError(t, err)
+                       assert.Equal(t, tc.want, got)
+               })
+       }
+}
+
 func TestPow(t *testing.T) {
        for _, tc := range []struct {
                n    decimal256.Num
diff --git a/arrow/scalar/append.go b/arrow/scalar/append.go
index 737e800d..296bffac 100644
--- a/arrow/scalar/append.go
+++ b/arrow/scalar/append.go
@@ -98,6 +98,10 @@ func appendToBldr(bldr array.Builder, scalars []Scalar) 
error {
                return appendToBldr(bldr.StorageBuilder(), baseScalars)
        case *array.BooleanBuilder:
                appendPrimitive(bldr, scalars)
+       case *array.Decimal32Builder:
+               appendPrimitive(bldr, scalars)
+       case *array.Decimal64Builder:
+               appendPrimitive(bldr, scalars)
        case *array.Decimal128Builder:
                appendPrimitive(bldr, scalars)
        case *array.Decimal256Builder:
diff --git a/arrow/scalar/decimal.go b/arrow/scalar/decimal.go
new file mode 100644
index 00000000..89a264c2
--- /dev/null
+++ b/arrow/scalar/decimal.go
@@ -0,0 +1,119 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package scalar
+
+import (
+       "fmt"
+       "unsafe"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/decimal"
+       "github.com/apache/arrow-go/v18/arrow/decimal128"
+       "github.com/apache/arrow-go/v18/arrow/decimal256"
+       "github.com/apache/arrow-go/v18/internal/utils"
+)
+
+type decimalScalar[T interface {
+       decimal.DecimalTypes
+       decimal.Num[T]
+}] struct {
+       scalar
+       Value T
+}
+
+type (
+       Decimal32 = decimalScalar[decimal.Decimal32]
+       Decimal64 = decimalScalar[decimal.Decimal64]
+)
+
+func NewDecimal32Scalar(val decimal.Decimal32, typ arrow.DataType) *Decimal32 {
+       return &Decimal32{scalar{typ, true}, val}
+}
+
+func NewDecimal64Scalar(val decimal.Decimal64, typ arrow.DataType) *Decimal64 {
+       return &Decimal64{scalar{typ, true}, val}
+}
+
+func (s *decimalScalar[T]) Data() []byte {
+       return unsafe.Slice((*byte)(unsafe.Pointer(&s.Value)), 
unsafe.Sizeof(s.Value))
+}
+
+func (s *decimalScalar[T]) value() interface{} { return s.Value }
+
+func (s *decimalScalar[T]) equals(rhs Scalar) bool {
+       return s.Value == rhs.(*decimalScalar[T]).Value
+}
+
+func (s *decimalScalar[T]) String() string {
+       if !s.Valid {
+               return "null"
+       }
+       val, err := s.CastTo(arrow.BinaryTypes.String)
+       if err != nil {
+               return "..."
+       }
+       return string(val.(*String).Value.Bytes())
+}
+
+// CastTo casts to string or to a decimal type at least as wide as the
+// scalar's own type.
+func (s *decimalScalar[T]) CastTo(to arrow.DataType) (Scalar, error) {
+       if !s.Valid {
+               return MakeNullScalar(to), nil
+       }
+
+       dt := s.Type.(arrow.DecimalType)
+       if to.ID() == arrow.STRING {
+               return NewStringScalar(utils.FormatDecimalG(s.Value, 
dt.GetPrecision(), dt.GetScale())), nil
+       }
+
+       toDec, ok := to.(arrow.DecimalType)
+       if !ok || toDec.BitWidth() < dt.BitWidth() {
+               return nil, fmt.Errorf("cannot cast non-nil %s scalar to type 
%s", s.Type, to)
+       }
+       newVal, err := toDecimal256(s.Value).Rescale(dt.GetScale(), 
toDec.GetScale())
+       if err != nil {
+               return nil, err
+       }
+       if !newVal.FitsInPrecision(toDec.GetPrecision()) {
+               return nil, fmt.Errorf("%s value %v will not fit in new 
precision %d", to, newVal, toDec.GetPrecision())
+       }
+
+       switch to.ID() {
+       case arrow.DECIMAL32:
+               return NewDecimal32Scalar(decimal.Decimal32(newVal.LowBits()), 
to), nil
+       case arrow.DECIMAL64:
+               return NewDecimal64Scalar(decimal.Decimal64(newVal.LowBits()), 
to), nil
+       case arrow.DECIMAL128:
+               return 
NewDecimal128Scalar(decimal128.New(int64(newVal.Array()[1]), newVal.LowBits()), 
to), nil
+       default:
+               return NewDecimal256Scalar(newVal, to), nil
+       }
+}
+
+func toDecimal256[T decimal.DecimalTypes](v T) decimal256.Num {
+       switch v := any(v).(type) {
+       case decimal.Decimal32:
+               return decimal256.FromI64(int64(v))
+       case decimal.Decimal64:
+               return decimal256.FromI64(int64(v))
+       case decimal128.Num:
+               return decimal256.FromDecimal128(v)
+       default:
+               return v.(decimal256.Num)
+       }
+}
diff --git a/arrow/scalar/parse.go b/arrow/scalar/parse.go
index ecc53a1b..66cda1fb 100644
--- a/arrow/scalar/parse.go
+++ b/arrow/scalar/parse.go
@@ -26,6 +26,7 @@ import (
 
        "github.com/apache/arrow-go/v18/arrow"
        "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/decimal"
        "github.com/apache/arrow-go/v18/arrow/decimal128"
        "github.com/apache/arrow-go/v18/arrow/decimal256"
        "github.com/apache/arrow-go/v18/arrow/float16"
@@ -580,6 +581,8 @@ func MakeScalarParam(val interface{}, dt arrow.DataType) 
(Scalar, error) {
                                        return nil, err
                                }
                                return NewDecimal256Scalar(n, ty), nil
+                       case arrow.DECIMAL32, arrow.DECIMAL64:
+                               return ParseScalar(dt, v)
                        }
                case arrow.IsFloating(dt.ID()):
                        bits := dt.(arrow.FixedWidthDataType).BitWidth()
@@ -628,6 +631,18 @@ func MakeScalarParam(val interface{}, dt arrow.DataType) 
(Scalar, error) {
                        }
                        return NewMapScalar(v), nil
                }
+       case decimal.Decimal32:
+               if _, ok := dt.(*arrow.Decimal32Type); !ok {
+                       return nil, fmt.Errorf("mismatch cannot create 
decimal32 scalar with incorrect data type")
+               }
+
+               return NewDecimal32Scalar(v, dt), nil
+       case decimal.Decimal64:
+               if _, ok := dt.(*arrow.Decimal64Type); !ok {
+                       return nil, fmt.Errorf("mismatch cannot create 
decimal64 scalar with incorrect data type")
+               }
+
+               return NewDecimal64Scalar(v, dt), nil
        case decimal128.Num:
                if _, ok := dt.(*arrow.Decimal128Type); !ok {
                        return nil, fmt.Errorf("mismatch cannot create 
decimal128 scalar with incorrect data type")
@@ -868,6 +883,20 @@ func ParseScalar(dt arrow.DataType, val string) (Scalar, 
error) {
                return NewTime64Scalar(tm, dt), nil
        case arrow.DICTIONARY:
                return ParseScalar(dt.(*arrow.DictionaryType).ValueType, val)
+       case arrow.DECIMAL32:
+               typ := dt.(*arrow.Decimal32Type)
+               n, err := decimal.Decimal32FromString(val, typ.Precision, 
typ.Scale)
+               if err != nil {
+                       return nil, err
+               }
+               return NewDecimal32Scalar(n, typ), nil
+       case arrow.DECIMAL64:
+               typ := dt.(*arrow.Decimal64Type)
+               n, err := decimal.Decimal64FromString(val, typ.Precision, 
typ.Scale)
+               if err != nil {
+                       return nil, err
+               }
+               return NewDecimal64Scalar(n, typ), nil
        case arrow.DECIMAL128:
                typ := dt.(*arrow.Decimal128Type)
                n, err := decimal128.FromString(val, typ.Precision, typ.Scale)
diff --git a/arrow/scalar/scalar.go b/arrow/scalar/scalar.go
index 42e48af4..bad7a2c9 100644
--- a/arrow/scalar/scalar.go
+++ b/arrow/scalar/scalar.go
@@ -525,6 +525,8 @@ func init() {
                arrow.INTERVAL_MONTHS:         func(dt arrow.DataType) Scalar { 
return &MonthInterval{scalar: scalar{dt, false}} },
                arrow.INTERVAL_DAY_TIME:       func(dt arrow.DataType) Scalar { 
return &DayTimeInterval{scalar: scalar{dt, false}} },
                arrow.INTERVAL_MONTH_DAY_NANO: func(dt arrow.DataType) Scalar { 
return &MonthDayNanoInterval{scalar: scalar{dt, false}} },
+               arrow.DECIMAL32:               func(dt arrow.DataType) Scalar { 
return &Decimal32{scalar: scalar{dt, false}} },
+               arrow.DECIMAL64:               func(dt arrow.DataType) Scalar { 
return &Decimal64{scalar: scalar{dt, false}} },
                arrow.DECIMAL128:              func(dt arrow.DataType) Scalar { 
return &Decimal128{scalar: scalar{dt, false}} },
                arrow.LIST:                    func(dt arrow.DataType) Scalar { 
return &List{scalar: scalar{dt, false}} },
                arrow.STRUCT: func(dt arrow.DataType) Scalar {
@@ -604,6 +606,10 @@ func GetScalar(arr arrow.Array, idx int) (Scalar, error) {
                return NewDate64Scalar(arr.Value(idx)), nil
        case *array.DayTimeInterval:
                return NewDayTimeIntervalScalar(arr.Value(idx)), nil
+       case *array.Decimal32:
+               return NewDecimal32Scalar(arr.Value(idx), arr.DataType()), nil
+       case *array.Decimal64:
+               return NewDecimal64Scalar(arr.Value(idx), arr.DataType()), nil
        case *array.Decimal128:
                return NewDecimal128Scalar(arr.Value(idx), arr.DataType()), nil
        case *array.Decimal256:
diff --git a/arrow/scalar/scalar_test.go b/arrow/scalar/scalar_test.go
index 50fd9f4a..b71a3784 100644
--- a/arrow/scalar/scalar_test.go
+++ b/arrow/scalar/scalar_test.go
@@ -183,6 +183,108 @@ func TestDecimalScalarStringCastUsesExactScaling(t 
*testing.T) {
        assert.Equal(t, 
"-0.1234567812345678123456781234567812345678123456781234567812345678123456781234",
 cast256.String())
 }
 
+func TestDecimal32And64Scalars(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+       defer mem.AssertSize(t, 0)
+
+       wider := []scalar.Scalar{
+               scalar.NewDecimal64Scalar(-12345, 
&arrow.Decimal64Type{Precision: 10, Scale: 2}),
+               scalar.NewDecimal128Scalar(decimal128.FromI64(-123450), 
&arrow.Decimal128Type{Precision: 20, Scale: 3}),
+               scalar.NewDecimal256Scalar(decimal256.FromI64(-12345), 
&arrow.Decimal256Type{Precision: 40, Scale: 2}),
+       }
+       tests := []struct {
+               value   scalar.Scalar
+               native  any
+               casts   []scalar.Scalar
+               invalid []arrow.DataType
+       }{
+               {
+                       value:  scalar.NewDecimal32Scalar(-12345, 
&arrow.Decimal32Type{Precision: 5, Scale: 2}),
+                       native: decimal.Decimal32(-12345),
+                       casts:  
append([]scalar.Scalar{scalar.NewDecimal32Scalar(-1234500, 
&arrow.Decimal32Type{Precision: 7, Scale: 4})}, wider...),
+                       invalid: []arrow.DataType{
+                               &arrow.Decimal32Type{Precision: 4, Scale: 2},
+                               &arrow.Decimal64Type{Precision: 12, Scale: 1},
+                               &arrow.Decimal256Type{Precision: 76, Scale: 76},
+                               arrow.PrimitiveTypes.Int32,
+                       },
+               },
+               {
+                       value:  scalar.NewDecimal64Scalar(-12345, 
&arrow.Decimal64Type{Precision: 12, Scale: 2}),
+                       native: decimal.Decimal64(-12345),
+                       casts:  wider,
+                       invalid: []arrow.DataType{
+                               &arrow.Decimal32Type{Precision: 9, Scale: 2},
+                               &arrow.Decimal128Type{Precision: 4, Scale: 2},
+                       },
+               },
+       }
+
+       for _, tc := range tests {
+               dt := tc.value.DataType()
+               t.Run(dt.String(), func(t *testing.T) {
+                       assert.Equal(t, "-123.45", tc.value.String())
+                       assertMakeScalarParam(t, tc.value, dt, tc.native)
+                       assertMakeScalarParam(t, tc.value, dt, "-123.45")
+                       other, err := scalar.ParseScalar(dt, "123.45")
+                       require.NoError(t, err)
+                       assert.False(t, scalar.Equals(tc.value, other))
+                       _, err = scalar.MakeScalarParam(tc.native, 
arrow.PrimitiveTypes.Int32)
+                       assert.Error(t, err)
+                       _, err = scalar.ParseScalar(dt, "12345678901234.5")
+                       assert.Error(t, err)
+
+                       null := checkMakeNullScalar(t, dt)
+                       assert.Equal(t, "null", null.String())
+                       for _, want := range tc.casts {
+                               got, err := tc.value.CastTo(want.DataType())
+                               require.NoError(t, err, "cast to %s", 
want.DataType())
+                               assertScalarsEqual(t, want, got)
+
+                               got, err = null.CastTo(want.DataType())
+                               require.NoError(t, err)
+                               assert.False(t, got.IsValid())
+                               assert.True(t, arrow.TypeEqual(want.DataType(), 
got.DataType()))
+                       }
+                       for _, to := range tc.invalid {
+                               _, err := tc.value.CastTo(to)
+                               assert.Error(t, err, "cast to %s", to)
+                       }
+
+                       expected, _, err := array.FromJSON(mem, dt, 
strings.NewReader(`["-123.45", null]`))
+                       require.NoError(t, err)
+                       defer expected.Release()
+                       for i, want := range []scalar.Scalar{tc.value, null} {
+                               got, err := scalar.GetScalar(expected, i)
+                               require.NoError(t, err)
+                               assertScalarsEqual(t, want, got)
+                       }
+
+                       bldr := array.NewBuilder(mem, dt)
+                       defer bldr.Release()
+                       require.NoError(t, scalar.AppendSlice(bldr, 
[]scalar.Scalar{tc.value, null}))
+                       appended := bldr.NewArray()
+                       defer appended.Release()
+                       assert.Truef(t, array.Equal(expected, appended), 
"expected: %s, got: %s", expected, appended)
+               })
+       }
+
+       _, err := scalar.NewDecimal32Scalar(1, &arrow.Decimal32Type{Precision: 
9, Scale: 10}).CastTo(&arrow.Decimal32Type{Precision: 9, Scale: 80})
+       assert.Error(t, err)
+       assert.Equal(t, "1e-19", scalar.NewDecimal32Scalar(1, 
&arrow.Decimal32Type{Precision: 1, Scale: 19}).String())
+       assert.Equal(t, "1e-19", scalar.NewDecimal64Scalar(1, 
&arrow.Decimal64Type{Precision: 1, Scale: 19}).String())
+       assert.Equal(t, "-1.2345e-999996", scalar.NewDecimal32Scalar(-12345, 
&arrow.Decimal32Type{Precision: 9, Scale: 1_000_000}).String())
+       assert.Equal(t, "1.2345e+1000004", scalar.NewDecimal64Scalar(12345, 
&arrow.Decimal64Type{Precision: 18, Scale: -1_000_000}).String())
+       assert.Equal(t, "0", scalar.NewDecimal32Scalar(0, 
&arrow.Decimal32Type{Precision: 9, Scale: 1_000_000}).String())
+       assert.Equal(t, "-1.2345e-999996", scalar.NewDecimal32Scalar(-12345, 
&arrow.Decimal32Type{Precision: -1, Scale: 1_000_000}).String())
+       b64 := array.NewDecimal64Builder(mem, &arrow.Decimal64Type{Precision: 
18, Scale: 1_000_000})
+       defer b64.Release()
+       b64.Append(12345)
+       huge := b64.NewDecimalArray()
+       defer huge.Release()
+       assert.Equal(t, "1.2345e-999996", huge.ValueStr(0))
+}
+
 func TestBinaryScalarBasics(t *testing.T) {
        data := "test data"
        buf := memory.NewBufferBytes([]byte(data))
@@ -1561,6 +1663,8 @@ func getScalars(mem memory.Allocator) []scalar.Scalar {
                scalar.NewDurationScalar(60, arrow.FixedWidthTypes.Duration_s),
                scalar.NewBinaryScalar(hello, arrow.BinaryTypes.Binary),
                scalar.NewFixedSizeBinaryScalar(hello, 
&arrow.FixedSizeBinaryType{ByteWidth: hello.Len()}),
+               scalar.NewDecimal32Scalar(10, &arrow.Decimal32Type{Precision: 
9, Scale: 4}),
+               scalar.NewDecimal64Scalar(10, &arrow.Decimal64Type{Precision: 
16, Scale: 4}),
                scalar.NewDecimal128Scalar(decimal128.FromI64(10), 
&arrow.Decimal128Type{Precision: 16, Scale: 4}),
                scalar.NewDecimal256Scalar(decimal256.FromI64(10), 
&arrow.Decimal256Type{Precision: 16, Scale: 4}),
                scalar.NewStringScalarFromBuffer(hello),
diff --git a/internal/utils/decimal_format.go b/internal/utils/decimal_format.go
new file mode 100644
index 00000000..f0dbb01f
--- /dev/null
+++ b/internal/utils/decimal_format.go
@@ -0,0 +1,46 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package utils
+
+import (
+       "fmt"
+       "math/big"
+       "strconv"
+       "strings"
+)
+
+// 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 {
+       if scale >= -1000 && scale <= 1000 {
+               return n.ToBigFloat(scale).Text('g', int(precision))
+       }
+       coef := n.ToBigFloat(0)
+       if coef.Sign() == 0 {
+               return coef.Text('g', int(precision))
+       }
+       // No decimal type has more than 77 coefficient digits, and a negative
+       // precision keeps 'g's shortest formatting.
+       p := min(int(precision), 77)
+       if p > 0 {
+               p--
+       }
+       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))
+}

Reply via email to