alamb commented on a change in pull request #8840: URL: https://github.com/apache/arrow/pull/8840#discussion_r537027784
########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); + let mut unqualified_names: HashSet<&str> = HashSet::new(); + for field in &fields { + if let Some(qualifier) = field.qualifier() { + if !qualified_names.insert((qualifier, field.name())) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain duplicate qualified field name '{}'", + field.qualified_name() + ))); + } + } else { + if !unqualified_names.insert(field.name()) { + return Err(DataFusionError::Plan( + format!("Joined schema would contain duplicate unqualified field name '{}'", + field.name()) + )); + } + } + } + + // check for mix of qualified and unqualified field with same unqualified name + // note that we need to sort the contents of the HashSet first so that errors are + // deterministic + let mut qualified_names: Vec<&(&str, &str)> = qualified_names.iter().collect(); + qualified_names.sort_by(|a, b| { + let a = format!("{}.{}", a.0, a.1); + let b = format!("{}.{}", b.0, b.1); + a.cmp(&b) + }); + for (qualifier, name) in &qualified_names { + if unqualified_names.contains(name) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain qualified field name '{}.{}' \ + and unqualified field name '{}' which would be ambiguous", + qualifier, name, name + ))); + } + } + Ok(Self { fields }) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from(schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: None, + }) + .collect(), + ) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from_qualified(qualifier: &str, schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: Some(qualifier.to_owned()), + }) + .collect(), + ) + } + + /// Combine two schemas + pub fn join(&self, schema: &DFSchema) -> Result<Self> { + let mut fields = self.fields.clone(); + fields.extend_from_slice(schema.fields().as_slice()); + Self::new(fields) + } + + /// Get a list of fields + pub fn fields(&self) -> &Vec<DFField> { + &self.fields + } + + /// Returns an immutable reference of a specific `Field` instance selected using an + /// offset within the internal `fields` vector + pub fn field(&self, i: usize) -> &DFField { + &self.fields[i] + } + + /// Find the index of the column with the given name + pub fn index_of(&self, name: &str) -> Result<usize> { + for i in 0..self.fields.len() { + if self.fields[i].name() == name { + return Ok(i); + } + } + Err(DataFusionError::Plan(format!("No field named '{}'", name))) + } + + /// Find the field with the given name + pub fn field_with_name( + &self, + relation_name: Option<&str>, + name: &str, + ) -> Result<DFField> { + if let Some(relation_name) = relation_name { + self.field_with_qualified_name(relation_name, name) + } else { + self.field_with_unqualified_name(name) + } + } + + /// Find the field with the given name + pub fn field_with_unqualified_name(&self, name: &str) -> Result<DFField> { + let matches: Vec<&DFField> = self + .fields + .iter() + .filter(|field| field.name() == name) + .collect(); + match matches.len() { + 0 => Err(DataFusionError::Plan(format!("No field named '{}'", name))), + 1 => Ok(matches[0].to_owned()), + _ => Err(DataFusionError::Plan(format!( + "Ambiguous reference to field named '{}'", + name + ))), + } + } + + /// Find the field with the given qualified name + pub fn field_with_qualified_name( + &self, + relation_name: &str, + name: &str, + ) -> Result<DFField> { + let matches: Vec<&DFField> = self + .fields + .iter() + .filter(|field| { + field.qualifier == Some(relation_name.to_string()) && field.name() == name + }) + .collect(); + match matches.len() { + 0 => Err(DataFusionError::Plan(format!( + "No field named '{}.{}'", + relation_name, name + ))), + 1 => Ok(matches[0].to_owned()), + _ => Err(DataFusionError::Plan(format!( + "Ambiguous reference to qualified field named '{}.{}'", + relation_name, name + ))), + } + } + + /// Convert to an Arrow schema + pub fn to_arrow_schema(&self) -> SchemaRef { + SchemaRef::new(Schema::new( + self.fields.iter().map(|f| f.field.clone()).collect(), + )) + } +} + +impl Display for DFSchema { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.fields + .iter() + .map(|field| field.qualified_name()) + .collect::<Vec<String>>() + .join(", ") + ) + } +} + +/// DFField wraps an Arrow field and adds an optional qualifier +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFField { + /// Optional qualifier (usually a table or relation name) + qualifier: Option<String>, + /// Arrow field definition + field: Field, +} + +impl DFField { + /// Creates a new `DFField` + pub fn new( + qualifier: Option<&str>, + name: &str, + data_type: DataType, + nullable: bool, + ) -> Self { + DFField { + qualifier: qualifier.map(|s| s.to_owned()), + field: Field::new(name, data_type, nullable), + } + } + + /// Create an unqualified field from an existing Arrow field + pub fn from(field: Field) -> Self { + Self { + qualifier: None, + field, + } + } + + /// Create a qualified field from an existing Arrow field + pub fn from_qualified(qualifier: &str, field: Field) -> Self { + Self { + qualifier: Some(qualifier.to_owned()), + field, + } + } + + /// Returns an immutable reference to the `DFField`'s unqualified name + pub fn name(&self) -> &String { + &self.field.name() + } + + /// Returns an immutable reference to the `DFField`'s data-type + pub fn data_type(&self) -> &DataType { + &self.field.data_type() + } + + /// Indicates whether this `DFField` supports null values + pub fn is_nullable(&self) -> bool { + self.field.is_nullable() + } + + /// Returns an immutable reference to the `DFField`'s qualified name Review comment: As a nit, as written this returns a `String` not an immutable reference Maybe we could use `Cow` in this case. Something like this (untested): ``` pub fn qualified_name(&self) -> Cow<'_, str> { if let Some(relation_name) = &self.qualifier { Cow::owned(format!("{}.{}", relation_name, self.field.name())) } else { Cow::Borrowed(self.field.name()) } } ``` I doubt this makes any measurable difference performance wise, it it would be nice to clean up the comment to match the code ########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); Review comment: You might be able to avoid the explicit types here (aka something like `let mut qualified_names = HashSet::new();` -- if not no worries, I am just not used to seeing explicit types in such a place ########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); + let mut unqualified_names: HashSet<&str> = HashSet::new(); + for field in &fields { + if let Some(qualifier) = field.qualifier() { + if !qualified_names.insert((qualifier, field.name())) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain duplicate qualified field name '{}'", + field.qualified_name() + ))); + } + } else { + if !unqualified_names.insert(field.name()) { + return Err(DataFusionError::Plan( + format!("Joined schema would contain duplicate unqualified field name '{}'", Review comment: ```suggestion format!("Schema contains ambiguous field name '{}'", ``` ########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); + let mut unqualified_names: HashSet<&str> = HashSet::new(); + for field in &fields { + if let Some(qualifier) = field.qualifier() { + if !qualified_names.insert((qualifier, field.name())) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain duplicate qualified field name '{}'", + field.qualified_name() + ))); + } + } else { + if !unqualified_names.insert(field.name()) { + return Err(DataFusionError::Plan( + format!("Joined schema would contain duplicate unqualified field name '{}'", + field.name()) + )); + } + } + } + + // check for mix of qualified and unqualified field with same unqualified name + // note that we need to sort the contents of the HashSet first so that errors are + // deterministic + let mut qualified_names: Vec<&(&str, &str)> = qualified_names.iter().collect(); + qualified_names.sort_by(|a, b| { + let a = format!("{}.{}", a.0, a.1); + let b = format!("{}.{}", b.0, b.1); + a.cmp(&b) + }); + for (qualifier, name) in &qualified_names { + if unqualified_names.contains(name) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain qualified field name '{}.{}' \ + and unqualified field name '{}' which would be ambiguous", + qualifier, name, name + ))); + } + } + Ok(Self { fields }) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from(schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: None, + }) + .collect(), + ) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from_qualified(qualifier: &str, schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: Some(qualifier.to_owned()), + }) + .collect(), + ) + } + + /// Combine two schemas + pub fn join(&self, schema: &DFSchema) -> Result<Self> { + let mut fields = self.fields.clone(); + fields.extend_from_slice(schema.fields().as_slice()); + Self::new(fields) + } + + /// Get a list of fields + pub fn fields(&self) -> &Vec<DFField> { + &self.fields + } + + /// Returns an immutable reference of a specific `Field` instance selected using an + /// offset within the internal `fields` vector + pub fn field(&self, i: usize) -> &DFField { + &self.fields[i] + } + + /// Find the index of the column with the given name + pub fn index_of(&self, name: &str) -> Result<usize> { + for i in 0..self.fields.len() { + if self.fields[i].name() == name { + return Ok(i); + } + } + Err(DataFusionError::Plan(format!("No field named '{}'", name))) + } + + /// Find the field with the given name + pub fn field_with_name( + &self, + relation_name: Option<&str>, + name: &str, + ) -> Result<DFField> { + if let Some(relation_name) = relation_name { + self.field_with_qualified_name(relation_name, name) + } else { + self.field_with_unqualified_name(name) + } + } + + /// Find the field with the given name + pub fn field_with_unqualified_name(&self, name: &str) -> Result<DFField> { + let matches: Vec<&DFField> = self + .fields + .iter() + .filter(|field| field.name() == name) + .collect(); + match matches.len() { + 0 => Err(DataFusionError::Plan(format!("No field named '{}'", name))), + 1 => Ok(matches[0].to_owned()), + _ => Err(DataFusionError::Plan(format!( + "Ambiguous reference to field named '{}'", + name + ))), + } + } + + /// Find the field with the given qualified name + pub fn field_with_qualified_name( + &self, + relation_name: &str, + name: &str, + ) -> Result<DFField> { + let matches: Vec<&DFField> = self + .fields + .iter() + .filter(|field| { + field.qualifier == Some(relation_name.to_string()) && field.name() == name + }) + .collect(); + match matches.len() { + 0 => Err(DataFusionError::Plan(format!( + "No field named '{}.{}'", + relation_name, name + ))), + 1 => Ok(matches[0].to_owned()), + _ => Err(DataFusionError::Plan(format!( + "Ambiguous reference to qualified field named '{}.{}'", + relation_name, name + ))), + } + } + + /// Convert to an Arrow schema + pub fn to_arrow_schema(&self) -> SchemaRef { + SchemaRef::new(Schema::new( + self.fields.iter().map(|f| f.field.clone()).collect(), + )) + } +} + +impl Display for DFSchema { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!( + f, + "{}", + self.fields + .iter() + .map(|field| field.qualified_name()) + .collect::<Vec<String>>() + .join(", ") + ) + } +} + +/// DFField wraps an Arrow field and adds an optional qualifier +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFField { + /// Optional qualifier (usually a table or relation name) + qualifier: Option<String>, + /// Arrow field definition + field: Field, +} + +impl DFField { + /// Creates a new `DFField` + pub fn new( + qualifier: Option<&str>, + name: &str, + data_type: DataType, + nullable: bool, + ) -> Self { + DFField { + qualifier: qualifier.map(|s| s.to_owned()), + field: Field::new(name, data_type, nullable), + } + } + + /// Create an unqualified field from an existing Arrow field + pub fn from(field: Field) -> Self { + Self { + qualifier: None, + field, + } + } + + /// Create a qualified field from an existing Arrow field + pub fn from_qualified(qualifier: &str, field: Field) -> Self { + Self { + qualifier: Some(qualifier.to_owned()), + field, + } + } + + /// Returns an immutable reference to the `DFField`'s unqualified name + pub fn name(&self) -> &String { + &self.field.name() + } + + /// Returns an immutable reference to the `DFField`'s data-type + pub fn data_type(&self) -> &DataType { + &self.field.data_type() + } + + /// Indicates whether this `DFField` supports null values + pub fn is_nullable(&self) -> bool { + self.field.is_nullable() + } + + /// Returns an immutable reference to the `DFField`'s qualified name + pub fn qualified_name(&self) -> String { + if let Some(relation_name) = &self.qualifier { + format!("{}.{}", relation_name, self.field.name()) + } else { + self.field.name().to_owned() + } + } + + /// Get the optional qualifier + pub fn qualifier(&self) -> &Option<String> { + &self.qualifier + } Review comment: ```suggestion pub fn qualifier(&self) -> Option<&String> { self.qualifier.as_ref() } ``` I have been told that pattern is more idomatic rust, though the &Option works just fine ########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); + let mut unqualified_names: HashSet<&str> = HashSet::new(); + for field in &fields { + if let Some(qualifier) = field.qualifier() { + if !qualified_names.insert((qualifier, field.name())) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain duplicate qualified field name '{}'", Review comment: ```suggestion "Schema contains duplicated field name '{}'", ``` ########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); + let mut unqualified_names: HashSet<&str> = HashSet::new(); + for field in &fields { + if let Some(qualifier) = field.qualifier() { + if !qualified_names.insert((qualifier, field.name())) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain duplicate qualified field name '{}'", + field.qualified_name() + ))); + } + } else { + if !unqualified_names.insert(field.name()) { + return Err(DataFusionError::Plan( + format!("Joined schema would contain duplicate unqualified field name '{}'", + field.name()) + )); + } + } + } + + // check for mix of qualified and unqualified field with same unqualified name + // note that we need to sort the contents of the HashSet first so that errors are + // deterministic + let mut qualified_names: Vec<&(&str, &str)> = qualified_names.iter().collect(); + qualified_names.sort_by(|a, b| { + let a = format!("{}.{}", a.0, a.1); + let b = format!("{}.{}", b.0, b.1); + a.cmp(&b) + }); + for (qualifier, name) in &qualified_names { + if unqualified_names.contains(name) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain qualified field name '{}.{}' \ + and unqualified field name '{}' which would be ambiguous", + qualifier, name, name + ))); + } + } + Ok(Self { fields }) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from(schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: None, + }) + .collect(), + ) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from_qualified(qualifier: &str, schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: Some(qualifier.to_owned()), + }) + .collect(), + ) + } + + /// Combine two schemas + pub fn join(&self, schema: &DFSchema) -> Result<Self> { + let mut fields = self.fields.clone(); + fields.extend_from_slice(schema.fields().as_slice()); Review comment: it seems like this will allow duplicated field names if `self` and `schema` have such duplication -- I think we may want to call `Self::new(...)` so we get the error checking ########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); + let mut unqualified_names: HashSet<&str> = HashSet::new(); + for field in &fields { + if let Some(qualifier) = field.qualifier() { + if !qualified_names.insert((qualifier, field.name())) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain duplicate qualified field name '{}'", + field.qualified_name() + ))); + } + } else { + if !unqualified_names.insert(field.name()) { + return Err(DataFusionError::Plan( + format!("Joined schema would contain duplicate unqualified field name '{}'", + field.name()) + )); + } + } + } + + // check for mix of qualified and unqualified field with same unqualified name + // note that we need to sort the contents of the HashSet first so that errors are + // deterministic + let mut qualified_names: Vec<&(&str, &str)> = qualified_names.iter().collect(); + qualified_names.sort_by(|a, b| { + let a = format!("{}.{}", a.0, a.1); + let b = format!("{}.{}", b.0, b.1); + a.cmp(&b) + }); + for (qualifier, name) in &qualified_names { + if unqualified_names.contains(name) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain qualified field name '{}.{}' \ + and unqualified field name '{}' which would be ambiguous", + qualifier, name, name + ))); + } + } + Ok(Self { fields }) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from(schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: None, + }) + .collect(), + ) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from_qualified(qualifier: &str, schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: Some(qualifier.to_owned()), + }) + .collect(), + ) + } + + /// Combine two schemas + pub fn join(&self, schema: &DFSchema) -> Result<Self> { + let mut fields = self.fields.clone(); + fields.extend_from_slice(schema.fields().as_slice()); + Self::new(fields) + } + + /// Get a list of fields + pub fn fields(&self) -> &Vec<DFField> { + &self.fields + } + + /// Returns an immutable reference of a specific `Field` instance selected using an + /// offset within the internal `fields` vector + pub fn field(&self, i: usize) -> &DFField { + &self.fields[i] + } + + /// Find the index of the column with the given name + pub fn index_of(&self, name: &str) -> Result<usize> { + for i in 0..self.fields.len() { + if self.fields[i].name() == name { + return Ok(i); + } + } + Err(DataFusionError::Plan(format!("No field named '{}'", name))) + } + + /// Find the field with the given name + pub fn field_with_name( + &self, + relation_name: Option<&str>, + name: &str, + ) -> Result<DFField> { + if let Some(relation_name) = relation_name { + self.field_with_qualified_name(relation_name, name) + } else { + self.field_with_unqualified_name(name) + } + } + + /// Find the field with the given name + pub fn field_with_unqualified_name(&self, name: &str) -> Result<DFField> { + let matches: Vec<&DFField> = self + .fields + .iter() + .filter(|field| field.name() == name) + .collect(); + match matches.len() { + 0 => Err(DataFusionError::Plan(format!("No field named '{}'", name))), + 1 => Ok(matches[0].to_owned()), + _ => Err(DataFusionError::Plan(format!( + "Ambiguous reference to field named '{}'", + name + ))), + } + } + + /// Find the field with the given qualified name + pub fn field_with_qualified_name( + &self, + relation_name: &str, + name: &str, + ) -> Result<DFField> { + let matches: Vec<&DFField> = self + .fields + .iter() + .filter(|field| { + field.qualifier == Some(relation_name.to_string()) && field.name() == name + }) + .collect(); + match matches.len() { + 0 => Err(DataFusionError::Plan(format!( + "No field named '{}.{}'", + relation_name, name + ))), + 1 => Ok(matches[0].to_owned()), + _ => Err(DataFusionError::Plan(format!( Review comment: In theory this case should not be possible (as `new` would error out). Perhaps we should make this `unreachable!(..)` to signal it is not an expected usage error. Or maybe just change the error message to `"Internal Error: Ambiguous...."`) ########## File path: rust/datafusion/src/logical_plan/dfschema.rs ########## @@ -0,0 +1,415 @@ +// 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. + +//! DFSchema is an extended schema struct that DataFusion uses to provide support for +//! fields with optional relation names. + +use std::collections::HashSet; +use std::sync::Arc; + +use crate::error::{DataFusionError, Result}; + +use arrow::datatypes::{DataType, Field, Schema, SchemaRef}; +use std::fmt::{Display, Formatter}; + +/// A reference-counted reference to a `DFSchema`. +pub type DFSchemaRef = Arc<DFSchema>; + +/// DFSchema wraps an Arrow schema and adds relation names +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DFSchema { + /// Fields + fields: Vec<DFField>, +} + +impl DFSchema { + /// Creates an empty `DFSchema` + pub fn empty() -> Self { + Self { fields: vec![] } + } + + /// Create a new `DFSchema` + pub fn new(fields: Vec<DFField>) -> Result<Self> { + let mut qualified_names: HashSet<(&str, &str)> = HashSet::new(); + let mut unqualified_names: HashSet<&str> = HashSet::new(); + for field in &fields { + if let Some(qualifier) = field.qualifier() { + if !qualified_names.insert((qualifier, field.name())) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain duplicate qualified field name '{}'", + field.qualified_name() + ))); + } + } else { + if !unqualified_names.insert(field.name()) { + return Err(DataFusionError::Plan( + format!("Joined schema would contain duplicate unqualified field name '{}'", + field.name()) + )); + } + } + } + + // check for mix of qualified and unqualified field with same unqualified name + // note that we need to sort the contents of the HashSet first so that errors are + // deterministic + let mut qualified_names: Vec<&(&str, &str)> = qualified_names.iter().collect(); + qualified_names.sort_by(|a, b| { + let a = format!("{}.{}", a.0, a.1); + let b = format!("{}.{}", b.0, b.1); + a.cmp(&b) + }); + for (qualifier, name) in &qualified_names { + if unqualified_names.contains(name) { + return Err(DataFusionError::Plan(format!( + "Joined schema would contain qualified field name '{}.{}' \ + and unqualified field name '{}' which would be ambiguous", + qualifier, name, name + ))); + } + } + Ok(Self { fields }) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from(schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: None, + }) + .collect(), + ) + } + + /// Create a `DFSchema` from an Arrow schema + pub fn from_qualified(qualifier: &str, schema: &Schema) -> Result<Self> { + Self::new( + schema + .fields() + .iter() + .map(|f| DFField { + field: f.clone(), + qualifier: Some(qualifier.to_owned()), + }) + .collect(), + ) + } + + /// Combine two schemas + pub fn join(&self, schema: &DFSchema) -> Result<Self> { + let mut fields = self.fields.clone(); + fields.extend_from_slice(schema.fields().as_slice()); + Self::new(fields) + } + + /// Get a list of fields + pub fn fields(&self) -> &Vec<DFField> { + &self.fields + } + + /// Returns an immutable reference of a specific `Field` instance selected using an + /// offset within the internal `fields` vector + pub fn field(&self, i: usize) -> &DFField { + &self.fields[i] + } + + /// Find the index of the column with the given name + pub fn index_of(&self, name: &str) -> Result<usize> { + for i in 0..self.fields.len() { + if self.fields[i].name() == name { + return Ok(i); + } + } + Err(DataFusionError::Plan(format!("No field named '{}'", name))) + } + + /// Find the field with the given name + pub fn field_with_name( + &self, + relation_name: Option<&str>, + name: &str, + ) -> Result<DFField> { + if let Some(relation_name) = relation_name { + self.field_with_qualified_name(relation_name, name) + } else { + self.field_with_unqualified_name(name) + } + } + + /// Find the field with the given name + pub fn field_with_unqualified_name(&self, name: &str) -> Result<DFField> { + let matches: Vec<&DFField> = self + .fields + .iter() + .filter(|field| field.name() == name) + .collect(); + match matches.len() { + 0 => Err(DataFusionError::Plan(format!("No field named '{}'", name))), + 1 => Ok(matches[0].to_owned()), + _ => Err(DataFusionError::Plan(format!( + "Ambiguous reference to field named '{}'", Review comment: 👍 ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected]
