-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Added composite identifiers to get field of struct. #628
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
Closed
Closed
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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,100 @@ | ||
| // 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. | ||
|
|
||
| //! get field of a struct array | ||
| use std::{any::Any, sync::Arc}; | ||
|
|
||
| use arrow::{ | ||
| array::StructArray, | ||
| datatypes::{DataType, Schema}, | ||
| record_batch::RecordBatch, | ||
| }; | ||
|
|
||
| use crate::{ | ||
| error::DataFusionError, | ||
| error::Result, | ||
| physical_plan::{ColumnarValue, PhysicalExpr}, | ||
| utils::get_field as get_data_type_field, | ||
| }; | ||
|
|
||
| /// expression to get a field of a struct array. | ||
| #[derive(Debug)] | ||
| pub struct GetFieldExpr { | ||
| arg: Arc<dyn PhysicalExpr>, | ||
| name: String, | ||
| } | ||
|
|
||
| impl GetFieldExpr { | ||
| /// Create new get field expression | ||
| pub fn new(arg: Arc<dyn PhysicalExpr>, name: String) -> Self { | ||
| Self { arg, name } | ||
| } | ||
|
|
||
| /// Get the input expression | ||
| pub fn arg(&self) -> &Arc<dyn PhysicalExpr> { | ||
| &self.arg | ||
| } | ||
| } | ||
|
|
||
| impl std::fmt::Display for GetFieldExpr { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { | ||
| write!(f, "({}).{}", self.arg, self.name) | ||
| } | ||
| } | ||
|
|
||
| impl PhysicalExpr for GetFieldExpr { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn data_type(&self, input_schema: &Schema) -> Result<DataType> { | ||
| let data_type = self.arg.data_type(input_schema)?; | ||
| get_data_type_field(&data_type, &self.name).map(|f| f.data_type().clone()) | ||
| } | ||
|
|
||
| fn nullable(&self, input_schema: &Schema) -> Result<bool> { | ||
| let data_type = self.arg.data_type(input_schema)?; | ||
| get_data_type_field(&data_type, &self.name).map(|f| f.is_nullable()) | ||
| } | ||
|
|
||
| fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { | ||
| let arg = self.arg.evaluate(batch)?; | ||
| match arg { | ||
| ColumnarValue::Array(array) => Ok(ColumnarValue::Array( | ||
| array | ||
| .as_any() | ||
| .downcast_ref::<StructArray>() | ||
| .unwrap() | ||
| .column_by_name(&self.name) | ||
| .unwrap() | ||
| .clone(), | ||
| )), | ||
| ColumnarValue::Scalar(_) => Err(DataFusionError::NotImplemented( | ||
| "field is not yet implemented for scalar values".to_string(), | ||
| )), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// Create an `.field` expression | ||
| pub fn get_field( | ||
| arg: Arc<dyn PhysicalExpr>, | ||
| name: String, | ||
| ) -> Result<Arc<dyn PhysicalExpr>> { | ||
| Ok(Arc::new(GetFieldExpr::new(arg, name))) | ||
| } | ||
This file contains hidden or 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 hidden or 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 hidden or 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 |
|---|---|---|
|
|
@@ -79,6 +79,22 @@ pub struct SqlToRel<'a, S: ContextProvider> { | |
| schema_provider: &'a S, | ||
| } | ||
|
|
||
| fn plan_compound(mut identifiers: Vec<String>) -> Expr { | ||
| if &identifiers[0][0..1] == "@" { | ||
| Expr::ScalarVariable(identifiers) | ||
| } else if identifiers.len() == 2 { | ||
|
Member
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. worth considering a follow up PR to handle an edge case where user tries to access nested field with unqualified column like |
||
| // "table.column" | ||
| let name = identifiers.pop().unwrap(); | ||
| let relation = Some(identifiers.pop().unwrap()); | ||
| Expr::Column(Column { relation, name }) | ||
| } else { | ||
| // "table.column.field..." | ||
| let name = identifiers.pop().unwrap(); | ||
| let expr = Box::new(plan_compound(identifiers)); | ||
| Expr::GetField { expr, name } | ||
| } | ||
| } | ||
|
|
||
| impl<'a, S: ContextProvider> SqlToRel<'a, S> { | ||
| /// Create a new query planner | ||
| pub fn new(schema_provider: &'a S) -> Self { | ||
|
|
@@ -916,23 +932,8 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> { | |
| } | ||
|
|
||
| SQLExpr::CompoundIdentifier(ids) => { | ||
| let mut var_names = vec![]; | ||
| for id in ids { | ||
| var_names.push(id.value.clone()); | ||
| } | ||
| if &var_names[0][0..1] == "@" { | ||
| Ok(Expr::ScalarVariable(var_names)) | ||
| } else if var_names.len() == 2 { | ||
| // table.column identifier | ||
| let name = var_names.pop().unwrap(); | ||
| let relation = Some(var_names.pop().unwrap()); | ||
| Ok(Expr::Column(Column { relation, name })) | ||
| } else { | ||
| Err(DataFusionError::NotImplemented(format!( | ||
| "Unsupported compound identifier '{:?}'", | ||
| var_names, | ||
| ))) | ||
| } | ||
| let var_names = ids.iter().map(|x| x.value.clone()).collect::<Vec<_>>(); | ||
| Ok(plan_compound(var_names)) | ||
| } | ||
|
|
||
| SQLExpr::Wildcard => Ok(Expr::Wildcard), | ||
|
|
||
This file contains hidden or 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 hidden or 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,43 @@ | ||
| // 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 arrow::datatypes::{DataType, Field}; | ||
|
|
||
| use crate::error::{DataFusionError, Result}; | ||
|
|
||
| /// Returns the first field named `name` from the fields of a [`DataType::Struct`]. | ||
| /// # Error | ||
| /// Errors iff | ||
| /// * the `data_type` is not a Struct or, | ||
| /// * there is no field named `name` | ||
| pub fn get_field<'a>(data_type: &'a DataType, name: &str) -> Result<&'a Field> { | ||
| if let DataType::Struct(fields) = data_type { | ||
| let maybe_field = fields.iter().find(|x| x.name() == name); | ||
| if let Some(field) = maybe_field { | ||
| Ok(field) | ||
| } else { | ||
| Err(DataFusionError::Plan(format!( | ||
| "The `Struct` has no field named \"{}\"", | ||
| name | ||
| ))) | ||
| } | ||
| } else { | ||
| Err(DataFusionError::Plan( | ||
| "The expression to get a field is only valid for `Struct`".to_string(), | ||
| )) | ||
| } | ||
| } |
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.
Very cool -- I was wondering if
column_by_namereturningNonecould be a legit error. For example what happens when trying to select a non existent field? it seems like the calls toget_fieldwill have failed earlier with a real error so it is probably fine to treat this as infallible.