Skip to content

Commit

Permalink
evaluator,parser: support ASCII(). (pingcap#309)
Browse files Browse the repository at this point in the history
* evaluator: add a builtin function wanted by pingcap#310.

* parser: update parser for ASCII().
  • Loading branch information
zyguan committed Apr 13, 2016
1 parent baa3968 commit 6b9509d
Show file tree
Hide file tree
Showing 8 changed files with 9,053 additions and 8,949 deletions.
1 change: 1 addition & 0 deletions evaluator/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ var Funcs = map[string]Func{
"date_arith": {builtinDateArith, 3, 3},

// string functions
"ascii": {builtinASCII, 1, 1},
"concat": {builtinConcat, 1, -1},
"concat_ws": {builtinConcatWS, 2, -1},
"left": {builtinLeft, 2, 2},
Expand Down
19 changes: 19 additions & 0 deletions evaluator/builtin_string.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,25 @@ func builtinLength(args []types.Datum, _ context.Context) (d types.Datum, err er
}
}

// See: https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_ascii
func builtinASCII(args []types.Datum, _ context.Context) (d types.Datum, err error) {
switch args[0].Kind() {
case types.KindNull:
return d, nil
default:
s, err := args[0].ToString()
if err != nil {
return d, errors.Trace(err)
}
if len(s) == 0 {
d.SetInt64(0)
return d, nil
}
d.SetInt64(int64(s[0]))
return d, nil
}
}

// See: https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_concat
func builtinConcat(args []types.Datum, _ context.Context) (d types.Datum, err error) {
var s []byte
Expand Down
27 changes: 27 additions & 0 deletions evaluator/builtin_string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,33 @@ func (s *testEvaluatorSuite) TestLength(c *C) {
}
}

func (s *testEvaluatorSuite) TestASCII(c *C) {
defer testleak.AfterTest(c)()
v, err := builtinASCII(types.MakeDatums([]interface{}{nil}...), nil)
c.Assert(err, IsNil)
c.Assert(v.Kind(), Equals, types.KindNull)

for _, t := range []struct {
Input interface{}
Expected int64
}{
{"", 0},
{"A", 65},
{"你好", 228},
{1, 49},
{1.2, 49},
{true, 49},
{false, 48},
} {
v, err = builtinASCII(types.MakeDatums(t.Input), nil)
c.Assert(err, IsNil)
c.Assert(v.GetInt64(), Equals, t.Expected)
}

v, err = builtinASCII(types.MakeDatums([]interface{}{errors.New("must error")}...), nil)
c.Assert(err, NotNil)
}

func (s *testEvaluatorSuite) TestConcat(c *C) {
defer testleak.AfterTest(c)()
args := []interface{}{nil}
Expand Down
Loading

0 comments on commit 6b9509d

Please sign in to comment.