Skip to content

Commit e98c739

Browse files
authored
expression: let cast function supports explicit set charset (#55724) (#56088)
close #55677
1 parent cdd7546 commit e98c739

File tree

11 files changed

+131
-15
lines changed

11 files changed

+131
-15
lines changed

pkg/expression/bench_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1452,7 +1452,7 @@ func genVecBuiltinFuncBenchCase(ctx sessionctx.Context, funcName string, testCas
14521452
case types.ETJson:
14531453
fc = &castAsJSONFunctionClass{baseFunctionClass{ast.Cast, 1, 1}, tp}
14541454
case types.ETString:
1455-
fc = &castAsStringFunctionClass{baseFunctionClass{ast.Cast, 1, 1}, tp}
1455+
fc = &castAsStringFunctionClass{baseFunctionClass{ast.Cast, 1, 1}, tp, false}
14561456
}
14571457
baseFunc, err = fc.getFunction(ctx, cols)
14581458
} else if funcName == ast.GetVar {

pkg/expression/builtin.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -485,6 +485,36 @@ func newBaseBuiltinCastFunc(builtinFunc baseBuiltinFunc, inUnion bool) baseBuilt
485485
}
486486
}
487487

488+
func newBaseBuiltinCastFunc4String(ctx sessionctx.Context, funcName string, args []Expression, tp *types.FieldType, isExplicitCharset bool) (baseBuiltinFunc, error) {
489+
var bf baseBuiltinFunc
490+
var err error
491+
if isExplicitCharset {
492+
bf = baseBuiltinFunc{
493+
bufAllocator: newLocalColumnPool(),
494+
childrenVectorizedOnce: new(sync.Once),
495+
496+
args: args,
497+
ctx: ctx,
498+
tp: tp,
499+
}
500+
bf.SetCharsetAndCollation(tp.GetCharset(), tp.GetCollate())
501+
bf.setCollator(collate.GetCollator(tp.GetCollate()))
502+
bf.SetCoercibility(CoercibilityExplicit)
503+
bf.SetExplicitCharset(true)
504+
if tp.GetCharset() == charset.CharsetASCII {
505+
bf.SetRepertoire(ASCII)
506+
} else {
507+
bf.SetRepertoire(UNICODE)
508+
}
509+
} else {
510+
bf, err = newBaseBuiltinFunc(ctx, funcName, args, tp)
511+
if err != nil {
512+
return baseBuiltinFunc{}, err
513+
}
514+
}
515+
return bf, nil
516+
}
517+
488518
// vecBuiltinFunc contains all vectorized methods for a builtin function.
489519
type vecBuiltinFunc interface {
490520
// vectorized returns if this builtin function itself supports vectorized evaluation.

pkg/expression/builtin_cast.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -272,14 +272,15 @@ func (c *castAsDecimalFunctionClass) getFunction(ctx sessionctx.Context, args []
272272
type castAsStringFunctionClass struct {
273273
baseFunctionClass
274274

275-
tp *types.FieldType
275+
tp *types.FieldType
276+
isExplicitCharset bool
276277
}
277278

278279
func (c *castAsStringFunctionClass) getFunction(ctx sessionctx.Context, args []Expression) (sig builtinFunc, err error) {
279280
if err := c.verifyArgs(args); err != nil {
280281
return nil, err
281282
}
282-
bf, err := newBaseBuiltinFunc(ctx, c.funcName, args, c.tp)
283+
bf, err := newBaseBuiltinCastFunc4String(ctx, c.funcName, args, c.tp, c.isExplicitCharset)
283284
if err != nil {
284285
return nil, err
285286
}
@@ -2089,13 +2090,13 @@ func BuildCastCollationFunction(ctx sessionctx.Context, expr Expression, ec *Exp
20892090

20902091
// BuildCastFunction builds a CAST ScalarFunction from the Expression.
20912092
func BuildCastFunction(ctx sessionctx.Context, expr Expression, tp *types.FieldType) (res Expression) {
2092-
res, err := BuildCastFunctionWithCheck(ctx, expr, tp)
2093+
res, err := BuildCastFunctionWithCheck(ctx, expr, tp, false)
20932094
terror.Log(err)
20942095
return
20952096
}
20962097

20972098
// BuildCastFunctionWithCheck builds a CAST ScalarFunction from the Expression and return error if any.
2098-
func BuildCastFunctionWithCheck(ctx sessionctx.Context, expr Expression, tp *types.FieldType) (res Expression, err error) {
2099+
func BuildCastFunctionWithCheck(ctx sessionctx.Context, expr Expression, tp *types.FieldType, isExplicitCharset bool) (res Expression, err error) {
20992100
argType := expr.GetType()
21002101
// If source argument's nullable, then target type should be nullable
21012102
if !mysql.HasNotNullFlag(argType.GetFlag()) {
@@ -2121,7 +2122,7 @@ func BuildCastFunctionWithCheck(ctx sessionctx.Context, expr Expression, tp *typ
21212122
fc = &castAsJSONFunctionClass{baseFunctionClass{ast.Cast, 1, 1}, tp}
21222123
}
21232124
case types.ETString:
2124-
fc = &castAsStringFunctionClass{baseFunctionClass{ast.Cast, 1, 1}, tp}
2125+
fc = &castAsStringFunctionClass{baseFunctionClass{ast.Cast, 1, 1}, tp, isExplicitCharset}
21252126
if expr.GetType().GetType() == mysql.TypeBit {
21262127
tp.SetFlen((expr.GetType().GetFlen() + 7) / 8)
21272128
}

pkg/expression/builtin_cast_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ func TestCastFuncSig(t *testing.T) {
646646
tp := types.NewFieldType(mysql.TypeVarString)
647647
tp.SetCharset(charset.CharsetBin)
648648
args := []Expression{c.before}
649-
stringFunc, err := newBaseBuiltinFunc(ctx, "", args, tp)
649+
stringFunc, err := newBaseBuiltinCastFunc4String(ctx, "", args, tp, false)
650650
require.NoError(t, err)
651651
switch i {
652652
case 0:
@@ -732,7 +732,7 @@ func TestCastFuncSig(t *testing.T) {
732732
tp := types.NewFieldType(mysql.TypeVarString)
733733
tp.SetFlen(c.flen)
734734
tp.SetCharset(charset.CharsetBin)
735-
stringFunc, err := newBaseBuiltinFunc(ctx, "", args, tp)
735+
stringFunc, err := newBaseBuiltinCastFunc4String(ctx, "", args, tp, false)
736736
require.NoError(t, err)
737737
switch i {
738738
case 0:
@@ -1083,7 +1083,7 @@ func TestCastFuncSig(t *testing.T) {
10831083
// null case
10841084
args := []Expression{&Column{RetType: types.NewFieldType(mysql.TypeDouble), Index: 0}}
10851085
row := chunk.MutRowFromDatums([]types.Datum{types.NewDatum(nil)})
1086-
bf, err := newBaseBuiltinFunc(ctx, "", args, types.NewFieldType(mysql.TypeVarString))
1086+
bf, err := newBaseBuiltinCastFunc4String(ctx, "", args, types.NewFieldType(mysql.TypeVarString), false)
10871087
require.NoError(t, err)
10881088
sig = &builtinCastRealAsStringSig{bf}
10891089
sRes, isNull, err := sig.evalString(row.ToRow())
@@ -1680,7 +1680,7 @@ func TestCastArrayFunc(t *testing.T) {
16801680
},
16811681
}
16821682
for _, tt := range tbl {
1683-
f, err := BuildCastFunctionWithCheck(ctx, datumsToConstants(types.MakeDatums(types.CreateBinaryJSON(tt.input)))[0], tt.tp)
1683+
f, err := BuildCastFunctionWithCheck(ctx, datumsToConstants(types.MakeDatums(types.CreateBinaryJSON(tt.input)))[0], tt.tp, false)
16841684
if !tt.buildFuncSuccess {
16851685
require.Error(t, err, tt.input)
16861686
continue

pkg/expression/collation.go

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ type collationInfo struct {
4444

4545
charset string
4646
collation string
47+
48+
isExplicitCharset bool
4749
}
4850

4951
func (c *collationInfo) HasCoercibility() bool {
@@ -76,6 +78,14 @@ func (c *collationInfo) CharsetAndCollation() (string, string) {
7678
return c.charset, c.collation
7779
}
7880

81+
func (c *collationInfo) IsExplicitCharset() bool {
82+
return c.isExplicitCharset
83+
}
84+
85+
func (c *collationInfo) SetExplicitCharset(explicit bool) {
86+
c.isExplicitCharset = explicit
87+
}
88+
7989
// CollationInfo contains all interfaces about dealing with collation.
8090
type CollationInfo interface {
8191
// HasCoercibility returns if the Coercibility value is initialized.
@@ -98,6 +108,12 @@ type CollationInfo interface {
98108

99109
// SetCharsetAndCollation sets charset and collation.
100110
SetCharsetAndCollation(chs, coll string)
111+
112+
// IsExplicitCharset return the charset is explicit set or not.
113+
IsExplicitCharset() bool
114+
115+
// SetExplicitCharset set the charset is explicit or not.
116+
SetExplicitCharset(bool)
101117
}
102118

103119
// Coercibility values are used to check whether the collation of one item can be coerced to
@@ -246,9 +262,8 @@ func deriveCollation(ctx sessionctx.Context, funcName string, args []Expression,
246262
case ast.Cast:
247263
// We assume all the cast are implicit.
248264
ec = &ExprCollation{args[0].Coercibility(), args[0].Repertoire(), args[0].GetType().GetCharset(), args[0].GetType().GetCollate()}
249-
// Non-string type cast to string type should use @@character_set_connection and @@collation_connection.
250-
// String type cast to string type should keep its original charset and collation. It should not happen.
251-
if retType == types.ETString && argTps[0] != types.ETString {
265+
// Cast to string type should use @@character_set_connection and @@collation_connection.
266+
if retType == types.ETString {
252267
ec.Charset, ec.Collation = ctx.GetSessionVars().GetCharsetInfo()
253268
}
254269
return ec, nil

pkg/expression/scalar_function.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -779,6 +779,16 @@ func (sf *ScalarFunction) SetRepertoire(r Repertoire) {
779779
sf.Function.SetRepertoire(r)
780780
}
781781

782+
// IsExplicitCharset return the charset is explicit set or not.
783+
func (sf *ScalarFunction) IsExplicitCharset() bool {
784+
return sf.Function.IsExplicitCharset()
785+
}
786+
787+
// SetExplicitCharset set the charset is explicit or not.
788+
func (sf *ScalarFunction) SetExplicitCharset(explicit bool) {
789+
sf.Function.SetExplicitCharset(explicit)
790+
}
791+
782792
const emptyScalarFunctionSize = int64(unsafe.Sizeof(ScalarFunction{}))
783793

784794
// MemoryUsage return the memory usage of ScalarFunction

pkg/expression/util.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -455,8 +455,10 @@ func ColumnSubstituteImpl(expr Expression, schema *Schema, newExprs []Expression
455455
if substituted {
456456
flag := v.RetType.GetFlag()
457457
var e Expression
458+
var err error
458459
if v.FuncName.L == ast.Cast {
459-
e = BuildCastFunction(v.GetCtx(), newArg, v.RetType)
460+
e, err = BuildCastFunctionWithCheck(v.GetCtx(), newArg, v.RetType, v.Function.IsExplicitCharset())
461+
terror.Log(err)
460462
} else {
461463
// for grouping function recreation, use clone (meta included) instead of newFunction
462464
e = v.Clone()

pkg/expression/util_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -588,6 +588,8 @@ func (m *MockExpr) Coercibility() Coercibility
588588
func (m *MockExpr) SetCoercibility(Coercibility) {}
589589
func (m *MockExpr) Repertoire() Repertoire { return UNICODE }
590590
func (m *MockExpr) SetRepertoire(Repertoire) {}
591+
func (m *MockExpr) IsExplicitCharset() bool { return false }
592+
func (m *MockExpr) SetExplicitCharset(bool) {}
591593

592594
func (m *MockExpr) CharsetAndCollation() (string, string) {
593595
return "", ""

pkg/planner/core/expression_rewriter.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1290,7 +1290,7 @@ func (er *expressionRewriter) Leave(originInNode ast.Node) (retNode ast.Node, ok
12901290
return retNode, false
12911291
}
12921292

1293-
castFunction, err := expression.BuildCastFunctionWithCheck(er.sctx, arg, v.Tp)
1293+
castFunction, err := expression.BuildCastFunctionWithCheck(er.sctx, arg, v.Tp, v.ExplicitCharSet)
12941294
if err != nil {
12951295
er.err = err
12961296
return retNode, false

tests/integrationtest/r/expression/cast.result

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,3 +129,33 @@ select 1.194192591e9 > t0.c0 from t0;
129129
select 1.194192591e9 < t0.c0 from t0;
130130
1.194192591e9 < t0.c0
131131
0
132+
drop table if exists test;
133+
CREATE TABLE `test` (
134+
`id` bigint(20) NOT NULL,
135+
`update_user` varchar(32) DEFAULT NULL,
136+
PRIMARY KEY (`id`) /*T![clustered_index] CLUSTERED */
137+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
138+
insert into test values(1,'张三');
139+
insert into test values(2,'李四');
140+
insert into test values(3,'张三');
141+
insert into test values(4,'李四');
142+
select * from test order by cast(update_user as char character set gbk) desc , id limit 3;
143+
id update_user
144+
1 张三
145+
3 张三
146+
2 李四
147+
drop table test;
148+
CREATE TABLE `test` (
149+
`id` bigint NOT NULL,
150+
`update_user` varchar(32) CHARACTER SET gbk COLLATE gbk_chinese_ci DEFAULT NULL,
151+
PRIMARY KEY (`id`)
152+
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
153+
insert into test values(1,'张三');
154+
insert into test values(2,'李四');
155+
insert into test values(3,'张三');
156+
insert into test values(4,'李四');
157+
select * from test order by cast(update_user as char) desc , id limit 3;
158+
id update_user
159+
2 李四
160+
4 李四
161+
1 张三

0 commit comments

Comments
 (0)