Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

expression: make cast return error if cast binary literal to another character set #30537

Merged
merged 8 commits into from
Dec 13, 2021
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()
xiongjiwei marked this conversation as resolved.
Show resolved Hide resolved
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