Skip to content

Commit c915415

Browse files
authored
Merge pull request uptrace#1132 from j2gg0s/fix-embeded-struct-field
fix: process embedded's struct field for table
2 parents fc6a894 + b410e42 commit c915415

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

schema/table.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ func (t *Table) processFields(typ reflect.Type) {
122122

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

126127
for i, n := 0, typ.NumField(); i < n; i++ {
127128
sf := typ.Field(i)
@@ -163,6 +164,17 @@ func (t *Table) processFields(typ reflect.Type) {
163164
subfield: subfield,
164165
})
165166
}
167+
if len(subtable.StructMap) > 0 {
168+
for k, v := range subtable.StructMap {
169+
// NOTE: conflict Struct name
170+
if _, ok := ebdStructs[k]; !ok {
171+
ebdStructs[k] = &structField{
172+
Index: makeIndex(sf.Index, v.Index),
173+
Table: subtable,
174+
}
175+
}
176+
}
177+
}
166178

167179
if tagstr != "" {
168180
tag := tagparser.Parse(tagstr)
@@ -197,6 +209,18 @@ func (t *Table) processFields(typ reflect.Type) {
197209
subfield: subfield,
198210
})
199211
}
212+
if len(subtable.StructMap) > 0 {
213+
for k, v := range subtable.StructMap {
214+
// NOTE: conflict Struct name
215+
k = prefix + k
216+
if _, ok := ebdStructs[k]; !ok {
217+
ebdStructs[k] = &structField{
218+
Index: makeIndex(sf.Index, v.Index),
219+
Table: subtable,
220+
}
221+
}
222+
}
223+
}
200224
continue
201225
}
202226

@@ -252,6 +276,15 @@ func (t *Table) processFields(typ reflect.Type) {
252276
}
253277
}
254278

279+
if len(ebdStructs) > 0 && t.StructMap == nil {
280+
t.StructMap = make(map[string]*structField)
281+
}
282+
for name, sfield := range ebdStructs {
283+
if _, ok := t.StructMap[name]; !ok {
284+
t.StructMap[name] = sfield
285+
}
286+
}
287+
255288
if len(embedded) > 0 {
256289
// https://github.com/uptrace/bun/issues/1095
257290
// < v1.2, all fields follow the order corresponding to the struct

schema/table_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ func TestTable(t *testing.T) {
9292
type Perms struct {
9393
View bool
9494
Create bool
95+
Model *Model
9596
}
9697

9798
type Role struct {
@@ -110,6 +111,11 @@ func TestTable(t *testing.T) {
110111
barView, ok := table.FieldMap["bar_view"]
111112
require.True(t, ok)
112113
require.Equal(t, []int{1, 0}, barView.Index)
114+
115+
_, ok = table.StructMap["foo_model"]
116+
require.True(t, ok)
117+
_, ok = table.StructMap["foo_model"]
118+
require.True(t, ok)
113119
})
114120

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

0 commit comments

Comments
 (0)