Skip to content

Commit

Permalink
fix: embedded default value (go-gorm#5540)
Browse files Browse the repository at this point in the history
  • Loading branch information
a631807682 committed Jul 25, 2022
1 parent bab3cd1 commit 06e174e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
8 changes: 2 additions & 6 deletions schema/field.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,18 +403,14 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field {
}

if ef.PrimaryKey {
if val, ok := ef.TagSettings["PRIMARYKEY"]; ok && utils.CheckTruth(val) {
ef.PrimaryKey = true
} else if val, ok := ef.TagSettings["PRIMARY_KEY"]; ok && utils.CheckTruth(val) {
ef.PrimaryKey = true
} else {
if !utils.CheckTruth(ef.TagSettings["PRIMARYKEY"], ef.TagSettings["PRIMARY_KEY"]) {
ef.PrimaryKey = false

if val, ok := ef.TagSettings["AUTOINCREMENT"]; !ok || !utils.CheckTruth(val) {
ef.AutoIncrement = false
}

if ef.DefaultValue == "" {
if !ef.AutoIncrement && ef.DefaultValue == "" {
ef.HasDefaultValue = false
}
}
Expand Down
26 changes: 26 additions & 0 deletions tests/embedded_struct_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,29 @@ func TestEmbeddedRelations(t *testing.T) {
}
}
}

func TestEmbeddedTagSetting(t *testing.T) {
type Tag1 struct {
Id int64 `gorm:"autoIncrement"`
}
type Tag2 struct {
Id int64
}

type EmbeddedTag struct {
Tag1 Tag1 `gorm:"Embedded;"`
Tag2 Tag2 `gorm:"Embedded;EmbeddedPrefix:t2_"`
Name string
}

DB.Migrator().DropTable(&EmbeddedTag{})
err := DB.Migrator().AutoMigrate(&EmbeddedTag{})
AssertEqual(t, err, nil)

t1 := EmbeddedTag{Name: "embedded_tag"}
err = DB.Save(&t1).Error
AssertEqual(t, err, nil)
if t1.Tag1.Id == 0 {
t.Errorf("embedded struct's primary field should be rewrited")
}
}

0 comments on commit 06e174e

Please sign in to comment.