/
sort.go
63 lines (52 loc) · 978 Bytes
/
sort.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
package dbkit
import (
"errors"
"fmt"
sq "github.com/Masterminds/squirrel"
)
const (
// Asc for ascending
Asc OrderBy = iota
// Desc for descending
Desc
)
type (
// SortOption for select
SortOption struct {
column string
orderBy OrderBy
}
// OrderBy is type of order by
OrderBy int
)
//
// Sort
//
var _ SelectOption = (*SortOption)(nil)
// Sort is find option to sort by column and order
func Sort(column string, orderBy OrderBy) *SortOption {
return &SortOption{
column: column,
orderBy: orderBy,
}
}
// CompileSelect to compile select query for sorting
func (s *SortOption) CompileSelect(base sq.SelectBuilder) (sq.SelectBuilder, error) {
if s.column == "" {
return base, errors.New("Sort column can't be empty")
}
base = base.OrderBy(fmt.Sprintf("%s %s", s.column, s.orderBy))
return base, nil
}
//
// OrderBy
//
func (o OrderBy) String() string {
switch o {
case Asc:
return "ASC"
case Desc:
return "DESC"
}
return "ASC"
}