From 78ada3fc29b7dd4a76156bb9937ea3ec4d6b2c25 Mon Sep 17 00:00:00 2001 From: Kiril Vladimiroff Date: Thu, 5 Mar 2020 16:18:52 +0200 Subject: [PATCH] Implement Scan with a type switch This is just a minor (and a bit opinionated) tweak in Scan. While using the generated Scan method, realized that what's being returned from any driver I've stumbled upon is actually []byte instead of string, thus always causing a one failed type assertion on Scan. --- golden_test.go | 36 ++++++++++++++++++++---------------- sql.go | 20 +++++++++++--------- 2 files changed, 31 insertions(+), 25 deletions(-) diff --git a/golden_test.go b/golden_test.go index 9f0b5b5..040fa68 100644 --- a/golden_test.go +++ b/golden_test.go @@ -1682,14 +1682,16 @@ func (i *Prime) Scan(value interface{}) error { return nil } - str, ok := value.(string) - if !ok { - bytes, ok := value.([]byte) - if !ok { - return fmt.Errorf("value is not a byte slice") - } - - str = string(bytes[:]) + var str string + switch v := value.(type) { + case []byte: + str = string(b) + case string: + str = v + case fmt.Stringer: + str = v.String() + default: + return fmt.Errorf("invalid value of Prime: %[1]T(%[1]v)", value) } val, err := PrimeString(str) @@ -1867,14 +1869,16 @@ func (i *Prime) Scan(value interface{}) error { return nil } - str, ok := value.(string) - if !ok { - bytes, ok := value.([]byte) - if !ok { - return fmt.Errorf("value is not a byte slice") - } - - str = string(bytes[:]) + var str string + switch v := value.(type) { + case []byte: + str = string(b) + case string: + str = v + case fmt.Stringer: + str = v.String() + default: + return fmt.Errorf("invalid value of Prime: %[1]T(%[1]v)", value) } val, err := PrimeString(str) diff --git a/sql.go b/sql.go index 67d5354..2a2906f 100644 --- a/sql.go +++ b/sql.go @@ -12,21 +12,23 @@ const scanMethod = `func (i *%[1]s) Scan(value interface{}) error { return nil } - str, ok := value.(string) - if !ok { - bytes, ok := value.([]byte) - if !ok { - return fmt.Errorf("value is not a byte slice") - } - - str = string(bytes[:]) + var str string + switch v := value.(type) { + case []byte: + str = string(b) + case string: + str = v + case fmt.Stringer: + str = v.String() + default: + return fmt.Errorf("invalid value of %[1]s: %%[1]T(%%[1]v)", value) } val, err := %[1]sString(str) if err != nil { return err } - + *i = val return nil }