Skip to content

Apache DataFusion SQL Query Engine

fix: keep fractional seconds in MySQL timestamp casts (#26886)

hozan23c9988fe4982c
diff --git a/datafusion/sql/src/unparser/dialect.rs b/datafusion/sql/src/unparser/dialect.rs
index b3be233b3d..e7b3339a12 100644
--- a/datafusion/sql/src/unparser/dialect.rs
+++ b/datafusion/sql/src/unparser/dialect.rs
@@ -587,10 +587,15 @@ impl Dialect for MySqlDialect {
fn timestamp_cast_dtype(
&self,
- _time_unit: &TimeUnit,
+ time_unit: &TimeUnit,
_tz: &Option<Arc<str>>,
) -> ast::DataType {
- ast::DataType::Datetime(None)
+ let precision = match time_unit {
+ TimeUnit::Second => None,
+ TimeUnit::Millisecond => Some(3),
+ TimeUnit::Microsecond | TimeUnit::Nanosecond => Some(6),
+ };
+ ast::DataType::Datetime(precision)
}
fn requires_derived_table_alias(&self) -> bool {
diff --git a/datafusion/sql/src/unparser/expr.rs b/datafusion/sql/src/unparser/expr.rs
index df034a27f4..093ba80d29 100644
--- a/datafusion/sql/src/unparser/expr.rs
+++ b/datafusion/sql/src/unparser/expr.rs
@@ -3106,6 +3106,44 @@ mod tests {
Ok(())
}
+ // MySQL `DATETIME` without precision is `DATETIME(0)` and rounds the
+ // literal to whole seconds, which breaks equality and keyset seeks on
+ // sub-second timestamps. The MySQL dialect must carry the unit's precision.
+ #[test]
+ fn mysql_timestamp_cast_keeps_fractional_precision() -> Result<()> {
+ let unparser = Unparser::new(&MySqlDialect {});
+
+ for (scalar, expected) in [
+ (
+ ScalarValue::TimestampSecond(Some(1789980940), None),
+ "CAST('2026-09-21 08:55:40' AS DATETIME)",
+ ),
+ (
+ ScalarValue::TimestampMillisecond(Some(1789980940006), None),
+ "CAST('2026-09-21 08:55:40.006' AS DATETIME(3))",
+ ),
+ (
+ ScalarValue::TimestampMicrosecond(Some(1789980940006000), None),
+ "CAST('2026-09-21 08:55:40.006' AS DATETIME(6))",
+ ),
+ (
+ ScalarValue::TimestampNanosecond(Some(1789980940006000000), None),
+ "CAST('2026-09-21 08:55:40.006' AS DATETIME(6))",
+ ),
+ ] {
+ let ast = unparser.expr_to_sql(&Expr::Literal(scalar, None))?;
+ assert_eq!(format!("{ast}"), expected);
+ }
+
+ let expr = Expr::Cast(Cast::new(
+ Box::new(col("a")),
+ DataType::Timestamp(TimeUnit::Microsecond, None),
+ ));
+ let ast = unparser.expr_to_sql(&expr)?;
+ assert_eq!(format!("{ast}"), "CAST(`a` AS DATETIME(6))");
+ Ok(())
+ }
+
#[test]
fn custom_dialect_date32_ast_dtype() -> Result<()> {
let default_dialect = CustomDialectBuilder::default().build();