Skip to content

Commit

Permalink
Merge pull request #1132 from j2gg0s/fix-embeded-struct-field
Browse files Browse the repository at this point in the history
fix: process embedded's struct field for table
  • Loading branch information
j2gg0s authored Feb 17, 2025
2 parents fc6a894 + b410e42 commit c915415
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
33 changes: 33 additions & 0 deletions schema/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ func (t *Table) processFields(typ reflect.Type) {

names := make(map[string]struct{})
embedded := make([]embeddedField, 0, 10)
ebdStructs := make(map[string]*structField, 0)

for i, n := 0, typ.NumField(); i < n; i++ {
sf := typ.Field(i)
Expand Down Expand Up @@ -163,6 +164,17 @@ func (t *Table) processFields(typ reflect.Type) {
subfield: subfield,
})
}
if len(subtable.StructMap) > 0 {
for k, v := range subtable.StructMap {
// NOTE: conflict Struct name
if _, ok := ebdStructs[k]; !ok {
ebdStructs[k] = &structField{
Index: makeIndex(sf.Index, v.Index),
Table: subtable,
}
}
}
}

if tagstr != "" {
tag := tagparser.Parse(tagstr)
Expand Down Expand Up @@ -197,6 +209,18 @@ func (t *Table) processFields(typ reflect.Type) {
subfield: subfield,
})
}
if len(subtable.StructMap) > 0 {
for k, v := range subtable.StructMap {
// NOTE: conflict Struct name
k = prefix + k
if _, ok := ebdStructs[k]; !ok {
ebdStructs[k] = &structField{
Index: makeIndex(sf.Index, v.Index),
Table: subtable,
}
}
}
}
continue
}

Expand Down Expand Up @@ -252,6 +276,15 @@ func (t *Table) processFields(typ reflect.Type) {
}
}

if len(ebdStructs) > 0 && t.StructMap == nil {
t.StructMap = make(map[string]*structField)
}
for name, sfield := range ebdStructs {
if _, ok := t.StructMap[name]; !ok {
t.StructMap[name] = sfield
}
}

if len(embedded) > 0 {
// https://github.com/uptrace/bun/issues/1095
// < v1.2, all fields follow the order corresponding to the struct
Expand Down
6 changes: 6 additions & 0 deletions schema/table_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ func TestTable(t *testing.T) {
type Perms struct {
View bool
Create bool
Model *Model
}

type Role struct {
Expand All @@ -110,6 +111,11 @@ func TestTable(t *testing.T) {
barView, ok := table.FieldMap["bar_view"]
require.True(t, ok)
require.Equal(t, []int{1, 0}, barView.Index)

_, ok = table.StructMap["foo_model"]
require.True(t, ok)
_, ok = table.StructMap["foo_model"]
require.True(t, ok)
})

t.Run("embedWithUnique", func(t *testing.T) {
Expand Down

0 comments on commit c915415

Please sign in to comment.