expression: make cast return error if cast binary literal to another character set (#30537)
This commit is contained in:
@ -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
|
||||
|
||||
@ -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)
|
||||
|
||||
Reference in New Issue
Block a user