Skip to content

Commit

Permalink
feat: sort fields by struct
Browse files Browse the repository at this point in the history
Close #1095
  • Loading branch information
j2gg0s committed Jan 2, 2025
1 parent 254c441 commit b5f22c3
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 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 All @@ -24,6 +25,13 @@ const (
var (
baseModelType = reflect.TypeFor[BaseModel]()
tableNameInflector = inflection.Plural

// 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,
// but we allow users to control this behavior through this parameter.
DisableSortFieldsByStruct = false
)

type BaseModel struct{}
Expand Down Expand Up @@ -250,6 +258,26 @@ func (t *Table) processFields(typ reflect.Type) {
t.addUnique(subfield, embfield.prefix, v)
}
}

if len(embedded) > 0 && !DisableSortFieldsByStruct {
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 b5f22c3

Please sign in to comment.