diff --git a/pgtype/numeric.go b/pgtype/numeric.go index caf5ff17b..90cf4307a 100644 --- a/pgtype/numeric.go +++ b/pgtype/numeric.go @@ -149,6 +149,10 @@ func (n *Numeric) ScanScientific(src string) error { } func (n *Numeric) toBigInt() (*big.Int, error) { + if n.Int == nil { + return big.NewInt(0), nil + } + if n.Exp == 0 { return n.Int, nil } diff --git a/pgtype/numeric_test.go b/pgtype/numeric_test.go index 61faac5df..7dcdaf624 100644 --- a/pgtype/numeric_test.go +++ b/pgtype/numeric_test.go @@ -171,6 +171,25 @@ func TestNumericFloat64Valuer(t *testing.T) { assert.True(t, f.Valid) } +func TestNumericInt64Valuer(t *testing.T) { + for i, tt := range []struct { + n pgtype.Numeric + i pgtype.Int8 + }{ + {mustParseNumeric(t, "1"), pgtype.Int8{Int64: 1, Valid: true}}, + {mustParseNumeric(t, "-99999999999"), pgtype.Int8{Int64: -99999999999, Valid: true}}, + {mustParseNumeric(t, "0"), pgtype.Int8{Int64: 0, Valid: true}}, + // A valid Numeric with a nil Int is zero, matching Float64Value, Value, + // and MarshalJSON. Int64Value used to dereference the nil Int and panic. + {pgtype.Numeric{Valid: true}, pgtype.Int8{Int64: 0, Valid: true}}, + {pgtype.Numeric{}, pgtype.Int8{}}, + } { + v, err := tt.n.Int64Value() + assert.NoErrorf(t, err, "%d", i) + assert.Equalf(t, tt.i, v, "%d", i) + } +} + func TestNumericCodecFuzz(t *testing.T) { skipCockroachDB(t, "server formats numeric text format differently")