Skip to content

Commit

Permalink
Merge pull request #1098 from uptrace/feat-fields-sort-by-struct
Browse files Browse the repository at this point in the history
feat: sort fields by struct
  • Loading branch information
j2gg0s authored Jan 6, 2025
2 parents 20eea4e + 5edb672 commit e8aaa46
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions schema/table.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"database/sql"
"fmt"
"reflect"
"sort"
"strings"
"time"

Expand Down Expand Up @@ -250,6 +251,30 @@ func (t *Table) processFields(typ reflect.Type) {
t.addUnique(subfield, embfield.prefix, v)
}
}

if len(embedded) > 0 {
// https://github.com/uptrace/bun/issues/1095
// < v1.2, all fields follow the order corresponding to the struct
// >= v1.2, < v1.2.8, fields of nested structs have been moved to the end.
// >= v1.2.8, The default behavior remains the same as initially,
sortFieldsByStruct(t.allFields)
sortFieldsByStruct(t.Fields)
sortFieldsByStruct(t.PKs)
sortFieldsByStruct(t.DataFields)
}
}

func sortFieldsByStruct(fields []*Field) {
sort.Slice(fields, func(i, j int) bool {
left, right := fields[i], fields[j]
for k := 0; k < len(left.Index) && k < len(right.Index); k++ {
if left.Index[k] != right.Index[k] {
return left.Index[k] < right.Index[k]
}
}
// NOTE: should not reach
return true
})
}

func (t *Table) addUnique(field *Field, prefix string, tagOptions []string) {
Expand Down

0 comments on commit e8aaa46

Please sign in to comment.