From 446ce99a42ffe050b77bdd761271f97dd1e2b554 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 5 Sep 2016 22:26:57 +0800 Subject: [PATCH] Support set prefix for embedded struct --- embedded_struct_test.go | 18 ++++++++++++++++++ migration_test.go | 1 - model_struct.go | 3 +++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/embedded_struct_test.go b/embedded_struct_test.go index 7be75d99..89938bc6 100644 --- a/embedded_struct_test.go +++ b/embedded_struct_test.go @@ -8,16 +8,34 @@ type BasePost struct { URL string } +type Author struct { + Name string + Email string +} + type HNPost struct { BasePost + Author `gorm:"embedded_prefix:user_"` // Embedded struct Upvotes int32 } type EngadgetPost struct { BasePost BasePost `gorm:"embedded"` + Author Author `gorm:"embedded;embedded_prefix:author_"` // Embedded struct ImageUrl string } +func TestPrefixColumnNameForEmbeddedStruct(t *testing.T) { + dialect := DB.NewScope(&EngadgetPost{}).Dialect() + if !dialect.HasColumn(DB.NewScope(&EngadgetPost{}).TableName(), "author_name") || !dialect.HasColumn(DB.NewScope(&EngadgetPost{}).TableName(), "author_email") { + t.Errorf("should has prefix for embedded columns") + } + + if !dialect.HasColumn(DB.NewScope(&HNPost{}).TableName(), "user_name") || !dialect.HasColumn(DB.NewScope(&HNPost{}).TableName(), "user_email") { + t.Errorf("should has prefix for embedded columns") + } +} + func TestSaveAndQueryEmbeddedStruct(t *testing.T) { DB.Save(&HNPost{BasePost: BasePost{Title: "news"}}) DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}}) diff --git a/migration_test.go b/migration_test.go index 30085263..08633283 100644 --- a/migration_test.go +++ b/migration_test.go @@ -256,7 +256,6 @@ func runMigration() { for _, value := range values { DB.DropTable(value) } - if err := DB.AutoMigrate(values...).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } diff --git a/model_struct.go b/model_struct.go index d9e84c3c..8179a1f3 100644 --- a/model_struct.go +++ b/model_struct.go @@ -203,6 +203,9 @@ func (scope *Scope) GetModelStruct() *ModelStruct { for _, subField := range scope.New(fieldValue).GetStructFields() { subField = subField.clone() subField.Names = append([]string{fieldStruct.Name}, subField.Names...) + if prefix, ok := field.TagSettings["EMBEDDED_PREFIX"]; ok { + subField.DBName = prefix + subField.DBName + } if subField.IsPrimaryKey { modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField) }