1
0
mirror of https://github.com/DATA-DOG/go-sqlmock.git synced 2025-05-15 22:06:43 +02:00

tests/Null{Int,Time}: refactor Scan for less lines of code

Single switch for all cases.
Single return for the success case.
This commit is contained in:
Olivier Mengué 2018-07-12 11:55:17 +02:00
parent f974ac3c0c
commit 9119b1dbff

View File

@ -19,25 +19,18 @@ type NullInt struct {
} }
// Satisfy sql.Scanner interface // Satisfy sql.Scanner interface
func (ni *NullInt) Scan(value interface{}) (err error) { func (ni *NullInt) Scan(value interface{}) error {
if value == nil {
ni.Integer, ni.Valid = 0, false
return
}
switch v := value.(type) { switch v := value.(type) {
case nil:
ni.Integer, ni.Valid = 0, false
case int: case int:
ni.Integer, ni.Valid = v, true ni.Integer, ni.Valid = v, true
return
case int8: case int8:
ni.Integer, ni.Valid = int(v), true ni.Integer, ni.Valid = int(v), true
return
case int16: case int16:
ni.Integer, ni.Valid = int(v), true ni.Integer, ni.Valid = int(v), true
return
case int32: case int32:
ni.Integer, ni.Valid = int(v), true ni.Integer, ni.Valid = int(v), true
return
case int64: case int64:
const maxUint = ^uint(0) const maxUint = ^uint(0)
const minUint = 0 const minUint = 0
@ -48,25 +41,23 @@ func (ni *NullInt) Scan(value interface{}) (err error) {
return errors.New("value out of int range") return errors.New("value out of int range")
} }
ni.Integer, ni.Valid = int(v), true ni.Integer, ni.Valid = int(v), true
return
case []byte: case []byte:
n, err := strconv.Atoi(string(v)) n, err := strconv.Atoi(string(v))
if err != nil { if err != nil {
return err return err
} }
ni.Integer, ni.Valid = n, true ni.Integer, ni.Valid = n, true
return nil
case string: case string:
n, err := strconv.Atoi(v) n, err := strconv.Atoi(v)
if err != nil { if err != nil {
return err return err
} }
ni.Integer, ni.Valid = n, true ni.Integer, ni.Valid = n, true
return nil default:
ni.Valid = false
return fmt.Errorf("Can't convert %T to integer", value)
} }
return nil
ni.Valid = false
return fmt.Errorf("Can't convert %T to integer", value)
} }
// Satisfy sql.Valuer interface. // Satisfy sql.Valuer interface.
@ -78,20 +69,17 @@ func (ni NullInt) Value() (driver.Value, error) {
} }
// Satisfy sql.Scanner interface // Satisfy sql.Scanner interface
func (nt *NullTime) Scan(value interface{}) (err error) { func (nt *NullTime) Scan(value interface{}) error {
if value == nil {
nt.Time, nt.Valid = time.Time{}, false
return
}
switch v := value.(type) { switch v := value.(type) {
case nil:
nt.Time, nt.Valid = time.Time{}, false
case time.Time: case time.Time:
nt.Time, nt.Valid = v, true nt.Time, nt.Valid = v, true
return default:
nt.Valid = false
return fmt.Errorf("Can't convert %T to time.Time", value)
} }
return nil
nt.Valid = false
return fmt.Errorf("Can't convert %T to time.Time", value)
} }
// Satisfy sql.Valuer interface. // Satisfy sql.Valuer interface.