Handle functions with params in sort order.

Related to #1023
This commit is contained in:
Deluan 2021-05-28 17:35:32 -04:00
parent 01f3ce0228
commit 1940267a18
2 changed files with 27 additions and 2 deletions

View File

@ -77,9 +77,9 @@ func (r sqlRepository) buildSortOrder(sort, order string) string {
}
var newSort []string
parts := strings.FieldsFunc(sort, func(c rune) bool { return c == ',' })
parts := strings.FieldsFunc(sort, splitFunc(','))
for _, p := range parts {
f := strings.Fields(p)
f := strings.FieldsFunc(p, splitFunc(' '))
newField := []string{f[0]}
if len(f) == 1 {
newField = append(newField, order)
@ -95,6 +95,21 @@ func (r sqlRepository) buildSortOrder(sort, order string) string {
return strings.Join(newSort, ", ")
}
func splitFunc(delimiter rune) func(c rune) bool {
open := false
return func(c rune) bool {
if open {
open = c != ')'
return false
}
if c == '(' {
open = true
return false
}
return c == delimiter
}
}
func (r sqlRepository) applyFilters(sq SelectBuilder, options ...model.QueryOptions) SelectBuilder {
if len(options) > 0 && options[0].Filters != nil {
sq = sq.Where(options[0].Filters)

View File

@ -60,5 +60,15 @@ var _ = Describe("sqlRepository", func() {
Expect(sql).To(Equal("name asc, age desc, status desc"))
})
})
Context("function fields", func() {
It("handles functions with multiple params", func() {
sql := r.buildSortOrder("substr(id, 7)", "asc")
Expect(sql).To(Equal("substr(id, 7) asc"))
})
It("handles functions with multiple params mixed with multiple fields", func() {
sql := r.buildSortOrder("name desc, substr(id, 7), status asc", "desc")
Expect(sql).To(Equal("name asc, substr(id, 7) desc, status desc"))
})
})
})
})