branch-2.1: [fix](Nereids) fix double literal to string literal cast problem #49416 (#49523)

Cherry-picked from #49416

Co-authored-by: LiBinfeng <libinfeng@selectdb.com>
This commit is contained in:
github-actions[bot]
2025-03-28 11:49:02 +08:00
committed by GitHub
parent 4645084ab1
commit 57f04a7b9b
2 changed files with 74 additions and 0 deletions

View File

@ -267,8 +267,20 @@ public abstract class Literal extends Expression implements LeafExpression, Comp
return new CharLiteral(desc, ((CharType) targetType).getLen());
}
} else if (targetType.isVarcharType()) {
if (this.dataType.isDoubleType() || this.dataType.isFloatType()) {
int pointZeroIndex = findPointZeroIndex(desc);
if (pointZeroIndex > -1) {
return new VarcharLiteral(desc.substring(0, pointZeroIndex), ((VarcharType) targetType).getLen());
}
}
return new VarcharLiteral(desc, ((VarcharType) targetType).getLen());
} else if (targetType instanceof StringType) {
if (this.dataType.isDoubleType() || this.dataType.isFloatType()) {
int pointZeroIndex = findPointZeroIndex(desc);
if (pointZeroIndex > -1) {
return new StringLiteral(desc.substring(0, pointZeroIndex));
}
}
return new StringLiteral(desc);
} else if (targetType.isDateType()) {
return new DateLiteral(desc);
@ -292,6 +304,19 @@ public abstract class Literal extends Expression implements LeafExpression, Comp
throw new AnalysisException("cannot cast " + desc + " from type " + this.dataType + " to type " + targetType);
}
private static int findPointZeroIndex(String str) {
int pointIndex = -1;
for (int i = 0; i < str.length(); ++i) {
char c = str.charAt(i);
if (pointIndex > 0 && c != '0') {
return -1;
} else if (pointIndex == -1 && c == '.') {
pointIndex = i;
}
}
return pointIndex;
}
/** fromLegacyLiteral */
public static Literal fromLegacyLiteral(LiteralExpr literalExpr, Type type) {
DataType dataType = DataType.fromCatalogType(type);