Skip to content

Commit 6b50efe

Browse files
committed
Treat nil Int as zero in Numeric.Int64Value instead of panicking
1 parent 4a49cda commit 6b50efe

2 files changed

Lines changed: 23 additions & 0 deletions

File tree

pgtype/numeric.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,10 @@ func (n *Numeric) ScanScientific(src string) error {
149149
}
150150

151151
func (n *Numeric) toBigInt() (*big.Int, error) {
152+
if n.Int == nil {
153+
return big.NewInt(0), nil
154+
}
155+
152156
if n.Exp == 0 {
153157
return n.Int, nil
154158
}

pgtype/numeric_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,25 @@ func TestNumericFloat64Valuer(t *testing.T) {
171171
assert.True(t, f.Valid)
172172
}
173173

174+
func TestNumericInt64Valuer(t *testing.T) {
175+
for i, tt := range []struct {
176+
n pgtype.Numeric
177+
i pgtype.Int8
178+
}{
179+
{mustParseNumeric(t, "1"), pgtype.Int8{Int64: 1, Valid: true}},
180+
{mustParseNumeric(t, "-99999999999"), pgtype.Int8{Int64: -99999999999, Valid: true}},
181+
{mustParseNumeric(t, "0"), pgtype.Int8{Int64: 0, Valid: true}},
182+
// A valid Numeric with a nil Int is zero, matching Float64Value, Value,
183+
// and MarshalJSON. Int64Value used to dereference the nil Int and panic.
184+
{pgtype.Numeric{Valid: true}, pgtype.Int8{Int64: 0, Valid: true}},
185+
{pgtype.Numeric{}, pgtype.Int8{}},
186+
} {
187+
v, err := tt.n.Int64Value()
188+
assert.NoErrorf(t, err, "%d", i)
189+
assert.Equalf(t, tt.i, v, "%d", i)
190+
}
191+
}
192+
174193
func TestNumericCodecFuzz(t *testing.T) {
175194
skipCockroachDB(t, "server formats numeric text format differently")
176195

0 commit comments

Comments
 (0)