diff --git a/persistence/sql_base_repository.go b/persistence/sql_base_repository.go index 53cb22383..d25501d43 100644 --- a/persistence/sql_base_repository.go +++ b/persistence/sql_base_repository.go @@ -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) diff --git a/persistence/sql_base_repository_test.go b/persistence/sql_base_repository_test.go index 81aea4974..b88b0af15 100644 --- a/persistence/sql_base_repository_test.go +++ b/persistence/sql_base_repository_test.go @@ -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")) + }) + }) }) })