This repository was archived by the owner on Jan 28, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathnullif.go
66 lines (54 loc) · 1.48 KB
/
nullif.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
package function
import (
"fmt"
"github.com/src-d/go-mysql-server/sql"
"github.com/src-d/go-mysql-server/sql/expression"
)
// NullIf function compares two expressions and returns NULL if they are equal. Otherwise, the first expression is returned.
type NullIf struct {
expression.BinaryExpression
}
// NewNullIf returns a new NULLIF UDF
func NewNullIf(ex1, ex2 sql.Expression) sql.Expression {
return &NullIf{
expression.BinaryExpression{
Left: ex1,
Right: ex2,
},
}
}
// Eval implements the Expression interface.
func (f *NullIf) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
if sql.IsNull(f.Left) && sql.IsNull(f.Right) {
return sql.Null, nil
}
val, err := expression.NewEquals(f.Left, f.Right).Eval(ctx, row)
if err != nil {
return nil, err
}
if b, ok := val.(bool); ok && b {
return sql.Null, nil
}
return f.Left.Eval(ctx, row)
}
// Type implements the Expression interface.
func (f *NullIf) Type() sql.Type {
if sql.IsNull(f.Left) {
return sql.Null
}
return f.Left.Type()
}
// IsNullable implements the Expression interface.
func (f *NullIf) IsNullable() bool {
return true
}
func (f *NullIf) String() string {
return fmt.Sprintf("nullif(%s, %s)", f.Left, f.Right)
}
// WithChildren implements the Expression interface.
func (f *NullIf) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 2 {
return nil, sql.ErrInvalidChildrenNumber.New(f, len(children), 2)
}
return NewNullIf(children[0], children[1]), nil
}