Apache DataFusion SQL Query Engine
ARROW-12277: [Rust][DataFusion] Implement Sum/Count/Min/Max aggregates for Timestamp(_,_)
Andrew Lamb32b4073101d7
diff --git a/rust/datafusion/src/execution/context.rs b/rust/datafusion/src/execution/context.rsindex ce0ea6d005..07d5b629e1 100644--- a/rust/datafusion/src/execution/context.rs+++ b/rust/datafusion/src/execution/context.rs@@ -1403,6 +1403,121 @@ mod tests {Ok(())}+ #[tokio::test]+ async fn aggregate_timestamps_sum() -> Result<()> {+ let tmp_dir = TempDir::new()?;+ let mut ctx = create_ctx(&tmp_dir, 1)?;+ ctx.register_table("t", test::table_with_timestamps())+ .unwrap();++ let results = plan_and_collect(+ &mut ctx,+ "SELECT sum(nanos), sum(micros), sum(millis), sum(secs) FROM t",+ )+ .await+ .unwrap_err();++ assert_eq!(results.to_string(), "Error during planning: Coercion from [Timestamp(Nanosecond, None)] to the signature Uniform(1, [Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64]) failed.");++ Ok(())+ }++ #[tokio::test]+ async fn aggregate_timestamps_count() -> Result<()> {+ let tmp_dir = TempDir::new()?;+ let mut ctx = create_ctx(&tmp_dir, 1)?;+ ctx.register_table("t", test::table_with_timestamps())+ .unwrap();++ let results = plan_and_collect(+ &mut ctx,+ "SELECT count(nanos), count(micros), count(millis), count(secs) FROM t",+ )+ .await+ .unwrap();++ let expected = vec![+ "+--------------+---------------+---------------+-------------+",+ "| COUNT(nanos) | COUNT(micros) | COUNT(millis) | COUNT(secs) |",+ "+--------------+---------------+---------------+-------------+",+ "| 3 | 3 | 3 | 3 |",+ "+--------------+---------------+---------------+-------------+",+ ];+ assert_batches_sorted_eq!(expected, &results);++ Ok(())+ }++ #[tokio::test]+ async fn aggregate_timestamps_min() -> Result<()> {+ let tmp_dir = TempDir::new()?;+ let mut ctx = create_ctx(&tmp_dir, 1)?;+ ctx.register_table("t", test::table_with_timestamps())+ .unwrap();++ let results = plan_and_collect(+ &mut ctx,+ "SELECT min(nanos), min(micros), min(millis), min(secs) FROM t",+ )+ .await+ .unwrap();++ let expected = vec![+ "+----------------------------+----------------------------+-------------------------+---------------------+",+ "| MIN(nanos) | MIN(micros) | MIN(millis) | MIN(secs) |",+ "+----------------------------+----------------------------+-------------------------+---------------------+",+ "| 2011-12-13 11:13:10.123450 | 2011-12-13 11:13:10.123450 | 2011-12-13 11:13:10.123 | 2011-12-13 11:13:10 |",+ "+----------------------------+----------------------------+-------------------------+---------------------+",+ ];+ assert_batches_sorted_eq!(expected, &results);++ Ok(())+ }++ #[tokio::test]+ async fn aggregate_timestamps_max() -> Result<()> {+ let tmp_dir = TempDir::new()?;+ let mut ctx = create_ctx(&tmp_dir, 1)?;+ ctx.register_table("t", test::table_with_timestamps())+ .unwrap();++ let results = plan_and_collect(+ &mut ctx,+ "SELECT max(nanos), max(micros), max(millis), max(secs) FROM t",+ )+ .await+ .unwrap();++ let expected = vec![+ "+-------------------------+-------------------------+-------------------------+---------------------+",+ "| MAX(nanos) | MAX(micros) | MAX(millis) | MAX(secs) |",+ "+-------------------------+-------------------------+-------------------------+---------------------+",+ "| 2021-01-01 05:11:10.432 | 2021-01-01 05:11:10.432 | 2021-01-01 05:11:10.432 | 2021-01-01 05:11:10 |",+ "+-------------------------+-------------------------+-------------------------+---------------------+",+];+ assert_batches_sorted_eq!(expected, &results);++ Ok(())+ }++ #[tokio::test]+ async fn aggregate_timestamps_avg() -> Result<()> {+ let tmp_dir = TempDir::new()?;+ let mut ctx = create_ctx(&tmp_dir, 1)?;+ ctx.register_table("t", test::table_with_timestamps())+ .unwrap();++ let results = plan_and_collect(+ &mut ctx,+ "SELECT avg(nanos), avg(micros), avg(millis), avg(secs) FROM t",+ )+ .await+ .unwrap_err();++ assert_eq!(results.to_string(), "Error during planning: Coercion from [Timestamp(Nanosecond, None)] to the signature Uniform(1, [Int8, Int16, Int32, Int64, UInt8, UInt16, UInt32, UInt64, Float32, Float64]) failed.");+ Ok(())+ }+#[tokio::test]async fn join_partitioned() -> Result<()> {// self join on partition id (workaround for duplicate column name)diff --git a/rust/datafusion/src/physical_plan/aggregates.rs b/rust/datafusion/src/physical_plan/aggregates.rsindex be90daa954..9417c7c8f0 100644--- a/rust/datafusion/src/physical_plan/aggregates.rs+++ b/rust/datafusion/src/physical_plan/aggregates.rs@@ -34,7 +34,7 @@ use super::{use crate::error::{DataFusionError, Result};use crate::physical_plan::distinct_expressions;use crate::physical_plan::expressions;-use arrow::datatypes::{DataType, Schema};+use arrow::datatypes::{DataType, Schema, TimeUnit};use expressions::{avg_return_type, sum_return_type};use std::{fmt, str::FromStr, sync::Arc};@@ -160,6 +160,8 @@ pub fn create_aggregate_expr(})}+static STRINGS: &[DataType] = &[DataType::Utf8, DataType::LargeUtf8];+static NUMERICS: &[DataType] = &[DataType::Int8,DataType::Int16,@@ -173,14 +175,25 @@ static NUMERICS: &[DataType] = &[DataType::Float64,];+static TIMESTAMPS: &[DataType] = &[+ DataType::Timestamp(TimeUnit::Second, None),+ DataType::Timestamp(TimeUnit::Millisecond, None),+ DataType::Timestamp(TimeUnit::Microsecond, None),+ DataType::Timestamp(TimeUnit::Nanosecond, None),+];+/// the signatures supported by the function `fun`.fn signature(fun: &AggregateFunction) -> Signature {// note: the physical expression must accept the type returned by this function or the execution panics.match fun {AggregateFunction::Count => Signature::Any(1),AggregateFunction::Min | AggregateFunction::Max => {- let mut valid = vec![DataType::Utf8, DataType::LargeUtf8];- valid.extend_from_slice(NUMERICS);+ let valid = STRINGS+ .iter()+ .chain(NUMERICS.iter())+ .chain(TIMESTAMPS.iter())+ .cloned()+ .collect::<Vec<_>>();Signature::Uniform(1, valid)}AggregateFunction::Avg | AggregateFunction::Sum => {diff --git a/rust/datafusion/src/physical_plan/datetime_expressions.rs b/rust/datafusion/src/physical_plan/datetime_expressions.rsindex 3d363ce97d..7b5816186f 100644--- a/rust/datafusion/src/physical_plan/datetime_expressions.rs+++ b/rust/datafusion/src/physical_plan/datetime_expressions.rs@@ -324,8 +324,8 @@ pub fn date_trunc(args: &[ColumnarValue]) -> Result<ColumnarValue> {Ok(match array {ColumnarValue::Scalar(scalar) => {- if let ScalarValue::TimeNanosecond(v) = scalar {- ColumnarValue::Scalar(ScalarValue::TimeNanosecond((f)(*v)?))+ if let ScalarValue::TimestampNanosecond(v) = scalar {+ ColumnarValue::Scalar(ScalarValue::TimestampNanosecond((f)(*v)?))} else {return Err(DataFusionError::Execution("array of `date_trunc` must be non-null scalar Utf8".to_string(),diff --git a/rust/datafusion/src/physical_plan/expressions/min_max.rs b/rust/datafusion/src/physical_plan/expressions/min_max.rsindex 2fd84a6cc7..5ed14610ad 100644--- a/rust/datafusion/src/physical_plan/expressions/min_max.rs+++ b/rust/datafusion/src/physical_plan/expressions/min_max.rs@@ -25,12 +25,13 @@ use crate::error::{DataFusionError, Result};use crate::physical_plan::{Accumulator, AggregateExpr, PhysicalExpr};use crate::scalar::ScalarValue;use arrow::compute;-use arrow::datatypes::DataType;+use arrow::datatypes::{DataType, TimeUnit};use arrow::{array::{ArrayRef, Float32Array, Float64Array, Int16Array, Int32Array, Int64Array,- Int8Array, LargeStringArray, StringArray, UInt16Array, UInt32Array, UInt64Array,- UInt8Array,+ Int8Array, LargeStringArray, StringArray, TimestampMicrosecondArray,+ TimestampMillisecondArray, TimestampNanosecondArray, TimestampSecondArray,+ UInt16Array, UInt32Array, UInt64Array, UInt8Array,},datatypes::Field,};@@ -128,6 +129,27 @@ macro_rules! min_max_batch {DataType::UInt32 => typed_min_max_batch!($VALUES, UInt32Array, UInt32, $OP),DataType::UInt16 => typed_min_max_batch!($VALUES, UInt16Array, UInt16, $OP),DataType::UInt8 => typed_min_max_batch!($VALUES, UInt8Array, UInt8, $OP),+ DataType::Timestamp(TimeUnit::Second, _) => {+ typed_min_max_batch!($VALUES, TimestampSecondArray, TimestampSecond, $OP)+ }+ DataType::Timestamp(TimeUnit::Millisecond, _) => typed_min_max_batch!(+ $VALUES,+ TimestampMillisecondArray,+ TimestampMillisecond,+ $OP+ ),+ DataType::Timestamp(TimeUnit::Microsecond, _) => typed_min_max_batch!(+ $VALUES,+ TimestampMicrosecondArray,+ TimestampMicrosecond,+ $OP+ ),+ DataType::Timestamp(TimeUnit::Nanosecond, _) => typed_min_max_batch!(+ $VALUES,+ TimestampNanosecondArray,+ TimestampNanosecond,+ $OP+ ),other => {// This should have been handled beforereturn Err(DataFusionError::Internal(format!(@@ -229,6 +251,27 @@ macro_rules! min_max {(ScalarValue::LargeUtf8(lhs), ScalarValue::LargeUtf8(rhs)) => {typed_min_max_string!(lhs, rhs, LargeUtf8, $OP)}+ (ScalarValue::TimestampSecond(lhs), ScalarValue::TimestampSecond(rhs)) => {+ typed_min_max!(lhs, rhs, TimestampSecond, $OP)+ }+ (+ ScalarValue::TimestampMillisecond(lhs),+ ScalarValue::TimestampMillisecond(rhs),+ ) => {+ typed_min_max!(lhs, rhs, TimestampMillisecond, $OP)+ }+ (+ ScalarValue::TimestampMicrosecond(lhs),+ ScalarValue::TimestampMicrosecond(rhs),+ ) => {+ typed_min_max!(lhs, rhs, TimestampMicrosecond, $OP)+ }+ (+ ScalarValue::TimestampNanosecond(lhs),+ ScalarValue::TimestampNanosecond(rhs),+ ) => {+ typed_min_max!(lhs, rhs, TimestampNanosecond, $OP)+ }e => {return Err(DataFusionError::Internal(format!("MIN/MAX is not expected to receive a scalar {:?}",diff --git a/rust/datafusion/src/physical_plan/group_scalar.rs b/rust/datafusion/src/physical_plan/group_scalar.rsindex a55e1d7a9a..f4987ae3a7 100644--- a/rust/datafusion/src/physical_plan/group_scalar.rs+++ b/rust/datafusion/src/physical_plan/group_scalar.rs@@ -64,9 +64,15 @@ impl TryFrom<&ScalarValue> for GroupByScalar {ScalarValue::UInt16(Some(v)) => GroupByScalar::UInt16(*v),ScalarValue::UInt32(Some(v)) => GroupByScalar::UInt32(*v),ScalarValue::UInt64(Some(v)) => GroupByScalar::UInt64(*v),- ScalarValue::TimeMillisecond(Some(v)) => GroupByScalar::TimeMillisecond(*v),- ScalarValue::TimeMicrosecond(Some(v)) => GroupByScalar::TimeMicrosecond(*v),- ScalarValue::TimeNanosecond(Some(v)) => GroupByScalar::TimeNanosecond(*v),+ ScalarValue::TimestampMillisecond(Some(v)) => {+ GroupByScalar::TimeMillisecond(*v)+ }+ ScalarValue::TimestampMicrosecond(Some(v)) => {+ GroupByScalar::TimeMicrosecond(*v)+ }+ ScalarValue::TimestampNanosecond(Some(v)) => {+ GroupByScalar::TimeNanosecond(*v)+ }ScalarValue::Utf8(Some(v)) => GroupByScalar::Utf8(Box::new(v.clone())),ScalarValue::Float32(None)| ScalarValue::Float64(None)@@ -110,9 +116,15 @@ impl From<&GroupByScalar> for ScalarValue {GroupByScalar::UInt32(v) => ScalarValue::UInt32(Some(*v)),GroupByScalar::UInt64(v) => ScalarValue::UInt64(Some(*v)),GroupByScalar::Utf8(v) => ScalarValue::Utf8(Some(v.to_string())),- GroupByScalar::TimeMillisecond(v) => ScalarValue::TimeMillisecond(Some(*v)),- GroupByScalar::TimeMicrosecond(v) => ScalarValue::TimeMicrosecond(Some(*v)),- GroupByScalar::TimeNanosecond(v) => ScalarValue::TimeNanosecond(Some(*v)),+ GroupByScalar::TimeMillisecond(v) => {+ ScalarValue::TimestampMillisecond(Some(*v))+ }+ GroupByScalar::TimeMicrosecond(v) => {+ ScalarValue::TimestampMicrosecond(Some(*v))+ }+ GroupByScalar::TimeNanosecond(v) => {+ ScalarValue::TimestampNanosecond(Some(*v))+ }GroupByScalar::Date32(v) => ScalarValue::Date32(Some(*v)),}}diff --git a/rust/datafusion/src/scalar.rs b/rust/datafusion/src/scalar.rsindex b236775849..833f707e97 100644--- a/rust/datafusion/src/scalar.rs+++ b/rust/datafusion/src/scalar.rs@@ -19,16 +19,21 @@use std::{convert::TryFrom, fmt, iter::repeat, sync::Arc};-use arrow::array::{- ArrayRef, Int16Builder, Int32Builder, Int64Builder, Int8Builder, ListBuilder,- TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,- UInt16Builder, UInt32Builder, UInt64Builder, UInt8Builder,-};use arrow::datatypes::{DataType, Field, IntervalUnit, TimeUnit};use arrow::{array::*,datatypes::{ArrowNativeType, Float32Type, TimestampNanosecondType},};+use arrow::{+ array::{+ ArrayRef, Int16Builder, Int32Builder, Int64Builder, Int8Builder, ListBuilder,+ TimestampMicrosecondArray, TimestampMillisecondArray, TimestampNanosecondArray,+ UInt16Builder, UInt32Builder, UInt64Builder, UInt8Builder,+ },+ datatypes::{+ TimestampMicrosecondType, TimestampMillisecondType, TimestampSecondType,+ },+};use crate::error::{DataFusionError, Result};@@ -72,12 +77,14 @@ pub enum ScalarValue {Date32(Option<i32>),/// Date stored as a signed 64bit intDate64(Option<i64>),+ /// Timestamp Second+ TimestampSecond(Option<i64>),/// Timestamp Milliseconds- TimeMillisecond(Option<i64>),+ TimestampMillisecond(Option<i64>),/// Timestamp Microseconds- TimeMicrosecond(Option<i64>),+ TimestampMicrosecond(Option<i64>),/// Timestamp Nanoseconds- TimeNanosecond(Option<i64>),+ TimestampNanosecond(Option<i64>),/// Interval with YearMonth unitIntervalYearMonth(Option<i32>),/// Interval with DayTime unit@@ -145,15 +152,18 @@ impl ScalarValue {ScalarValue::Int16(_) => DataType::Int16,ScalarValue::Int32(_) => DataType::Int32,ScalarValue::Int64(_) => DataType::Int64,- ScalarValue::TimeMicrosecond(_) => {+ ScalarValue::TimestampSecond(_) => {+ DataType::Timestamp(TimeUnit::Second, None)+ }+ ScalarValue::TimestampMillisecond(_) => {+ DataType::Timestamp(TimeUnit::Millisecond, None)+ }+ ScalarValue::TimestampMicrosecond(_) => {DataType::Timestamp(TimeUnit::Microsecond, None)}- ScalarValue::TimeNanosecond(_) => {+ ScalarValue::TimestampNanosecond(_) => {DataType::Timestamp(TimeUnit::Nanosecond, None)}- ScalarValue::TimeMillisecond(_) => {- DataType::Timestamp(TimeUnit::Millisecond, None)- }ScalarValue::Float32(_) => DataType::Float32,ScalarValue::Float64(_) => DataType::Float64,ScalarValue::Utf8(_) => DataType::Utf8,@@ -209,9 +219,9 @@ impl ScalarValue {| ScalarValue::Utf8(None)| ScalarValue::LargeUtf8(None)| ScalarValue::List(None, _)- | ScalarValue::TimeMillisecond(None)- | ScalarValue::TimeMicrosecond(None)- | ScalarValue::TimeNanosecond(None)+ | ScalarValue::TimestampMillisecond(None)+ | ScalarValue::TimestampMicrosecond(None)+ | ScalarValue::TimestampNanosecond(None))}@@ -266,7 +276,15 @@ impl ScalarValue {Some(value) => Arc::new(UInt64Array::from_value(*value, size)),None => new_null_array(&DataType::UInt64, size),},- ScalarValue::TimeMillisecond(e) => match e {+ ScalarValue::TimestampSecond(e) => match e {+ Some(value) => Arc::new(TimestampSecondArray::from_iter_values(+ repeat(*value).take(size),+ )),+ None => {+ new_null_array(&DataType::Timestamp(TimeUnit::Second, None), size)+ }+ },+ ScalarValue::TimestampMillisecond(e) => match e {Some(value) => Arc::new(TimestampMillisecondArray::from_iter_values(repeat(*value).take(size),)),@@ -275,7 +293,7 @@ impl ScalarValue {size,),},- ScalarValue::TimeMicrosecond(e) => match e {+ ScalarValue::TimestampMicrosecond(e) => match e {Some(value) => {Arc::new(TimestampMicrosecondArray::from_value(*value, size))}@@ -284,7 +302,7 @@ impl ScalarValue {size,),},- ScalarValue::TimeNanosecond(e) => match e {+ ScalarValue::TimestampNanosecond(e) => match e {Some(value) => {Arc::new(TimestampNanosecondArray::from_value(*value, size))}@@ -403,6 +421,28 @@ impl ScalarValue {DataType::Date64 => {typed_cast!(array, index, Date64Array, Date64)}+ DataType::Timestamp(TimeUnit::Second, _) => {+ typed_cast!(array, index, TimestampSecondArray, TimestampSecond)+ }+ DataType::Timestamp(TimeUnit::Millisecond, _) => {+ typed_cast!(+ array,+ index,+ TimestampMillisecondArray,+ TimestampMillisecond+ )+ }+ DataType::Timestamp(TimeUnit::Microsecond, _) => {+ typed_cast!(+ array,+ index,+ TimestampMicrosecondArray,+ TimestampMicrosecond+ )+ }+ DataType::Timestamp(TimeUnit::Nanosecond, _) => {+ typed_cast!(array, index, TimestampNanosecondArray, TimestampNanosecond)+ }other => {return Err(DataFusionError::NotImplemented(format!("Can't create a scalar of array of type \"{:?}\"",@@ -525,7 +565,7 @@ impl TryFrom<ScalarValue> for i64 {fn try_from(value: ScalarValue) -> Result<Self> {match value {ScalarValue::Int64(Some(inner_value))- | ScalarValue::TimeNanosecond(Some(inner_value)) => Ok(inner_value),+ | ScalarValue::TimestampNanosecond(Some(inner_value)) => Ok(inner_value),_ => Err(DataFusionError::Internal(format!("Cannot convert {:?} to {}",value,@@ -561,6 +601,18 @@ impl TryFrom<&DataType> for ScalarValue {DataType::UInt64 => ScalarValue::UInt64(None),DataType::Utf8 => ScalarValue::Utf8(None),DataType::LargeUtf8 => ScalarValue::LargeUtf8(None),+ DataType::Timestamp(TimeUnit::Second, _) => {+ ScalarValue::TimestampSecond(None)+ }+ DataType::Timestamp(TimeUnit::Millisecond, _) => {+ ScalarValue::TimestampMillisecond(None)+ }+ DataType::Timestamp(TimeUnit::Microsecond, _) => {+ ScalarValue::TimestampMicrosecond(None)+ }+ DataType::Timestamp(TimeUnit::Nanosecond, _) => {+ ScalarValue::TimestampNanosecond(None)+ }DataType::List(ref nested_type) => {ScalarValue::List(None, nested_type.data_type().clone())}@@ -597,9 +649,10 @@ impl fmt::Display for ScalarValue {ScalarValue::UInt16(e) => format_option!(f, e)?,ScalarValue::UInt32(e) => format_option!(f, e)?,ScalarValue::UInt64(e) => format_option!(f, e)?,- ScalarValue::TimeMillisecond(e) => format_option!(f, e)?,- ScalarValue::TimeMicrosecond(e) => format_option!(f, e)?,- ScalarValue::TimeNanosecond(e) => format_option!(f, e)?,+ ScalarValue::TimestampSecond(e) => format_option!(f, e)?,+ ScalarValue::TimestampMillisecond(e) => format_option!(f, e)?,+ ScalarValue::TimestampMicrosecond(e) => format_option!(f, e)?,+ ScalarValue::TimestampNanosecond(e) => format_option!(f, e)?,ScalarValue::Utf8(e) => format_option!(f, e)?,ScalarValue::LargeUtf8(e) => format_option!(f, e)?,ScalarValue::Binary(e) => match e {@@ -658,9 +711,16 @@ impl fmt::Debug for ScalarValue {ScalarValue::UInt16(_) => write!(f, "UInt16({})", self),ScalarValue::UInt32(_) => write!(f, "UInt32({})", self),ScalarValue::UInt64(_) => write!(f, "UInt64({})", self),- ScalarValue::TimeMillisecond(_) => write!(f, "TimeMillisecond({})", self),- ScalarValue::TimeMicrosecond(_) => write!(f, "TimeMicrosecond({})", self),- ScalarValue::TimeNanosecond(_) => write!(f, "TimeNanosecond({})", self),+ ScalarValue::TimestampSecond(_) => write!(f, "TimestampSecond({})", self),+ ScalarValue::TimestampMillisecond(_) => {+ write!(f, "TimestampMillisecond({})", self)+ }+ ScalarValue::TimestampMicrosecond(_) => {+ write!(f, "TimestampMicrosecond({})", self)+ }+ ScalarValue::TimestampNanosecond(_) => {+ write!(f, "TimestampNanosecond({})", self)+ }ScalarValue::Utf8(None) => write!(f, "Utf8({})", self),ScalarValue::Utf8(Some(_)) => write!(f, "Utf8(\"{}\")", self),ScalarValue::LargeUtf8(None) => write!(f, "LargeUtf8({})", self),@@ -694,9 +754,27 @@ impl ScalarType<f32> for Float32Type {}}+impl ScalarType<i64> for TimestampSecondType {+ fn scalar(r: Option<i64>) -> ScalarValue {+ ScalarValue::TimestampSecond(r)+ }+}++impl ScalarType<i64> for TimestampMillisecondType {+ fn scalar(r: Option<i64>) -> ScalarValue {+ ScalarValue::TimestampMillisecond(r)+ }+}++impl ScalarType<i64> for TimestampMicrosecondType {+ fn scalar(r: Option<i64>) -> ScalarValue {+ ScalarValue::TimestampMicrosecond(r)+ }+}+impl ScalarType<i64> for TimestampNanosecondType {fn scalar(r: Option<i64>) -> ScalarValue {- ScalarValue::TimeNanosecond(r)+ ScalarValue::TimestampNanosecond(r)}}diff --git a/rust/datafusion/src/test/mod.rs b/rust/datafusion/src/test/mod.rsindex 5773618948..926a692261 100644--- a/rust/datafusion/src/test/mod.rs+++ b/rust/datafusion/src/test/mod.rs@@ -20,7 +20,10 @@use crate::datasource::{MemTable, TableProvider};use crate::error::Result;use crate::logical_plan::{LogicalPlan, LogicalPlanBuilder};-use array::ArrayRef;+use array::{+ Array, ArrayRef, StringArray, TimestampMicrosecondArray, TimestampMillisecondArray,+ TimestampNanosecondArray, TimestampSecondArray,+};use arrow::array::{self, Int32Array};use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;@@ -182,6 +185,93 @@ pub fn make_partition(sz: i32) -> RecordBatch {RecordBatch::try_new(schema, vec![arr]).unwrap()}+/// Return a new table provider containing all of the supported timestamp types+pub fn table_with_timestamps() -> Arc<dyn TableProvider> {+ let batch = make_timestamps();+ let schema = batch.schema();+ let partitions = vec![vec![batch]];+ Arc::new(MemTable::try_new(schema, partitions).unwrap())+}++/// Return record batch with all of the supported timestamp types+/// values+///+/// Columns are named:+/// "nanos" --> TimestampNanosecondArray+/// "micros" --> TimestampMicrosecondArray+/// "millis" --> TimestampMillisecondArray+/// "secs" --> TimestampSecondArray+/// "names" --> StringArray+pub fn make_timestamps() -> RecordBatch {+ let ts_strings = vec![+ Some("2018-11-13T17:11:10.011375885995"),+ Some("2011-12-13T11:13:10.12345"),+ None,+ Some("2021-1-1T05:11:10.432"),+ ];++ let ts_nanos = ts_strings+ .into_iter()+ .map(|t| {+ t.map(|t| {+ t.parse::<chrono::NaiveDateTime>()+ .unwrap()+ .timestamp_nanos()+ })+ })+ .collect::<Vec<_>>();++ let ts_micros = ts_nanos+ .iter()+ .map(|t| t.as_ref().map(|ts_nanos| ts_nanos / 1000))+ .collect::<Vec<_>>();++ let ts_millis = ts_nanos+ .iter()+ .map(|t| t.as_ref().map(|ts_nanos| ts_nanos / 1000000))+ .collect::<Vec<_>>();++ let ts_secs = ts_nanos+ .iter()+ .map(|t| t.as_ref().map(|ts_nanos| ts_nanos / 1000000000))+ .collect::<Vec<_>>();++ let names = ts_nanos+ .iter()+ .enumerate()+ .map(|(i, _)| format!("Row {}", i))+ .collect::<Vec<_>>();++ let arr_nanos = TimestampNanosecondArray::from_opt_vec(ts_nanos, None);+ let arr_micros = TimestampMicrosecondArray::from_opt_vec(ts_micros, None);+ let arr_millis = TimestampMillisecondArray::from_opt_vec(ts_millis, None);+ let arr_secs = TimestampSecondArray::from_opt_vec(ts_secs, None);++ let names = names.iter().map(|s| s.as_str()).collect::<Vec<_>>();+ let arr_names = StringArray::from(names);++ let schema = Schema::new(vec![+ Field::new("nanos", arr_nanos.data_type().clone(), false),+ Field::new("micros", arr_micros.data_type().clone(), false),+ Field::new("millis", arr_millis.data_type().clone(), false),+ Field::new("secs", arr_secs.data_type().clone(), false),+ Field::new("name", arr_names.data_type().clone(), false),+ ]);+ let schema = Arc::new(schema);++ RecordBatch::try_new(+ schema,+ vec![+ Arc::new(arr_nanos),+ Arc::new(arr_micros),+ Arc::new(arr_millis),+ Arc::new(arr_secs),+ Arc::new(arr_names),+ ],+ )+ .unwrap()+}+pub mod exec;pub mod user_defined;pub mod variable;