-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcase.go
45 lines (34 loc) · 1013 Bytes
/
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
package sqlbuilder
type CaseExpr struct {
inputExpr AsExpr
cases []*CaseWhenClause
elseExpr AsExpr
}
func Case(inputExpr AsExpr) *CaseExpr {
return &CaseExpr{inputExpr: inputExpr}
}
func (c *CaseExpr) When(whenClause ...*CaseWhenClause) *CaseExpr {
return &CaseExpr{inputExpr: c.inputExpr, cases: append(c.cases[:], whenClause...), elseExpr: c.elseExpr}
}
func (c *CaseExpr) Else(elseExpr AsExpr) *CaseExpr {
return &CaseExpr{inputExpr: c.inputExpr, cases: c.cases, elseExpr: elseExpr}
}
func (c *CaseExpr) AsExpr(s *Serializer) {
s.D("CASE ")
if c.inputExpr != nil {
s.F(c.inputExpr.AsExpr).D(" ")
}
for _, e := range c.cases {
s.D("WHEN ").F(e.whenExpr.AsExpr).D(" THEN ").F(e.resultExpr.AsExpr).D(" ")
}
if c.elseExpr != nil {
s.D("ELSE ").F(c.elseExpr.AsExpr).D(" ")
}
s.D("END")
}
type CaseWhenClause struct {
whenExpr, resultExpr AsExpr
}
func CaseWhen(whenExpr, resultExpr AsExpr) *CaseWhenClause {
return &CaseWhenClause{whenExpr: whenExpr, resultExpr: resultExpr}
}