-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorderByNulls.go
81 lines (69 loc) · 2.04 KB
/
orderByNulls.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
package squl
import (
"bytes"
"encoding/json"
"strings"
fmt "golang.org/x/xerrors"
"github.com/trivigy/squl/internal/global"
)
// OrderByNulls describes NULLS sorting order.
type OrderByNulls int
const (
// OrderByNullsFirst indicates that sorting should list nulls first.
OrderByNullsFirst OrderByNulls = iota + 1
// OrderByNullsLast indicates that sorting should list nulls last.
OrderByNullsLast
)
const (
orderByNullsFirstStr = "first"
orderByNullsLastStr = "last"
)
var toStringOrderByNulls = map[OrderByNulls]string{
OrderByNulls(Unknown): unknownStr,
OrderByNullsFirst: orderByNullsFirstStr,
OrderByNullsLast: orderByNullsLastStr,
}
// NewOrderByNulls creates a new instance of the enum from raw string.
func NewOrderByNulls(raw string) (OrderByNulls, error) {
switch raw {
case orderByNullsFirstStr:
return OrderByNullsFirst, nil
case orderByNullsLastStr:
return OrderByNullsLast, nil
default:
return OrderByNulls(Unknown), fmt.Errorf(global.ErrFmt, pkg.Name(), fmt.Errorf("unknown type %q", raw))
}
}
// String returns the string representation of the enum type
func (r OrderByNulls) String() string {
return toStringOrderByNulls[r]
}
// UnmarshalJSON unmarshals a quoted json string to enum type.
func (r *OrderByNulls) UnmarshalJSON(rbytes []byte) error {
var s string
if err := json.Unmarshal(rbytes, &s); err != nil {
return err
}
raw := strings.ToLower(s)
switch raw {
case orderByNullsFirstStr:
*r = OrderByNullsFirst
case orderByNullsLastStr:
*r = OrderByNullsLast
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 OrderByNulls) MarshalJSON() ([]byte, error) {
buffer := bytes.NewBufferString(`"`)
if _, err := buffer.WriteString(toStringOrderByNulls[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
}