From 27a03477f4f63b4cbdc8afe41a27ec73e7b07bfd Mon Sep 17 00:00:00 2001 From: Timothy Stranex Date: Sat, 15 Mar 2014 21:55:40 +0200 Subject: [PATCH] Prevent panic for fields that implement the sql.Scanner interface but are not structs. Example: type NamedInt int64 func (i *NamedInt) Scan(src interface{}) error { v := reflect.ValueOf(src) if v.Kind() != reflect.Int64 { return errors.New("Cannot scan NamedInt from " + v.String()) } *i = NamedInt(v.Int()) return nil } The model: type Model struct { NamedInt NamedInt `sql:"type:bigint"` } Currently, the NamedInt field causes gorm to panic. This change allows it to work as expected. --- main_test.go | 11 +++++++++++ scope_private.go | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/main_test.go b/main_test.go index 1df4558a..b662d43c 100644 --- a/main_test.go +++ b/main_test.go @@ -22,6 +22,16 @@ type IgnoredEmbedStruct struct { Name string } +type NamedInt int64 +func (i *NamedInt) Scan(src interface{}) error { + v := reflect.ValueOf(src) + if v.Kind() != reflect.Int64 { + return errors.New("Cannot scan NamedInt from " + v.String()) + } + *i = NamedInt(v.Int()) + return nil +} + type User struct { Id int64 // Id: Primary key Age int64 @@ -42,6 +52,7 @@ type User struct { PasswordHash []byte IgnoreMe int64 `sql:"-"` IgnoreStringSlice []string `sql:"-"` + NamedInt NamedInt `sql:"type:bigint"` } type CreditCard struct { diff --git a/scope_private.go b/scope_private.go index 7212af2b..591a7fed 100644 --- a/scope_private.go +++ b/scope_private.go @@ -309,7 +309,7 @@ func (scope *Scope) sqlTagForField(field *Field) (tag string) { value := field.Value reflectValue := reflect.ValueOf(value) - if field.IsScanner() { + if field.IsScanner() && reflectValue.Kind() == reflect.Struct { value = reflectValue.Field(0).Interface() }