[fix](cast)fix cast to char(N) error (#14168)

This commit is contained in:
starocean999
2022-11-11 11:27:51 +08:00
committed by GitHub
parent 883dfa38ab
commit 8e17fcef3f
5 changed files with 39 additions and 4 deletions

View File

@ -5561,7 +5561,23 @@ func_args_def ::=
cast_expr ::=
KW_CAST LPAREN expr:e KW_AS type_def:targetType RPAREN
{: RESULT = new CastExpr(targetType, e); :}
{:
CastExpr castExpr = new CastExpr(targetType, e);
if (targetType.getType().getLength() != -1
&& (targetType.getType().getPrimitiveType() == PrimitiveType.VARCHAR
|| targetType.getType().getPrimitiveType() == PrimitiveType.CHAR)) {
// transfer cast(xx as char(N)/varchar(N)) to substr(cast(xx as char), 1, N)
// this is just a workaround to make the result correct
ArrayList<Expr> exprs = new ArrayList<>();
exprs.add(castExpr);
exprs.add(new IntLiteral(1));
exprs.add(new IntLiteral(targetType.getType().getLength()));
RESULT = new FunctionCallExpr("substr", new FunctionParams(exprs));
}
else {
RESULT = castExpr;
}
:}
;
case_expr ::=

View File

@ -321,8 +321,12 @@ public class CastExpr extends Expr {
}
if (fn == null) {
throw new AnalysisException("Invalid type cast of " + getChild(0).toSql()
if (childType.isNull() && Type.canCastTo(childType, type)) {
return;
} else {
throw new AnalysisException("Invalid type cast of " + getChild(0).toSql()
+ " from " + childType + " to " + type);
}
}
if (PrimitiveType.typeWithPrecision.contains(type.getPrimitiveType())) {

View File

@ -110,7 +110,7 @@ public class FoldConstantsRule implements ExprRewriteRule {
if (expr instanceof CastExpr) {
CastExpr castExpr = (CastExpr) expr;
if (castExpr.getChild(0) instanceof NullLiteral) {
return expr;
return castExpr.getChild(0);
}
}

View File

@ -11,6 +11,12 @@
-- !sql --
\N
-- !sql --
\N
-- !sql --
20
-- !sql --
1
@ -23,3 +29,9 @@
-- !sql --
\N
-- !sql --
\N
-- !sql --
20

View File

@ -22,6 +22,8 @@ suite("test_cast_function") {
qt_sql """ select cast(cast ("11.2" as double) as bigint) """
qt_sql """ select cast ("0.0101031417" as datetime) """
qt_sql """ select cast ("0.0000031417" as datetime) """
qt_sql """ select cast (NULL AS CHAR(1)); """
qt_sql """ select cast ('20190101' AS CHAR(2)); """
sql """ SET enable_vectorized_engine = FALSE; """
@ -29,6 +31,7 @@ suite("test_cast_function") {
qt_sql """ select cast(cast ("11.2" as double) as bigint) """
qt_sql """ select cast ("0.0101031417" as datetime) """
qt_sql """ select cast ("0.0000031417" as datetime) """
qt_sql """ select cast (NULL AS CHAR(1)); """
qt_sql """ select cast ('20190101' AS CHAR(2)); """
}