Skip to content

Commit 7ca928b

Browse files
sgrebnovphillipleblanc
authored andcommitted
Improve scalar_to_sql to respect dialect timestamp type overrides (#73)
UPSTREAM NOTE: This PR was upstreamed in apache#14407 and is available in DF 46
1 parent 088729a commit 7ca928b

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

datafusion/sql/src/unparser/expr.rs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -965,10 +965,16 @@ impl Unparser<'_> {
965965
))?
966966
.to_string()
967967
};
968+
969+
let time_unit = match T::DATA_TYPE {
970+
DataType::Timestamp(unit, _) => unit,
971+
_ => return Err(internal_datafusion_err!("Expected Timestamp, got {:?}", T::DATA_TYPE)),
972+
};
973+
968974
Ok(ast::Expr::Cast {
969975
kind: ast::CastKind::Cast,
970976
expr: Box::new(ast::Expr::Value(SingleQuotedString(ts))),
971-
data_type: ast::DataType::Timestamp(None, TimezoneInfo::None),
977+
data_type: self.dialect.timestamp_cast_dtype(&time_unit, &None),
972978
format: None,
973979
})
974980
}
@@ -2579,6 +2585,32 @@ mod tests {
25792585
Ok(())
25802586
}
25812587

2588+
#[test]
2589+
fn custom_dialect_with_timestamp_cast_dtype_scalar_expr() -> Result<()> {
2590+
let default_dialect = CustomDialectBuilder::new().build();
2591+
let mysql_dialect = CustomDialectBuilder::new()
2592+
.with_timestamp_cast_dtype(
2593+
ast::DataType::Datetime(None),
2594+
ast::DataType::Datetime(None),
2595+
)
2596+
.build();
2597+
2598+
for (dialect, identifier) in [
2599+
(&default_dialect, "TIMESTAMP"),
2600+
(&mysql_dialect, "DATETIME"),
2601+
] {
2602+
let unparser = Unparser::new(dialect);
2603+
let expr = Expr::Literal(ScalarValue::TimestampMillisecond(Some(1738285549123), None));
2604+
let ast = unparser.expr_to_sql(&expr)?;
2605+
2606+
let actual = format!("{}", ast);
2607+
let expected = format!(r#"CAST('2025-01-31 01:05:49.123' AS {identifier})"#);
2608+
2609+
assert_eq!(actual, expected);
2610+
}
2611+
Ok(())
2612+
}
2613+
25822614
#[test]
25832615
fn custom_dialect_date32_ast_dtype() -> Result<()> {
25842616
let default_dialect = CustomDialectBuilder::default().build();

0 commit comments

Comments
 (0)