Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: sort fields by struct #1098

Merged
merged 1 commit into from
Jan 6, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading