-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
Move from_unixtime, now, current_date, current_time functions to datafusion-functions #9537
Merged
Merged
Changes from all commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
bcd2bd1
Move date_part, date_trunc, date_bin functions to datafusion-functions
Omega359 761d873
Merge remote-tracking branch 'upstream/main' into feature/9421
Omega359 2a41960
I do not understand why the logical plan changed but updating the exp…
Omega359 35f8e36
Merge remote-tracking branch 'upstream/main' into feature/9421
Omega359 618cc40
Fix fmt
Omega359 7ea0527
Merge remote-tracking branch 'upstream/main' into feature/9421
Omega359 98d5ff7
Improvements to remove datafusion-functions dependency from sq and ph…
Omega359 42039da
Merge remote-tracking branch 'upstream/main' into feature/9421
Omega359 4c84f08
WIP
Omega359 9675dcd
Fix function arguments for date_bin, date_trunc and date_part.
Omega359 444337c
Merge remote-tracking branch 'upstream/main' into feature/9421
Omega359 b72bd55
Merge remote-tracking branch 'upstream/main' into feature/9466
Omega359 8840d50
WIP
Omega359 c0ce362
Fix projection change. Add new test date_bin monotonicity
mustafasrepo 3ef85ad
Merge remote-tracking branch 'origin/feature/9421' into feature/9466
Omega359 e574abf
Move now, current_date and current_time functions to datafusion-funct…
Omega359 f9a7717
Merge remote-tracking branch 'upstream/main' into feature/9466
Omega359 ea89f71
Force exact version of chrono
Omega359 8abb99a
Merge updates.
Omega359 15c50eb
Updates for chrono changes
Omega359 b4e54cc
Merge remote-tracking branch 'upstream/main' into feature/9466
Omega359 a58a851
Merge fixes
Omega359 b63feb3
Removed make_now from incorrect merge.
Omega359 3986baa
fmt fix.
Omega359 c2e8b69
Merge remote-tracking branch 'upstream/main' into feature/9466
Omega359 92a1370
Updates after correcting merge conflicts.
Omega359 189190c
Only move the tests using now() function from optimizer_integration.r…
Omega359 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,198 @@ | ||
// 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::any::Any; | ||
use std::collections::HashMap; | ||
use std::sync::Arc; | ||
|
||
use arrow::datatypes::{DataType, Field, Schema, SchemaRef, TimeUnit}; | ||
use datafusion_common::config::ConfigOptions; | ||
use datafusion_common::{plan_err, Result}; | ||
use datafusion_expr::{AggregateUDF, LogicalPlan, ScalarUDF, TableSource, WindowUDF}; | ||
use datafusion_optimizer::analyzer::Analyzer; | ||
use datafusion_optimizer::optimizer::Optimizer; | ||
use datafusion_optimizer::{OptimizerConfig, OptimizerContext}; | ||
use datafusion_sql::planner::{ContextProvider, SqlToRel}; | ||
use datafusion_sql::sqlparser::ast::Statement; | ||
use datafusion_sql::sqlparser::dialect::GenericDialect; | ||
use datafusion_sql::sqlparser::parser::Parser; | ||
use datafusion_sql::TableReference; | ||
|
||
use chrono::DateTime; | ||
use datafusion_functions::datetime; | ||
|
||
#[cfg(test)] | ||
#[ctor::ctor] | ||
fn init() { | ||
// enable logging so RUST_LOG works | ||
let _ = env_logger::try_init(); | ||
} | ||
|
||
#[test] | ||
fn timestamp_nano_ts_none_predicates() -> Result<()> { | ||
let sql = "SELECT col_int32 | ||
FROM test | ||
WHERE col_ts_nano_none < (now() - interval '1 hour')"; | ||
let plan = test_sql(sql)?; | ||
// a scan should have the now()... predicate folded to a single | ||
// constant and compared to the column without a cast so it can be | ||
// pushed down / pruned | ||
let expected = | ||
"Projection: test.col_int32\ | ||
\n Filter: test.col_ts_nano_none < TimestampNanosecond(1666612093000000000, None)\ | ||
\n TableScan: test projection=[col_int32, col_ts_nano_none]"; | ||
assert_eq!(expected, format!("{plan:?}")); | ||
Ok(()) | ||
} | ||
|
||
#[test] | ||
fn timestamp_nano_ts_utc_predicates() { | ||
let sql = "SELECT col_int32 | ||
FROM test | ||
WHERE col_ts_nano_utc < (now() - interval '1 hour')"; | ||
let plan = test_sql(sql).unwrap(); | ||
// a scan should have the now()... predicate folded to a single | ||
// constant and compared to the column without a cast so it can be | ||
// pushed down / pruned | ||
let expected = | ||
"Projection: test.col_int32\n Filter: test.col_ts_nano_utc < TimestampNanosecond(1666612093000000000, Some(\"+00:00\"))\ | ||
\n TableScan: test projection=[col_int32, col_ts_nano_utc]"; | ||
assert_eq!(expected, format!("{plan:?}")); | ||
} | ||
|
||
fn test_sql(sql: &str) -> Result<LogicalPlan> { | ||
// parse the SQL | ||
let dialect = GenericDialect {}; // or AnsiDialect, or your own dialect ... | ||
let ast: Vec<Statement> = Parser::parse_sql(&dialect, sql).unwrap(); | ||
let statement = &ast[0]; | ||
|
||
// create a logical query plan | ||
let now_udf = datetime::functions() | ||
.iter() | ||
.find(|f| f.name() == "now") | ||
.unwrap() | ||
.to_owned(); | ||
let context_provider = MyContextProvider::default().with_udf(now_udf); | ||
let sql_to_rel = SqlToRel::new(&context_provider); | ||
let plan = sql_to_rel.sql_statement_to_plan(statement.clone()).unwrap(); | ||
|
||
// hard code the return value of now() | ||
let now_time = DateTime::from_timestamp(1666615693, 0).unwrap(); | ||
let config = OptimizerContext::new() | ||
.with_skip_failing_rules(false) | ||
.with_query_execution_start_time(now_time); | ||
let analyzer = Analyzer::new(); | ||
let optimizer = Optimizer::new(); | ||
// analyze and optimize the logical plan | ||
let plan = analyzer.execute_and_check(&plan, config.options(), |_, _| {})?; | ||
optimizer.optimize(&plan, &config, |_, _| {}) | ||
} | ||
|
||
#[derive(Default)] | ||
struct MyContextProvider { | ||
options: ConfigOptions, | ||
udfs: HashMap<String, Arc<ScalarUDF>>, | ||
} | ||
|
||
impl MyContextProvider { | ||
fn with_udf(mut self, udf: Arc<ScalarUDF>) -> Self { | ||
self.udfs.insert(udf.name().to_string(), udf); | ||
self | ||
} | ||
} | ||
|
||
impl ContextProvider for MyContextProvider { | ||
fn get_table_source(&self, name: TableReference) -> Result<Arc<dyn TableSource>> { | ||
let table_name = name.table(); | ||
if table_name.starts_with("test") { | ||
let schema = Schema::new_with_metadata( | ||
vec![ | ||
Field::new("col_int32", DataType::Int32, true), | ||
Field::new("col_uint32", DataType::UInt32, true), | ||
Field::new("col_utf8", DataType::Utf8, true), | ||
Field::new("col_date32", DataType::Date32, true), | ||
Field::new("col_date64", DataType::Date64, true), | ||
// timestamp with no timezone | ||
Field::new( | ||
"col_ts_nano_none", | ||
DataType::Timestamp(TimeUnit::Nanosecond, None), | ||
true, | ||
), | ||
// timestamp with UTC timezone | ||
Field::new( | ||
"col_ts_nano_utc", | ||
DataType::Timestamp(TimeUnit::Nanosecond, Some("+00:00".into())), | ||
true, | ||
), | ||
], | ||
HashMap::new(), | ||
); | ||
|
||
Ok(Arc::new(MyTableSource { | ||
schema: Arc::new(schema), | ||
})) | ||
} else { | ||
plan_err!("table does not exist") | ||
} | ||
} | ||
|
||
fn get_function_meta(&self, name: &str) -> Option<Arc<ScalarUDF>> { | ||
self.udfs.get(name).cloned() | ||
} | ||
|
||
fn get_aggregate_meta(&self, _name: &str) -> Option<Arc<AggregateUDF>> { | ||
None | ||
} | ||
|
||
fn get_variable_type(&self, _variable_names: &[String]) -> Option<DataType> { | ||
None | ||
} | ||
|
||
fn get_window_meta(&self, _name: &str) -> Option<Arc<WindowUDF>> { | ||
None | ||
} | ||
|
||
fn options(&self) -> &ConfigOptions { | ||
&self.options | ||
} | ||
|
||
fn udfs_names(&self) -> Vec<String> { | ||
Vec::new() | ||
} | ||
|
||
fn udafs_names(&self) -> Vec<String> { | ||
Vec::new() | ||
} | ||
|
||
fn udwfs_names(&self) -> Vec<String> { | ||
Vec::new() | ||
} | ||
} | ||
|
||
struct MyTableSource { | ||
schema: SchemaRef, | ||
} | ||
|
||
impl TableSource for MyTableSource { | ||
fn as_any(&self) -> &dyn Any { | ||
self | ||
} | ||
|
||
fn schema(&self) -> SchemaRef { | ||
self.schema.clone() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
How much of the optimizer integration test do you think needs Udfs? I am wondering maybe we could just port the tests case for
now()
into core/tests/sql_integration` or something and eave the rest of the optimizer_integration test in the optimizer crate?The reason it might be good to leave the optimzer tests in the optimizer crate are
cargo test -p datafusion_optimizer
and run all the relevant testsdatafusion_optimizer
without the function definitionsThere 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.
I'll take a look. 6/20 tests use functions in the test (concat, sum, concat_ws, now(), avg). I can move just those over for sure. I wish this test dependency issue wasn't such an problem in Rust - most of the problems I've seen migrating the functions have been test related.
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.
Thinking about this more - the issue is not test related because we can use dev dependencies. The issue is publishing to crates.io because cargo publishes with dev-dependencies and has been for many many years according to the bug report. Would it be possible to just fix that by the use of --no-dev-deps or something similar during publishing?
🤔
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.
#9579
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.
I think moving the tests to the core (what this PR does) is probably the best solution for now, as it correctly reflects the dependencies (the optimizer tests are testing behavior of functions that are not available to optimizer)
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.
I moved all but the tests that required now() back to the datafusion/optimizer/tests folder.