This repository has been archived by the owner on Jan 28, 2021. It is now read-only.
/
trim_ltrim_rtrim.go
94 lines (79 loc) · 2.09 KB
/
trim_ltrim_rtrim.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
93
94
package function
import (
"fmt"
"reflect"
"strings"
"unicode"
"gopkg.in/src-d/go-mysql-server.v0/sql/expression"
"gopkg.in/src-d/go-mysql-server.v0/sql"
)
type trimType rune
const (
lTrimType trimType = 'l'
rTrimType trimType = 'r'
bTrimType trimType = 'b'
)
// NewTrimFunc returns a Trim creator function with a specific trimType.
func NewTrimFunc(tType trimType) func(e sql.Expression) sql.Expression {
return func(e sql.Expression) sql.Expression {
return NewTrim(tType, e)
}
}
// NewTrim creates a new Trim expression.
func NewTrim(tType trimType, str sql.Expression) sql.Expression {
return &Trim{expression.UnaryExpression{Child: str}, tType}
}
// Trim is a function that returns the string with prefix or suffix spaces removed based on the trimType
type Trim struct {
expression.UnaryExpression
trimType
}
// Type implements the Expression interface.
func (t *Trim) Type() sql.Type { return sql.Text }
func (t *Trim) String() string {
switch t.trimType {
case lTrimType:
return fmt.Sprintf("ltrim(%s)", t.Child)
case rTrimType:
return fmt.Sprintf("rtrim(%s)", t.Child)
default:
return fmt.Sprintf("trim(%s)", t.Child)
}
}
// IsNullable implements the Expression interface.
func (t *Trim) IsNullable() bool {
return t.Child.IsNullable()
}
// TransformUp implements the Expression interface.
func (t *Trim) TransformUp(f sql.TransformExprFunc) (sql.Expression, error) {
str, err := t.Child.TransformUp(f)
if err != nil {
return nil, err
}
return f(NewTrim(t.trimType, str))
}
// Eval implements the Expression interface.
func (t *Trim) Eval(
ctx *sql.Context,
row sql.Row,
) (interface{}, error) {
str, err := t.Child.Eval(ctx, row)
if err != nil {
return nil, err
}
if str == nil {
return nil, nil
}
str, err = sql.Text.Convert(str)
if err != nil {
return nil, sql.ErrInvalidType.New(reflect.TypeOf(str))
}
switch t.trimType {
case lTrimType:
return strings.TrimLeftFunc(str.(string), unicode.IsSpace), nil
case rTrimType:
return strings.TrimRightFunc(str.(string), unicode.IsSpace), nil
default:
return strings.TrimFunc(str.(string), unicode.IsSpace), nil
}
}