From cf9e73a7d274ad05c5f1f5def8e00ffb0d7240b7 Mon Sep 17 00:00:00 2001 From: Alec Fong Date: Fri, 19 Apr 2024 12:40:02 +0200 Subject: [PATCH] Check if ok when casting Scan src to string --- amount.go | 5 ++++- amount_test.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/amount.go b/amount.go index a15b311..a03ef8e 100644 --- a/amount.go +++ b/amount.go @@ -360,7 +360,10 @@ func (a Amount) Value() (driver.Value, error) { // Allows scanning amounts from a PostgreSQL composite type. func (a *Amount) Scan(src interface{}) error { // Wire format: "(9.99,USD)". - input := src.(string) + input, ok := src.(string) + if !ok { + return fmt.Errorf("value is not a string: %v", src) + } if len(input) == 0 { return nil } diff --git a/amount_test.go b/amount_test.go index dce7e96..4aa42c7 100644 --- a/amount_test.go +++ b/amount_test.go @@ -930,3 +930,17 @@ func TestAmount_Scan(t *testing.T) { }) } } + +func TestAmount_ScanNonString(t *testing.T) { + var a currency.Amount + err := a.Scan(123) + + wantError := "value is not a string: 123" + errStr := "" + if err != nil { + errStr = err.Error() + } + if errStr != wantError { + t.Errorf("error: got %v, want %v", errStr, wantError) + } +}