-
Notifications
You must be signed in to change notification settings - Fork 0
/
orderByDirection.go
90 lines (77 loc) · 2.49 KB
/
orderByDirection.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package squl
import (
"bytes"
"encoding/json"
"strings"
fmt "golang.org/x/xerrors"
"github.com/trivigy/squl/internal/global"
)
// OrderByDirection describes the ORDER BY direction ASC/DESC/USING.
type OrderByDirection int
const (
// OrderByDirectionAsc indicates the sorting direction is ascending.
OrderByDirectionAsc OrderByDirection = iota + 1
// OrderByDirectionDesc indicates the sorting direction is descending.
OrderByDirectionDesc
// OrderByDirectionUsing indicates the usage of custom sorting direction operator.
OrderByDirectionUsing
)
const (
orderByDirectionAscStr = "asc"
orderByDirectionDescStr = "desc"
orderByDirectionUsingStr = "using"
)
var toStringOrderByDirection = map[OrderByDirection]string{
OrderByDirection(Unknown): unknownStr,
OrderByDirectionAsc: orderByDirectionAscStr,
OrderByDirectionDesc: orderByDirectionDescStr,
OrderByDirectionUsing: orderByDirectionUsingStr,
}
// NewOrderByDirection creates a new instance of the enum from raw string.
func NewOrderByDirection(raw string) (OrderByDirection, error) {
switch raw {
case orderByDirectionAscStr:
return OrderByDirectionAsc, nil
case orderByDirectionDescStr:
return OrderByDirectionDesc, nil
case orderByDirectionUsingStr:
return OrderByDirectionUsing, nil
default:
return OrderByDirection(Unknown), fmt.Errorf(global.ErrFmt, pkg.Name(), fmt.Errorf("unknown type %q", raw))
}
}
// String returns the string representation of the enum type
func (r OrderByDirection) String() string {
return toStringOrderByDirection[r]
}
// UnmarshalJSON unmarshals a quoted json string to enum type.
func (r *OrderByDirection) UnmarshalJSON(rbytes []byte) error {
var s string
if err := json.Unmarshal(rbytes, &s); err != nil {
return err
}
raw := strings.ToLower(s)
switch raw {
case orderByDirectionAscStr:
*r = OrderByDirectionAsc
case orderByDirectionDescStr:
*r = OrderByDirectionDesc
case orderByDirectionUsingStr:
*r = OrderByDirectionUsing
default:
*r = Unknown
return fmt.Errorf(global.ErrFmt, pkg.Name(), fmt.Errorf("unknown type %q", raw))
}
return nil
}
// MarshalJSON marshals the enum as a quoted json string.
func (r OrderByDirection) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
if _, err := buffer.WriteString(toStringOrderByDirection[r]); err != nil {
return nil, fmt.Errorf(global.ErrFmt, pkg.Name(), err)
}
if _, err := buffer.WriteString(`"`); err != nil {
return nil, fmt.Errorf(global.ErrFmt, pkg.Name(), err)
}
return buffer.Bytes(), nil
}