-
Notifications
You must be signed in to change notification settings - Fork 1
/
function_case.go
92 lines (69 loc) · 1.63 KB
/
function_case.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
91
92
package dbr
import (
"fmt"
"strings"
)
type functionCase struct {
alias *string
onCase *onCase
onWhens onCaseWhens
onElse *onCaseElse
*functionBase
}
func newFunctionCase(value ...interface{}) *functionCase {
funcCase := &functionCase{
functionBase: newFunctionBase(false, false),
onCase: newCase(value...),
onWhens: newCaseWhens(),
}
return funcCase
}
func (c *functionCase) When(query interface{}, values ...interface{}) *functionCase {
c.onWhens = append(c.onWhens, newCaseWhen(newCondition(nil, OperatorAnd, query, values...)))
return c
}
func (c *functionCase) Then(result interface{}) *functionCase {
if len(c.onWhens) > 0 {
c.onWhens[len(c.onWhens)-1].result = result
}
return c
}
func (c *functionCase) Else(result interface{}) *functionCase {
c.onElse = newCaseElse(result)
return c
}
func (c *functionCase) As(alias string) *functionCase {
c.alias = &alias
return c
}
func (c *functionCase) Expression(db *db) (string, error) {
c.db = db
return "", nil
}
func (c *functionCase) Build(db *db) (string, error) {
c.db = db
var value string
var query string
onCase, err := c.onCase.Build(db)
if err != nil {
return "", err
}
value += onCase
onWhens, err := c.onWhens.Build(db)
if err != nil {
return "", err
}
value += onWhens
onElse, err := c.onElse.Build(db)
if err != nil {
return "", err
}
if len(onElse) > 0 {
value += fmt.Sprintf(" %s", onElse)
}
query = fmt.Sprintf("(%s %s %s)", constFunctionCase, value, constFunctionEnd)
if c.alias != nil && len(strings.TrimSpace(*c.alias)) > 0 {
query += fmt.Sprintf(" %s %s", constFunctionAs, *c.alias)
}
return query, nil
}