fix(09-04): keep relation columns out of the default sort set

- A relation column is not sortable unless columns.yaml says so
- An explicit sortable relation orders the joined select column, then the primary key
This commit is contained in:
Jakub Zych
2026-09-24 19:04:42 +02:00
parent 6a57f63e81
commit 3efdcc1c59
2 changed files with 16 additions and 5 deletions

View File

@@ -123,7 +123,7 @@ func ExecuteList(ctx context.Context, db *gorm.DB, cc *CompiledController, in Li
if err := q.Session(&gorm.Session{}).Count(&total).Error; err != nil {
return nil, err
}
q = applyListOrder(q, model, sortCol, sortDesc)
q = applyListOrder(q, cc.List, model, sortCol, sortDesc)
for _, col := range cc.List.Columns {
if col.Relation != "" {
q = q.Preload(col.Relation)
@@ -207,7 +207,7 @@ func normalizeSort(schema *ListSchema, in ListInput) (string, bool, error) {
break
}
}
if match == nil || !match.Sortable || match.Relation != "" {
if match == nil || !match.Sortable {
return "", false, listInvalid("sort", "is not a sortable column")
}
dir := in.Dir
@@ -220,12 +220,23 @@ func normalizeSort(schema *ListSchema, in ListInput) (string, bool, error) {
return match.Key, dir == "desc", nil
}
func applyListOrder(db *gorm.DB, model any, column string, desc bool) *gorm.DB {
func applyListOrder(db *gorm.DB, schema *ListSchema, model any, column string, desc bool) *gorm.DB {
table := tableName(model)
pk := primaryColumn(model)
if column != "" {
orderTable := table
orderColumn := column
for _, col := range schema.Columns {
if col.Key != column || col.Relation == "" {
continue
}
orderTable = col.Relation
orderColumn = col.Select
db = db.Joins(col.Relation)
break
}
db = db.Order(clause.OrderByColumn{
Column: clause.Column{Table: table, Name: column},
Column: clause.Column{Table: orderTable, Name: orderColumn},
Desc: desc,
})
}