forked from raystack/guardian
-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
68 lines (59 loc) · 1.78 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package postgres
import (
"fmt"
"strings"
"github.com/goto/guardian/utils"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type addOrderByClauseOptions struct {
statusColumnName string
statusesOrder []string
}
func addOrderByClause(db *gorm.DB, conditions []string, options addOrderByClauseOptions) *gorm.DB {
var orderByClauses []string
var vars []interface{}
for _, orderBy := range conditions {
if strings.Contains(orderBy, "status") {
orderByClauses = append(orderByClauses, fmt.Sprintf(`ARRAY_POSITION(ARRAY[?], %s)`, options.statusColumnName))
vars = append(vars, options.statusesOrder)
} else {
columnOrder := strings.Split(orderBy, ":")
column := columnOrder[0]
if utils.ContainsString([]string{"updated_at", "created_at"}, column) {
if len(columnOrder) == 1 {
orderByClauses = append(orderByClauses, fmt.Sprintf(`"%s"`, column))
} else if len(columnOrder) == 2 {
order := columnOrder[1]
if utils.ContainsString([]string{"asc", "desc"}, order) {
orderByClauses = append(orderByClauses, fmt.Sprintf(`"%s" %s`, column, order))
}
}
}
}
}
return db.Clauses(clause.OrderBy{
Expression: clause.Expr{
SQL: strings.Join(orderByClauses, ", "),
Vars: vars,
WithoutParentheses: true,
},
})
}
func addOrderBy(db *gorm.DB, orderBy string) *gorm.DB {
if orderBy != "" {
var column, order string
expression := strings.Split(orderBy, ":")
column = expression[0]
if len(expression) == 2 {
order = expression[1]
}
if utils.ContainsString([]string{"updated_at", "created_at"}, strings.ToLower(column)) {
if utils.ContainsString([]string{"asc", "desc"}, strings.ToLower(order)) {
return db.Order(fmt.Sprintf(`"%s" %s`, column, order))
}
return db.Order(column)
}
}
return db
}