Apache DataFusion SQL Query Engine
support `date_trunc` with `millisecond` and `microsecond` and keep the same type as the input (#5818)
Alex Huang9ceff97c34d7
diff --git a/datafusion/core/tests/sql/timestamp.rs b/datafusion/core/tests/sql/timestamp.rsindex afc1932b74..d6fffddcbf 100644--- a/datafusion/core/tests/sql/timestamp.rs+++ b/datafusion/core/tests/sql/timestamp.rs@@ -704,6 +704,58 @@ async fn cast_timestamp_before_1970() -> Result<()> {Ok(())}+#[tokio::test]+async fn test_arrow_typeof() -> Result<()> {+ let ctx = SessionContext::new();++ let sql = "select arrow_typeof(date_trunc('minute', to_timestamp_seconds(61)));";+ let actual = execute_to_batches(&ctx, sql).await;++ let expected = vec![+ "+----------------------------------------------------------------------+",+ "| arrowtypeof(datetrunc(Utf8(\"minute\"),totimestampseconds(Int64(61)))) |",+ "+----------------------------------------------------------------------+",+ "| Timestamp(Second, None) |",+ "+----------------------------------------------------------------------+",+ ];+ assert_batches_eq!(expected, &actual);++ let sql = "select arrow_typeof(date_trunc('second', to_timestamp_millis(61)));";+ let actual = execute_to_batches(&ctx, sql).await;+ let expected = vec![+ "+---------------------------------------------------------------------+",+ "| arrowtypeof(datetrunc(Utf8(\"second\"),totimestampmillis(Int64(61)))) |",+ "+---------------------------------------------------------------------+",+ "| Timestamp(Millisecond, None) |",+ "+---------------------------------------------------------------------+",+ ];+ assert_batches_eq!(expected, &actual);++ let sql = "select arrow_typeof(date_trunc('millisecond', to_timestamp_micros(61)));";+ let actual = execute_to_batches(&ctx, sql).await;+ let expected = vec![+ "+--------------------------------------------------------------------------+",+ "| arrowtypeof(datetrunc(Utf8(\"millisecond\"),totimestampmicros(Int64(61)))) |",+ "+--------------------------------------------------------------------------+",+ "| Timestamp(Microsecond, None) |",+ "+--------------------------------------------------------------------------+",+ ];+ assert_batches_eq!(expected, &actual);++ let sql = "select arrow_typeof(date_trunc('microsecond', to_timestamp(61)));";+ let actual = execute_to_batches(&ctx, sql).await;+ let expected = vec![+ "+--------------------------------------------------------------------+",+ "| arrowtypeof(datetrunc(Utf8(\"microsecond\"),totimestamp(Int64(61)))) |",+ "+--------------------------------------------------------------------+",+ "| Timestamp(Nanosecond, None) |",+ "+--------------------------------------------------------------------+",+ ];+ assert_batches_eq!(expected, &actual);++ Ok(())+}+#[tokio::test]async fn cast_timestamp_to_timestamptz() -> Result<()> {let ctx = SessionContext::new();diff --git a/datafusion/expr/src/function.rs b/datafusion/expr/src/function.rsindex 81740f10ff..9604e4d1dc 100644--- a/datafusion/expr/src/function.rs+++ b/datafusion/expr/src/function.rs@@ -132,9 +132,24 @@ pub fn return_type(BuiltinScalarFunction::Concat => Ok(DataType::Utf8),BuiltinScalarFunction::ConcatWithSeparator => Ok(DataType::Utf8),BuiltinScalarFunction::DatePart => Ok(DataType::Float64),- BuiltinScalarFunction::DateTrunc => {- Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))- }+ BuiltinScalarFunction::DateTrunc => match input_expr_types[1] {+ DataType::Timestamp(TimeUnit::Nanosecond, _) | DataType::Utf8 => {+ Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))+ }+ DataType::Timestamp(TimeUnit::Microsecond, _) => {+ Ok(DataType::Timestamp(TimeUnit::Microsecond, None))+ }+ DataType::Timestamp(TimeUnit::Millisecond, _) => {+ Ok(DataType::Timestamp(TimeUnit::Millisecond, None))+ }+ DataType::Timestamp(TimeUnit::Second, _) => {+ Ok(DataType::Timestamp(TimeUnit::Second, None))+ }+ _ => Err(DataFusionError::Internal(+ "The date_trunc function can only accept timestamp as the second arg."+ .to_string(),+ )),+ },BuiltinScalarFunction::DateBin => {Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))}diff --git a/datafusion/physical-expr/src/datetime_expressions.rs b/datafusion/physical-expr/src/datetime_expressions.rsindex c0df41df61..c71a6141f0 100644--- a/datafusion/physical-expr/src/datetime_expressions.rs+++ b/datafusion/physical-expr/src/datetime_expressions.rs@@ -222,7 +222,7 @@ fn date_trunc_single(granularity: &str, value: i64) -> Result<i64> {})?.with_nanosecond(0);let value = match granularity {- "second" => value,+ "second" | "millisecond" | "microsecond" => value,"minute" => value.and_then(|d| d.with_second(0)),"hour" => value.and_then(|d| d.with_second(0))@@ -280,10 +280,41 @@ pub fn date_trunc(args: &[ColumnarValue]) -> Result<ColumnarValue> {Ok(match array {ColumnarValue::Scalar(ScalarValue::TimestampNanosecond(v, tz_opt)) => {- ColumnarValue::Scalar(ScalarValue::TimestampNanosecond(- (f)(*v)?,- tz_opt.clone(),- ))+ let nano = (f)(*v)?;+ match granularity.as_str() {+ "minute" => {+ // cast to second+ let second = ScalarValue::TimestampSecond(+ Some(nano.unwrap() / 1_000_000_000),+ tz_opt.clone(),+ );+ ColumnarValue::Scalar(second)+ }+ "second" => {+ // cast to millisecond+ let mill = ScalarValue::TimestampMillisecond(+ Some(nano.unwrap() / 1_000_000),+ tz_opt.clone(),+ );+ ColumnarValue::Scalar(mill)+ }+ "millisecond" => {+ // cast to microsecond+ let micro = ScalarValue::TimestampMicrosecond(+ Some(nano.unwrap() / 1_000),+ tz_opt.clone(),+ );+ ColumnarValue::Scalar(micro)+ }+ _ => {+ // cast to nanosecond+ let nano = ScalarValue::TimestampNanosecond(+ Some(nano.unwrap()),+ tz_opt.clone(),+ );+ ColumnarValue::Scalar(nano)+ }+ }}ColumnarValue::Array(array) => {let array = as_timestamp_nanosecond_array(array)?;