Skip to content

Commit 49bc5c3

Browse files
author
Terran
committed
[CALCITE-7456] Improve the conversion of try_cast function with mssql
1 parent 2886ce1 commit 49bc5c3

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

core/src/main/java/org/apache/calcite/sql/dialect/MssqlSqlDialect.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,13 @@ public MssqlSqlDialect(Context context) {
172172
final SqlWriter.Frame frame = writer.startFunCall("CEILING");
173173
call.operand(0).unparse(writer, leftPrec, rightPrec);
174174
writer.endFunCall(frame);
175+
} else if (call.getKind() == (SqlKind.SAFE_CAST)) {
176+
// TRY_CAST is supported but not SAFE_CAST in MS SQL
177+
final SqlWriter.Frame frame = writer.startFunCall("TRY_CAST");
178+
call.operand(0).unparse(writer, leftPrec, rightPrec);
179+
writer.sep("as");
180+
call.operand(1).unparse(writer, leftPrec, rightPrec);
181+
writer.endFunCall(frame);
175182
} else {
176183
switch (call.getKind()) {
177184
case FLOOR:

core/src/test/java/org/apache/calcite/rel/rel2sql/RelToSqlConverterTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12025,4 +12025,16 @@ public Sql schema(CalciteAssert.SchemaSpec schemaSpec) {
1202512025
sql(query).withLibrary(SqlLibrary.HIVE).withHive().ok(expectedHive);
1202612026
sql(query).withLibrary(SqlLibrary.SPARK).withSpark().ok(expectedSpark);
1202712027
}
12028+
12029+
/** Test case for
12030+
* <a href="https://issues.apache.org/jira/browse/CALCITE-7456">[CALCITE-7456]
12031+
* Improve the conversion of try_cast function with mssql</a>. */
12032+
@Test void testTryCastWithMssql() {
12033+
final String query = "select TRY_CAST(\"gross_weight\" as bigint) as gross_weight_value\n"
12034+
+ "from \"product\"";
12035+
final String expectedSql = "SELECT TRY_CAST([gross_weight] AS BIGINT) AS [GROSS_WEIGHT_VALUE]"
12036+
+ "\nFROM [foodmart].[product]";
12037+
12038+
sql(query).withLibrary(SqlLibrary.MSSQL).withMssql().ok(expectedSql);
12039+
}
1202812040
}

0 commit comments

Comments
 (0)