-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Add to_date
function
#9019
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add to_date
function
#9019
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
// 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. | ||
|
||
use std::sync::Arc; | ||
|
||
use datafusion::arrow::array::StringArray; | ||
use datafusion::arrow::datatypes::{DataType, Field, Schema}; | ||
use datafusion::arrow::record_batch::RecordBatch; | ||
use datafusion::error::Result; | ||
use datafusion::prelude::*; | ||
|
||
/// This example demonstrates how to use the to_date series | ||
/// of functions in the DataFrame API as well as via sql. | ||
#[tokio::main] | ||
async fn main() -> Result<()> { | ||
// define a schema. | ||
let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)])); | ||
|
||
// define data. | ||
let batch = RecordBatch::try_new( | ||
schema, | ||
vec![Arc::new(StringArray::from(vec![ | ||
"2020-09-08T13:42:29Z", | ||
"2020-09-08T13:42:29.190855-05:00", | ||
"2020-08-09 12:13:29", | ||
"2020-01-02", | ||
]))], | ||
)?; | ||
|
||
// declare a new context. In spark API, this corresponds to a new spark SQLsession | ||
let ctx = SessionContext::new(); | ||
|
||
// declare a table in memory. In spark API, this corresponds to createDataFrame(...). | ||
ctx.register_batch("t", batch)?; | ||
let df = ctx.table("t").await?; | ||
|
||
// use to_date function to convert col 'a' to timestamp type using the default parsing | ||
let df = df.with_column("a", to_date(vec![col("a")]))?; | ||
|
||
let df = df.select_columns(&["a"])?; | ||
|
||
// print the results | ||
df.show().await?; | ||
|
||
Ok(()) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -54,7 +54,8 @@ use datafusion_common::cast::{ | |
as_timestamp_nanosecond_array, as_timestamp_second_array, | ||
}; | ||
use datafusion_common::{ | ||
exec_err, not_impl_err, DataFusionError, Result, ScalarType, ScalarValue, | ||
exec_err, internal_datafusion_err, not_impl_err, DataFusionError, Result, ScalarType, | ||
ScalarValue, | ||
}; | ||
use datafusion_expr::ColumnarValue; | ||
|
||
|
@@ -424,6 +425,84 @@ fn to_timestamp_impl<T: ArrowTimestampType + ScalarType<i64>>( | |
} | ||
} | ||
|
||
/// # Examples | ||
/// | ||
/// ```ignore | ||
/// # use std::sync::Arc; | ||
|
||
/// # use datafusion::arrow::array::StringArray; | ||
/// # use datafusion::arrow::datatypes::{DataType, Field, Schema}; | ||
/// # use datafusion::arrow::record_batch::RecordBatch; | ||
/// # use datafusion::error::Result; | ||
/// # use datafusion::prelude::*; | ||
|
||
/// # #[tokio::main] | ||
/// # async fn main() -> Result<()> { | ||
/// // define a schema. | ||
/// let schema = Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false)])); | ||
|
||
/// // define data. | ||
/// let batch = RecordBatch::try_new( | ||
/// schema, | ||
/// vec![Arc::new(StringArray::from(vec![ | ||
/// "2020-09-08T13:42:29Z", | ||
/// "2020-09-08T13:42:29.190855-05:00", | ||
/// "2020-08-09 12:13:29", | ||
/// "2020-01-02", | ||
/// ]))], | ||
/// )?; | ||
|
||
/// // declare a new context. In spark API, this corresponds to a new spark SQLsession | ||
/// let ctx = SessionContext::new(); | ||
|
||
/// // declare a table in memory. In spark API, this corresponds to createDataFrame(...). | ||
/// ctx.register_batch("t", batch)?; | ||
/// let df = ctx.table("t").await?; | ||
|
||
/// // use to_date function to convert col 'a' to timestamp type using the default parsing | ||
/// let df = df.with_column("a", to_date(vec![col("a")]))?; | ||
|
||
/// let df = df.select_columns(&["a"])?; | ||
|
||
/// // print the results | ||
/// df.show().await?; | ||
|
||
/// # Ok(()) | ||
/// # } | ||
/// ``` | ||
pub fn to_date(args: &[ColumnarValue]) -> Result<ColumnarValue> { | ||
match args.len() { | ||
1 => handle::<Date32Type, _, Date32Type>( | ||
args, | ||
|s| { | ||
string_to_timestamp_nanos_shim(s) | ||
.map(|n| n / (1_000_000 * 24 * 60 * 60 * 1_000)) | ||
.and_then(|v| { | ||
v.try_into().map_err(|_| { | ||
internal_datafusion_err!("Unable to cast to Date32 for converting from i64 to i32 failed") | ||
}) | ||
}) | ||
}, | ||
"to_date", | ||
), | ||
n if n >= 2 => handle_multiple::<Date32Type, _, Date32Type, _>( | ||
args, | ||
|s, format| { | ||
string_to_timestamp_nanos_formatted(s, format) | ||
.map(|n| n / (1_000_000 * 24 * 60 * 60 * 1_000)) | ||
.and_then(|v| { | ||
v.try_into().map_err(|_| { | ||
internal_datafusion_err!("Unable to cast to Date32 for converting from i64 to i32 failed") | ||
}) | ||
}) | ||
}, | ||
|n| n, | ||
"to_date", | ||
), | ||
_ => exec_err!("Unsupported 0 argument count for function to_date"), | ||
} | ||
} | ||
|
||
/// to_timestamp SQL function | ||
/// | ||
/// Note: `to_timestamp` returns `Timestamp(Nanosecond)` though its arguments are interpreted as **seconds**. | ||
|
@@ -1567,6 +1646,36 @@ fn validate_to_timestamp_data_types( | |
None | ||
} | ||
|
||
/// to_date SQL function implementation | ||
pub fn to_date_invoke(args: &[ColumnarValue]) -> Result<ColumnarValue> { | ||
if args.is_empty() { | ||
return exec_err!( | ||
"to_date function requires 1 or more arguments, got {}", | ||
args.len() | ||
); | ||
} | ||
|
||
// validate that any args after the first one are Utf8 | ||
if args.len() > 1 { | ||
if let Some(value) = validate_to_timestamp_data_types(args, "to_date") { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. the validate method should likely be renamed as it won't be used just for timestamps now |
||
return value; | ||
} | ||
} | ||
|
||
match args[0].data_type() { | ||
DataType::Int32 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It looks like your code takes several input types -- can you please add tests that show calling There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done |
||
| DataType::Int64 | ||
| DataType::Null | ||
| DataType::Float64 | ||
| DataType::Date32 | ||
| DataType::Date64 => cast_column(&args[0], &DataType::Date32, None), | ||
DataType::Utf8 => to_date(args), | ||
other => { | ||
exec_err!("Unsupported data type {:?} for function to_date", other) | ||
} | ||
} | ||
} | ||
|
||
/// to_timestamp() SQL function implementation | ||
pub fn to_timestamp_invoke(args: &[ColumnarValue]) -> Result<ColumnarValue> { | ||
if args.is_empty() { | ||
|
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we add some rustdoc with a dataframe based example to this? See this as an example