Skip to content

Commit b80080e

Browse files
authored
Improve Unparser (scalar_to_sql) to respect dialect timestamp type overrides (#14407)
1 parent 80cf58c commit b80080e

File tree

1 file changed

+41
-1
lines changed

1 file changed

+41
-1
lines changed

datafusion/sql/src/unparser/expr.rs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -965,10 +965,21 @@ impl Unparser<'_> {
965965
))?
966966
.to_string()
967967
};
968+
969+
let time_unit = match T::DATA_TYPE {
970+
DataType::Timestamp(unit, _) => unit,
971+
_ => {
972+
return Err(internal_datafusion_err!(
973+
"Expected Timestamp, got {:?}",
974+
T::DATA_TYPE
975+
))
976+
}
977+
};
978+
968979
Ok(ast::Expr::Cast {
969980
kind: ast::CastKind::Cast,
970981
expr: Box::new(ast::Expr::Value(SingleQuotedString(ts))),
971-
data_type: ast::DataType::Timestamp(None, TimezoneInfo::None),
982+
data_type: self.dialect.timestamp_cast_dtype(&time_unit, &None),
972983
format: None,
973984
})
974985
}
@@ -2581,6 +2592,35 @@ mod tests {
25812592
Ok(())
25822593
}
25832594

2595+
#[test]
2596+
fn custom_dialect_with_timestamp_cast_dtype_scalar_expr() -> Result<()> {
2597+
let default_dialect = CustomDialectBuilder::new().build();
2598+
let mysql_dialect = CustomDialectBuilder::new()
2599+
.with_timestamp_cast_dtype(
2600+
ast::DataType::Datetime(None),
2601+
ast::DataType::Datetime(None),
2602+
)
2603+
.build();
2604+
2605+
for (dialect, identifier) in [
2606+
(&default_dialect, "TIMESTAMP"),
2607+
(&mysql_dialect, "DATETIME"),
2608+
] {
2609+
let unparser = Unparser::new(dialect);
2610+
let expr = Expr::Literal(ScalarValue::TimestampMillisecond(
2611+
Some(1738285549123),
2612+
None,
2613+
));
2614+
let ast = unparser.expr_to_sql(&expr)?;
2615+
2616+
let actual = format!("{}", ast);
2617+
let expected = format!(r#"CAST('2025-01-31 01:05:49.123' AS {identifier})"#);
2618+
2619+
assert_eq!(actual, expected);
2620+
}
2621+
Ok(())
2622+
}
2623+
25842624
#[test]
25852625
fn custom_dialect_date32_ast_dtype() -> Result<()> {
25862626
let default_dialect = CustomDialectBuilder::default().build();

0 commit comments

Comments
 (0)