Apache DataFusion SQL Query Engine
ARROW-9944: [Rust][DataFusion] Implement to_timestamp function
alamb880246cd6bb9
diff --git a/rust/datafusion/Cargo.toml b/rust/datafusion/Cargo.tomlindex c5c7900a63..39568ff608 100644--- a/rust/datafusion/Cargo.toml+++ b/rust/datafusion/Cargo.toml@@ -53,6 +53,7 @@ rustyline = {version = "6.0", optional = true}crossbeam = "0.7"paste = "0.1"num_cpus = "1.13.0"+chrono = "0.4"[dev-dependencies]criterion = "0.3"diff --git a/rust/datafusion/README.md b/rust/datafusion/README.mdindex 015f5f7da6..a6b305afb2 100644--- a/rust/datafusion/README.md+++ b/rust/datafusion/README.md@@ -57,7 +57,10 @@ DataFusion includes a simple command-line interactive SQL utility. See the [CLI- String functions- [x] Length- [x] Concatenate-- [ ] Common date/time functions+- Common date/time functions+ - [ ] Basic date functions+ - [ ] Basic time functions+ - [x] Basic timestamp functions- [x] Sorting- [ ] Nested types- [ ] Listsdiff --git a/rust/datafusion/src/physical_plan/datetime_expressions.rs b/rust/datafusion/src/physical_plan/datetime_expressions.rsnew file mode 100644index 0000000000..998cddc6b9--- /dev/null+++ b/rust/datafusion/src/physical_plan/datetime_expressions.rs@@ -0,0 +1,329 @@+// Licensed to the Apache Software Foundation (ASF) under one+// or more contributor license agreements. See the NOTICE file+// distributed with this work for additional information+// regarding copyright ownership. The ASF licenses this file+// to you under the Apache License, Version 2.0 (the+// "License"); you may not use this file except in compliance+// with the License. You may obtain a copy of the License at+//+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing,+// software distributed under the License is distributed on an+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+// KIND, either express or implied. See the License for the+// specific language governing permissions and limitations+// under the License.++//! DateTime expressions++use std::sync::Arc;++use crate::error::{ExecutionError, Result};+use arrow::{+ array::{Array, ArrayData, ArrayRef, StringArray, TimestampNanosecondArray},+ buffer::Buffer,+ datatypes::{DataType, TimeUnit, ToByteSlice},+};+use chrono::prelude::*;++#[inline]+/// Accepts a string in RFC3339 / ISO8601 standard format and some+/// variants and converts it to a nanosecond precision timestamp.+///+/// Implements the `to_timestamp` function to convert a string to a+/// timestamp, following the model of spark SQL’s to_`timestamp`.+///+/// In addition to RFC3339 / ISO8601 standard tiemstamps, it also+/// accepts strings that use a space ` ` to separate the date and time+/// as well as strings that have no explicit timezone offset.+///+/// Examples of accepted inputs:+/// * `1997-01-31T09:26:56.123Z` # RCF3339+/// * `1997-01-31T09:26:56.123-05:00` # RCF3339+/// * `1997-01-31 09:26:56.123-05:00` # close to RCF3339 but with a space rather than T+/// * `1997-01-31T09:26:56.123` # close to RCF3339 but no timezone offset specified+/// * `1997-01-31 09:26:56.123` # close to RCF3339 but uses a space and no timezone offset+//+/// Internally, this function uses the `chrono` library for the+/// datetime parsing+///+/// We hope to extend this function in the future with a second+/// parameter to specifying the format string.+///+/// ## Timestamp Precision+///+/// DataFusion uses the maximum precision timestamps supported by+/// Arrow (nanoseconds stored as a 64-bit integer) timestamps. This+/// means the range of dates that timestamps can represent is ~1677 AD+/// to 2262 AM+///+///+/// ## Timezone / Offset Handling+///+/// By using the Arrow format, DataFusion inherits Arrow’s handling of+/// timestamp values. Specifically, the stored numerical values of+/// timestamps are stored compared to offset UTC.+///+/// This function intertprets strings without an explicit time zone as+/// timestamps with offsets of the local time on the machine that ran+/// the datafusion query+///+/// For example, `1997-01-31 09:26:56.123Z` is interpreted as UTC, as+/// it has an explicit timezone specifier (“Z” for Zulu/UTC)+///+/// `1997-01-31T09:26:56.123` is interpreted as a local timestamp in+/// the timezone of the machine that ran DataFusion. For example, if+/// the system timezone is set to Americas/New_York (UTC-5) the+/// timestamp will be interpreted as though it were+/// `1997-01-31T09:26:56.123-05:00`+fn string_to_timestamp_nanos(s: &str) -> Result<i64> {+ // Fast path: RFC3339 timestamp (with a T)+ // Example: 2020-09-08T13:42:29.190855Z+ if let Ok(ts) = DateTime::parse_from_rfc3339(s) {+ return Ok(ts.timestamp_nanos());+ }++ // Implement quasi-RFC3339 support by trying to parse the+ // timestamp with various other format specifiers to to support+ // separating the date and time with a space ' ' rather than 'T' to be+ // (more) compatible with Apache Spark SQL++ // timezone offset, using ' ' as a separator+ // Example: 2020-09-08 13:42:29.190855-05:00+ if let Ok(ts) = DateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S%.f%:z") {+ return Ok(ts.timestamp_nanos());+ }++ // with an explict Z, using ' ' as a separator+ // Example: 2020-09-08 13:42:29Z+ if let Ok(ts) = Utc.datetime_from_str(s, "%Y-%m-%d %H:%M:%S%.fZ") {+ return Ok(ts.timestamp_nanos());+ }++ // Support timestamps without an explicit timezone offset, again+ // to be compatible with what Apache Spark SQL does.++ // without a timezone specifier as a local time, using T as a separator+ // Example: 2020-09-08T13:42:29.190855+ if let Ok(ts) = NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S.%f") {+ return Ok(ts.timestamp_nanos());+ }++ // without a timezone specifier as a local time, using ' ' as a separator+ // Example: 2020-09-08 13:42:29.190855+ if let Ok(ts) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S.%f") {+ return Ok(ts.timestamp_nanos());+ }++ // Note we don't pass along the error message from the underlying+ // chrono parsing because we tried several different format+ // strings and we don't know which the user was trying to+ // match. Ths any of the specific error messages is likely to be+ // be more confusing than helpful+ Err(ExecutionError::General(format!(+ "Error parsing '{}' as timestamp",+ s+ )))+}++/// convert an array of strings into `Timestamp(Nanosecond, None)`+pub fn to_timestamp(args: &[ArrayRef]) -> Result<TimestampNanosecondArray> {+ let num_rows = args[0].len();+ let string_args =+ &args[0]+ .as_any()+ .downcast_ref::<StringArray>()+ .ok_or_else(|| {+ ExecutionError::General(format!(+ "Internal error: could not cast to_timestamp input to StringArray"+ ))+ })?;++ let result = (0..num_rows)+ .map(|i| {+ if string_args.is_null(i) {+ // NB: Since we use the same null bitset as the input,+ // the output for this value will be ignored, but we+ // need some value in the array we are building.+ Ok(0)+ } else {+ string_to_timestamp_nanos(string_args.value(i))+ }+ })+ .collect::<Result<Vec<_>>>()?;++ let data = ArrayData::new(+ DataType::Timestamp(TimeUnit::Nanosecond, None),+ num_rows,+ Some(string_args.null_count()),+ string_args.data().null_buffer().cloned(),+ 0,+ vec![Buffer::from(result.to_byte_slice())],+ vec![],+ );++ Ok(TimestampNanosecondArray::from(Arc::new(data)))+}++#[cfg(test)]+mod tests {+ use std::sync::Arc;++ use arrow::array::Int64Array;++ use super::*;++ #[test]+ fn string_to_timestamp_timezone() -> Result<()> {+ // Explicit timezone+ assert_eq!(+ 1599572549190855000,+ parse_timestamp("2020-09-08T13:42:29.190855+00:00")?+ );+ assert_eq!(+ 1599572549190855000,+ parse_timestamp("2020-09-08T13:42:29.190855Z")?+ );+ assert_eq!(+ 1599572549000000000,+ parse_timestamp("2020-09-08T13:42:29Z")?+ ); // no fractional part+ assert_eq!(+ 1599590549190855000,+ parse_timestamp("2020-09-08T13:42:29.190855-05:00")?+ );+ Ok(())+ }++ #[test]+ fn string_to_timestamp_timezone_space() -> Result<()> {+ // Ensure space rather than T between time and date is accepted+ assert_eq!(+ 1599572549190855000,+ parse_timestamp("2020-09-08 13:42:29.190855+00:00")?+ );+ assert_eq!(+ 1599572549190855000,+ parse_timestamp("2020-09-08 13:42:29.190855Z")?+ );+ assert_eq!(+ 1599572549000000000,+ parse_timestamp("2020-09-08 13:42:29Z")?+ ); // no fractional part+ assert_eq!(+ 1599590549190855000,+ parse_timestamp("2020-09-08 13:42:29.190855-05:00")?+ );+ Ok(())+ }++ #[test]+ fn string_to_timestamp_no_timezone() -> Result<()> {+ let expected_date_time = NaiveDateTime::new(+ NaiveDate::from_ymd(2020, 09, 08),+ NaiveTime::from_hms_nano(13, 42, 29, 190855),+ )+ .timestamp_nanos();++ // Ensure both T and ' ' variants work+ assert_eq!(+ expected_date_time,+ parse_timestamp("2020-09-08T13:42:29.190855")?+ );++ assert_eq!(+ expected_date_time,+ parse_timestamp("2020-09-08 13:42:29.190855")?+ );+ Ok(())+ }++ #[test]+ fn string_to_timestamp_invalid() -> Result<()> {+ // Test parsing invalid formats++ // It would be nice to make these messages better+ expect_timestamp_parse_error("", "Error parsing '' as timestamp");+ expect_timestamp_parse_error("SS", "Error parsing 'SS' as timestamp");+ expect_timestamp_parse_error(+ "Wed, 18 Feb 2015 23:16:09 GMT",+ "Error parsing 'Wed, 18 Feb 2015 23:16:09 GMT' as timestamp",+ );++ Ok(())+ }++ // Parse a timestamp to timestamp int with a useful human readable error message+ fn parse_timestamp(s: &str) -> Result<i64> {+ let result = string_to_timestamp_nanos(s);+ if let Err(e) = &result {+ eprintln!("Error parsing timestamp '{}': {:?}", s, e);+ }+ result+ }++ fn expect_timestamp_parse_error(s: &str, expected_err: &str) {+ match string_to_timestamp_nanos(s) {+ Ok(v) => assert!(+ false,+ "Expected error '{}' while parsing '{}', but parsed {} instead",+ expected_err, s, v+ ),+ Err(e) => {+ assert!(e.to_string().contains(expected_err),+ "Can not find expected error '{}' while parsing '{}'. Actual error '{}'",+ expected_err, s, e);+ }+ }+ }++ #[test]+ fn to_timestamp_arrays_and_nulls() -> Result<()> {+ // ensure that arrow array implementation is wired up and handles nulls correctly++ let mut string_builder = StringArray::builder(2);+ let mut ts_builder = TimestampNanosecondArray::builder(2);++ string_builder.append_value("2020-09-08T13:42:29.190855Z")?;+ ts_builder.append_value(1599572549190855000)?;++ string_builder.append_null()?;+ ts_builder.append_null()?;++ let string_array = Arc::new(string_builder.finish());+ let parsed_timestamps = to_timestamp(&[string_array])+ .expect("that to_timestamp parsed values without error");++ let expected_timestamps = ts_builder.finish();++ assert_eq!(parsed_timestamps.len(), 2);+ assert_eq!(expected_timestamps, parsed_timestamps);+ Ok(())+ }++ #[test]+ fn to_timestamp_invalid_input_type() -> Result<()> {+ // pass the wrong type of input array to to_timestamp and test+ // that we get an error.++ let mut builder = Int64Array::builder(1);+ builder.append_value(1)?;+ let int64array = Arc::new(builder.finish());++ let expected_err =+ "Internal error: could not cast to_timestamp input to StringArray";+ match to_timestamp(&[int64array]) {+ Ok(_) => panic!("Expected error but got success"),+ Err(e) => {+ assert!(+ e.to_string().contains(expected_err),+ "Can not find expected error '{}'. Actual error '{}'",+ expected_err,+ e+ );+ }+ }+ Ok(())+ }+}diff --git a/rust/datafusion/src/physical_plan/functions.rs b/rust/datafusion/src/physical_plan/functions.rsindex 7f1e4fc4e7..06ce949b91 100644--- a/rust/datafusion/src/physical_plan/functions.rs+++ b/rust/datafusion/src/physical_plan/functions.rs@@ -34,11 +34,13 @@ use super::{PhysicalExpr,};use crate::error::{ExecutionError, Result};+use crate::physical_plan::datetime_expressions;use crate::physical_plan::math_expressions;use crate::physical_plan::string_expressions;use arrow::{array::ArrayRef,compute::kernels::length::length,+ datatypes::TimeUnit,datatypes::{DataType, Schema},record_batch::RecordBatch,};@@ -112,6 +114,8 @@ pub enum BuiltinScalarFunction {Length,/// concatConcat,+ /// to_timestamp+ ToTimestamp,}impl fmt::Display for BuiltinScalarFunction {@@ -144,6 +148,7 @@ impl FromStr for BuiltinScalarFunction {"signum" => BuiltinScalarFunction::Signum,"length" => BuiltinScalarFunction::Length,"concat" => BuiltinScalarFunction::Concat,+ "to_timestamp" => BuiltinScalarFunction::ToTimestamp,_ => {return Err(ExecutionError::General(format!("There is no built-in function named {}",@@ -173,12 +178,15 @@ pub fn return_type());}- // the return type after coercion.- // for now, this is type-independent, but there will be built-in functions whose return type- // depends on the incoming type.+ // the return type of the built in function. Eventually there+ // will be built-in functions whose return type depends on the+ // incoming type.match fun {BuiltinScalarFunction::Length => Ok(DataType::UInt32),BuiltinScalarFunction::Concat => Ok(DataType::Utf8),+ BuiltinScalarFunction::ToTimestamp => {+ Ok(DataType::Timestamp(TimeUnit::Nanosecond, None))+ }_ => Ok(DataType::Float64),}}@@ -212,6 +220,9 @@ pub fn create_physical_expr(BuiltinScalarFunction::Concat => {|args| Ok(Arc::new(string_expressions::concatenate(args)?))}+ BuiltinScalarFunction::ToTimestamp => {+ |args| Ok(Arc::new(datetime_expressions::to_timestamp(args)?))+ }});// coercelet args = coerce(args, input_schema, &signature(fun))?;@@ -237,6 +248,7 @@ fn signature(fun: &BuiltinScalarFunction) -> Signature {match fun {BuiltinScalarFunction::Length => Signature::Uniform(1, vec![DataType::Utf8]),BuiltinScalarFunction::Concat => Signature::Variadic(vec![DataType::Utf8]),+ BuiltinScalarFunction::ToTimestamp => Signature::Uniform(1, vec![DataType::Utf8]),// math expressions expect 1 argument of type f64 or f32// priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we// return the best approximation for it (in f64).diff --git a/rust/datafusion/src/physical_plan/mod.rs b/rust/datafusion/src/physical_plan/mod.rsindex 4977ae3b9a..e2265cd1d5 100644--- a/rust/datafusion/src/physical_plan/mod.rs+++ b/rust/datafusion/src/physical_plan/mod.rs@@ -132,6 +132,7 @@ pub trait Accumulator: Debug {pub mod common;pub mod csv;+pub mod datetime_expressions;pub mod empty;pub mod explain;pub mod expressions;diff --git a/rust/datafusion/tests/sql.rs b/rust/datafusion/tests/sql.rsindex 050660c64a..33385d53be 100644--- a/rust/datafusion/tests/sql.rs+++ b/rust/datafusion/tests/sql.rs@@ -21,9 +21,9 @@ use std::sync::Arc;extern crate arrow;extern crate datafusion;-use arrow::array::*;use arrow::datatypes::{DataType, Field, Schema, SchemaRef};use arrow::record_batch::RecordBatch;+use arrow::{array::*, datatypes::TimeUnit};use datafusion::datasource::{csv::CsvReadOptions, MemTable};use datafusion::error::Result;@@ -761,3 +761,39 @@ fn like() -> Result<()> {assert_eq!(expected, actual);Ok(())}++fn make_timestamp_nano_table() -> Result<Box<MemTable>> {+ let schema = Arc::new(Schema::new(vec![+ Field::new("ts", DataType::Timestamp(TimeUnit::Nanosecond, None), false),+ Field::new("value", DataType::Int32, true),+ ]));++ let mut builder = TimestampNanosecondArray::builder(3);++ builder.append_value(1599572549190855000)?; // 2020-09-08T13:42:29.190855+00:00+ builder.append_value(1599568949190855000)?; // 2020-09-08T12:42:29.190855+00:00+ builder.append_value(1599565349190855000)?; // 2020-09-08T11:42:29.190855+00:00++ let data = RecordBatch::try_new(+ schema.clone(),+ vec![+ Arc::new(builder.finish()),+ Arc::new(Int32Array::from(vec![Some(1), Some(2), Some(3)])),+ ],+ )?;+ let table = MemTable::new(schema, vec![vec![data]])?;+ Ok(Box::new(table))+}++#[test]+fn to_timstamp() -> Result<()> {+ let mut ctx = ExecutionContext::new();+ ctx.register_table("ts_data", make_timestamp_nano_table()?);++ let sql = "SELECT COUNT(*) FROM ts_data where ts > to_timestamp('2020-09-08T12:00:00+00:00')";+ let actual = execute(&mut ctx, sql).join("\n");++ let expected = "2".to_string();+ assert_eq!(expected, actual);+ Ok(())+}