From 471eda5a12ea440edb642b81f0dd5f291fb4fe45 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 28 Aug 2014 19:14:58 +0800 Subject: [PATCH] Panic if found duplicated column name --- anonymous_struct_test.go | 14 ++++++++++++-- scope.go | 13 ++++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/anonymous_struct_test.go b/anonymous_struct_test.go index 35bee690..964732b4 100644 --- a/anonymous_struct_test.go +++ b/anonymous_struct_test.go @@ -14,13 +14,13 @@ type HNPost struct { } type EngadgetPost struct { - BasePost + BasePost BasePost `gorm:"embedded"` ImageUrl string } func TestSaveAndQueryEmbeddedStruct(t *testing.T) { + DB.Save(&HNPost{BasePost: BasePost{Title: "news"}}) DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}}) - var news HNPost if err := DB.First(&news, "title = ?", "hn_news").Error; err != nil { t.Errorf("no error should happen when query with embedded struct, but got %v", err) @@ -29,4 +29,14 @@ func TestSaveAndQueryEmbeddedStruct(t *testing.T) { t.Errorf("embedded struct's value should be scanned correctly") } } + + DB.Save(&EngadgetPost{BasePost: BasePost{Title: "engadget_news"}}) + var egNews EngadgetPost + if err := DB.First(&egNews, "title = ?", "engadget_news").Error; err != nil { + t.Errorf("no error should happen when query with embedded struct, but got %v", err) + } else { + if egNews.BasePost.Title != "engadget_news" { + t.Errorf("embedded struct's value should be scanned correctly") + } + } } diff --git a/scope.go b/scope.go index 52cd7d87..b36669da 100644 --- a/scope.go +++ b/scope.go @@ -263,11 +263,6 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) []*Field { // Search for primary key tag identifier settings := parseTagSetting(fieldStruct.Tag.Get("gorm")) - prefix := settings["PREFIX"] - if prefix == "-" { - prefix = "" - } - if scope.PrimaryKey() == field.DBName { field.IsPrimaryKey = true } @@ -322,7 +317,7 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField) []*Field { if embedded != "" { var fields []*Field for _, field := range scope.New(field.Field.Addr().Interface()).Fields() { - field.DBName = prefix + field.DBName + field.DBName = field.DBName fields = append(fields, field) } return fields @@ -356,7 +351,11 @@ func (scope *Scope) Fields() map[string]*Field { continue } for _, field := range scope.fieldFromStruct(fieldStruct) { - fields[field.DBName] = field + if _, ok := fields[field.DBName]; ok { + panic(fmt.Sprintf("Duplicated column name for %v (%v)\n", scope.typeName(), fileWithLineNum())) + } else { + fields[field.DBName] = field + } } } }