Add support for CASE operator.
This commit is contained in:
parent
3367df247c
commit
4f9323ddca
18 changed files with 243 additions and 272 deletions
|
|
@ -1,5 +1,7 @@
|
|||
package sqlbuilder
|
||||
|
||||
import "errors"
|
||||
|
||||
type funcExpressionImpl struct {
|
||||
expressionInterfaceImpl
|
||||
|
||||
|
|
@ -63,3 +65,98 @@ func MAX(expression NumericExpression) NumericExpression {
|
|||
func SUM(expression NumericExpression) NumericExpression {
|
||||
return NewNumericFunc("SUM", expression)
|
||||
}
|
||||
|
||||
type caseInterface interface {
|
||||
Expression
|
||||
|
||||
WHEN(condition Expression) caseInterface
|
||||
THEN(then Expression) caseInterface
|
||||
ELSE(els Expression) caseInterface
|
||||
}
|
||||
|
||||
type caseExpression struct {
|
||||
expressionInterfaceImpl
|
||||
|
||||
expression Expression
|
||||
when []Expression
|
||||
then []Expression
|
||||
els Expression
|
||||
}
|
||||
|
||||
func CASE(expression ...Expression) caseInterface {
|
||||
caseExp := &caseExpression{}
|
||||
|
||||
if len(expression) == 1 {
|
||||
caseExp.expression = expression[0]
|
||||
}
|
||||
|
||||
caseExp.expressionInterfaceImpl.parent = caseExp
|
||||
|
||||
return caseExp
|
||||
}
|
||||
|
||||
func (c *caseExpression) WHEN(when Expression) caseInterface {
|
||||
c.when = append(c.when, when)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *caseExpression) THEN(then Expression) caseInterface {
|
||||
c.then = append(c.then, then)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *caseExpression) ELSE(els Expression) caseInterface {
|
||||
c.els = els
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *caseExpression) Serialize(out *queryData, options ...serializeOption) error {
|
||||
out.WriteString("(CASE")
|
||||
|
||||
if c.expression != nil {
|
||||
out.WriteString(" ")
|
||||
err := c.expression.Serialize(out)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(c.when) == 0 || len(c.then) == 0 {
|
||||
return errors.New("Invalid case statement. There should be at least one when/then expression pair. ")
|
||||
}
|
||||
|
||||
if len(c.when) != len(c.then) {
|
||||
return errors.New("When and then expression count mismatch. ")
|
||||
}
|
||||
|
||||
for i, when := range c.when {
|
||||
out.WriteString(" WHEN ")
|
||||
err := when.Serialize(out)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
out.WriteString(" THEN ")
|
||||
err = c.then[i].Serialize(out)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if c.els != nil {
|
||||
out.WriteString(" ELSE ")
|
||||
err := c.els.Serialize(out)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
out.WriteString(" END)")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue