-
Notifications
You must be signed in to change notification settings - Fork 28
/
case.go
87 lines (76 loc) · 1.87 KB
/
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
package sqlingo
import "strings"
// CaseExpression indicates the status in a CASE statement
type CaseExpression interface {
WhenThen(when BooleanExpression, then interface{}) CaseExpression
Else(value interface{}) CaseExpressionWithElse
End() Expression
}
// CaseExpressionWithElse indicates the status in CASE ... ELSE ... statement
type CaseExpressionWithElse interface {
End() Expression
}
type caseStatus struct {
head, tail *whenThen
elseValue interface{}
}
type whenThen struct {
next *whenThen
when BooleanExpression
then interface{}
}
// Case initiates a CASE statement
func Case() CaseExpression {
return caseStatus{}
}
func (s caseStatus) WhenThen(when BooleanExpression, then interface{}) CaseExpression {
whenThen := &whenThen{when: when, then: then}
if s.head == nil {
s.head = whenThen
}
if s.tail != nil {
s.tail.next = whenThen
}
s.tail = whenThen
return s
}
func (s caseStatus) Else(value interface{}) CaseExpressionWithElse {
s.elseValue = value
return s
}
func (s caseStatus) End() Expression {
if s.head == nil {
return expression{
builder: func(scope scope) (string, error) {
elseSql, _, err := getSQL(scope, s.elseValue)
return elseSql, err
},
}
}
return expression{
builder: func(scope scope) (string, error) {
sb := strings.Builder{}
sb.WriteString("CASE ")
for whenThen := s.head; whenThen != nil; whenThen = whenThen.next {
whenSql, err := whenThen.when.GetSQL(scope)
if err != nil {
return "", err
}
thenSql, _, err := getSQL(scope, whenThen.then)
if err != nil {
return "", err
}
sb.WriteString("WHEN " + whenSql + " THEN " + thenSql + " ")
}
if s.elseValue != nil {
elseSql, _, err := getSQL(scope, s.elseValue)
if err != nil {
return "", err
}
sb.WriteString("ELSE " + elseSql + " ")
}
sb.WriteString("END")
return sb.String(), nil
},
}
}