From b708c8b985ce0602ab017cab5f03a6ae7fd2f2be Mon Sep 17 00:00:00 2001 From: leighhopcroft Date: Tue, 2 Jun 2020 19:07:10 +0100 Subject: [PATCH] support NaN in Numeric.AssignTo --- numeric.go | 7 +++++++ numeric_test.go | 18 ++++++++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/numeric.go b/numeric.go index f4ddb789..644ee23f 100644 --- a/numeric.go +++ b/numeric.go @@ -267,6 +267,13 @@ func (src *Numeric) AssignTo(dst interface{}) error { } case Null: return NullAssignTo(dst) + case Undefined: + switch v := dst.(type) { + case *float32: + *v = float32(math.NaN()) + case *float64: + *v = math.NaN() + } } return nil diff --git a/numeric_test.go b/numeric_test.go index 3b099b55..ee72ff5e 100644 --- a/numeric_test.go +++ b/numeric_test.go @@ -269,6 +269,8 @@ func TestNumericAssignTo(t *testing.T) { {src: &pgtype.Numeric{Int: big.NewInt(0), Status: pgtype.Null}, dst: &pi8, expected: ((*int8)(nil))}, {src: &pgtype.Numeric{Int: big.NewInt(0), Status: pgtype.Null}, dst: &_pi8, expected: ((*_int8)(nil))}, {src: &pgtype.Numeric{Int: big.NewInt(1006), Exp: -2, Status: pgtype.Present}, dst: &f64, expected: float64(10.06)}, // https://github.com/jackc/pgtype/issues/27 + {src: &pgtype.Numeric{}, dst: &f64, expected: math.NaN()}, + {src: &pgtype.Numeric{}, dst: &f32, expected: float32(math.NaN())}, } for i, tt := range simpleTests { @@ -277,8 +279,20 @@ func TestNumericAssignTo(t *testing.T) { t.Errorf("%d: %v", i, err) } - if dst := reflect.ValueOf(tt.dst).Elem().Interface(); dst != tt.expected { - t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) + dst := reflect.ValueOf(tt.dst).Elem().Interface() + switch dstTyped := dst.(type) { + case float32: + if math.IsNaN(float64(tt.expected.(float32))) && !math.IsNaN(float64(dstTyped)) { + t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) + } + case float64: + if math.IsNaN(tt.expected.(float64)) && !math.IsNaN(dstTyped) { + t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) + } + default: + if dst != tt.expected { + t.Errorf("%d: expected %v to assign %v, but result was %v", i, tt.src, tt.expected, dst) + } } }