| 1 | package querytools |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "strings" |
| 6 | |
| 7 | "github.com/gin-gonic/gin" |
| 8 | ) |
| 9 | |
| 10 | type OrderByField struct { |
| 11 | Dir string |
| 12 | Field string |
| 13 | } |
| 14 | |
| 15 | type OrderBy struct { |
| 16 | Fields []OrderByField |
| 17 | } |
| 18 | |
| 19 | func (ob OrderBy) SqlStmt() string { |
| 20 | if len(ob.Fields) == 0 { |
| 21 | return "" |
| 22 | } |
| 23 | stmt := "ORDER BY " |
| 24 | for _, field := range ob.Fields { |
| 25 | stmt += fmt.Sprintf("%s %s,", field.Field, field.Dir) |
| 26 | } |
| 27 | return stmt[:len(stmt)-1] |
| 28 | } |
| 29 | |
| 30 | func (ob *OrderBy) Append(field OrderByField) { |
| 31 | ob.Fields = append(ob.Fields, field) |
| 32 | } |
| 33 | |
| 34 | func OrderByFromString(allowed_fields map[string]struct{}, s string) OrderBy { |
| 35 | ob := OrderBy{} |
| 36 | for raw := range strings.SplitSeq(s, ",") { |
| 37 | dir := "ASC" |
| 38 | if raw[0] == '-' { |
| 39 | raw = raw[1:] |
| 40 | dir = "DESC" |
| 41 | } |
| 42 | if _, exists := allowed_fields[raw]; exists { |
| 43 | ob.Append(OrderByField{Field: raw, Dir: dir}) |
| 44 | } |
| 45 | } |
| 46 | return ob |
| 47 | } |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | func QueryOrderBy(c *gin.Context, allowed_fields map[string]struct{}, def string) OrderBy { |
| 54 | if c.Query("order_by") == "" { |
| 55 | return OrderByFromString(allowed_fields, def) |
| 56 | } |
| 57 | return OrderByFromString(allowed_fields, c.Query("order_by")) |
| 58 | } |