Skip to content

Commit

Permalink
expression: make cast return error if cast binary literal to another …
Browse files Browse the repository at this point in the history
…character set (#30537)
  • Loading branch information
xiongjiwei committed Dec 13, 2021
1 parent d3833c2 commit e8577c7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
5 changes: 5 additions & 0 deletions expression/builtin_cast.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,11 @@ func (c *castAsStringFunctionClass) getFunction(ctx sessionctx.Context, args []E
}
bf.tp = c.tp
if args[0].GetType().Hybrid() || IsBinaryLiteral(args[0]) {
// When cast from binary to some other charsets, we should check if the binary is valid or not.
// so we build a from_binary function to do this check.
ft := args[0].GetType().Clone()
ft.Charset, ft.Collate = c.tp.Charset, c.tp.Collate
bf.args[0] = BuildFromBinaryFunction(ctx, args[0], ft)
sig = &builtinCastStringAsStringSig{bf}
sig.setPbCode(tipb.ScalarFuncSig_CastStringAsString)
return sig, nil
Expand Down
31 changes: 31 additions & 0 deletions expression/builtin_cast_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1398,6 +1398,37 @@ func TestWrapWithCastAsDuration(t *testing.T) {
}
}

func TestWrapWithCastAsString(t *testing.T) {
t.Parallel()
ctx := createContext(t)

cases := []struct {
expr Expression
err bool
ret string
}{
{
&Constant{RetType: types.NewFieldTypeWithCollation(mysql.TypeVarString, charset.CollationBin, 1), Value: types.NewBinaryLiteralDatum([]byte{0x91})},
true,
"",
},
{
&Constant{RetType: types.NewFieldTypeWithCollation(mysql.TypeVarString, charset.CollationBin, 1), Value: types.NewBinaryLiteralDatum([]byte{0x61})},
false,
"a",
},
}
for _, c := range cases {
expr := BuildCastFunction(ctx, c.expr, types.NewFieldType(mysql.TypeVarString))
res, _, err := expr.EvalString(ctx, chunk.Row{})
if c.err {
require.Error(t, err)
} else {
require.Equal(t, c.ret, res)
}
}
}

func TestWrapWithCastAsJSON(t *testing.T) {
t.Parallel()
ctx := createContext(t)
Expand Down

0 comments on commit e8577c7

Please sign in to comment.