From f1216222284fc2f91bee7018c5c54a3662b9a2b3 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 4 Sep 2020 14:30:53 +0800 Subject: [PATCH] Don't add prefix for invalid embedded fields --- schema/field.go | 2 +- schema/schema_test.go | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/schema/field.go b/schema/field.go index f8a73c60..db044c23 100644 --- a/schema/field.go +++ b/schema/field.go @@ -340,7 +340,7 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field { ef.StructField.Index = append([]int{-fieldStruct.Index[0] - 1}, ef.StructField.Index...) } - if prefix, ok := field.TagSettings["EMBEDDEDPREFIX"]; ok { + if prefix, ok := field.TagSettings["EMBEDDEDPREFIX"]; ok && ef.DBName != "" { ef.DBName = prefix + ef.DBName } diff --git a/schema/schema_test.go b/schema/schema_test.go index 4d13ebd2..6ca5b269 100644 --- a/schema/schema_test.go +++ b/schema/schema_test.go @@ -194,6 +194,7 @@ func TestEmbeddedStruct(t *testing.T) { ID int OwnerID int Name string + Ignored string `gorm:"-"` } type Corp struct { @@ -211,15 +212,18 @@ func TestEmbeddedStruct(t *testing.T) { {Name: "ID", DBName: "id", BindNames: []string{"CorpBase", "Model", "ID"}, DataType: schema.Uint, PrimaryKey: true, Size: 64, HasDefaultValue: true, AutoIncrement: true, TagSettings: map[string]string{"PRIMARYKEY": "PRIMARYKEY"}}, {Name: "ID", DBName: "company_id", BindNames: []string{"Base", "ID"}, DataType: schema.Int, Size: 64, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}}, {Name: "Name", DBName: "company_name", BindNames: []string{"Base", "Name"}, DataType: schema.String, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}}, + {Name: "Ignored", BindNames: []string{"Base", "Ignored"}, TagSettings: map[string]string{"-": "-", "EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}}, {Name: "OwnerID", DBName: "company_owner_id", BindNames: []string{"Base", "OwnerID"}, DataType: schema.Int, Size: 64, TagSettings: map[string]string{"EMBEDDED": "EMBEDDED", "EMBEDDEDPREFIX": "company_"}}, {Name: "OwnerID", DBName: "owner_id", BindNames: []string{"CorpBase", "OwnerID"}, DataType: schema.String}, } for _, f := range fields { checkSchemaField(t, cropSchema, &f, func(f *schema.Field) { - f.Creatable = true - f.Updatable = true - f.Readable = true + if f.Name != "Ignored" { + f.Creatable = true + f.Updatable = true + f.Readable = true + } }) } }