Panic if found duplicated column name

This commit is contained in:
Jinzhu 2014-08-28 19:14:58 +08:00
parent f984bc8515
commit 471eda5a12
2 changed files with 18 additions and 9 deletions

View File

@ -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")
}
}
}

View File

@ -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
}
}
}
}