Apache DataFusion SQL Query Engine
Clippy lints (#6464)
Louis Gariépy0d9c542c84f6
diff --git a/datafusion/common/src/dfschema.rs b/datafusion/common/src/dfschema.rsindex 8105ada59f..0416086d81 100644--- a/datafusion/common/src/dfschema.rs+++ b/datafusion/common/src/dfschema.rs@@ -511,7 +511,6 @@ impl From<DFSchema> for SchemaRef {}// Hashing refers to a subset of fields considered in PartialEq.-#[allow(clippy::derived_hash_with_manual_eq)]impl Hash for DFSchema {fn hash<H: std::hash::Hasher>(&self, state: &mut H) {self.fields.hash(state);@@ -525,25 +524,21 @@ whereSelf: Sized,{/// Attempt to create a DSSchema- #[allow(clippy::wrong_self_convention)]fn to_dfschema(self) -> Result<DFSchema>;/// Attempt to create a DSSchemaRef- #[allow(clippy::wrong_self_convention)]fn to_dfschema_ref(self) -> Result<DFSchemaRef> {Ok(Arc::new(self.to_dfschema()?))}}impl ToDFSchema for Schema {- #[allow(clippy::wrong_self_convention)]fn to_dfschema(self) -> Result<DFSchema> {DFSchema::try_from(self)}}impl ToDFSchema for SchemaRef {- #[allow(clippy::wrong_self_convention)]fn to_dfschema(self) -> Result<DFSchema> {// Attempt to use the Schema directly if there are no other// references, otherwise clonediff --git a/datafusion/common/src/error.rs b/datafusion/common/src/error.rsindex 97c448f41a..2074d35fb2 100644--- a/datafusion/common/src/error.rs+++ b/datafusion/common/src/error.rs@@ -486,22 +486,18 @@ mod test {);}- /// Model what happens when implementing SendableRecrordBatchStream:+ /// Model what happens when implementing SendableRecordBatchStream:/// DataFusion code needs to return an ArrowError- #[allow(clippy::try_err)]fn return_arrow_error() -> arrow::error::Result<()> {// Expect the '?' to work- Err(DataFusionError::Plan("foo".to_string()))?;- Ok(())+ Err(DataFusionError::Plan("foo".to_string()).into())}/// Model what happens when using arrow kernels in DataFusion/// code: need to turn an ArrowError into a DataFusionError- #[allow(clippy::try_err)]fn return_datafusion_error() -> crate::error::Result<()> {// Expect the '?' to work- Err(ArrowError::SchemaError("bar".to_string()))?;- Ok(())+ Err(ArrowError::SchemaError("bar".to_string()).into())}fn do_root_test(e: DataFusionError, exp: DataFusionError) {diff --git a/datafusion/common/src/utils.rs b/datafusion/common/src/utils.rsindex 895fbc1ffe..1fec19c76b 100644--- a/datafusion/common/src/utils.rs+++ b/datafusion/common/src/utils.rs@@ -29,6 +29,7 @@ use sqlparser::parser::Parser;use std::borrow::{Borrow, Cow};use std::cmp::Ordering;use std::ops::Range;+use std::sync::Arc;/// Given column vectors, returns row at `idx`.pub fn get_row_at_idx(columns: &[ArrayRef], idx: usize) -> Result<Vec<ScalarValue>> {@@ -289,6 +290,34 @@ pub fn longest_consecutive_prefix<T: Borrow<usize>>(count}+/// An extension trait for smart pointers. Provides an interface to get a+/// raw pointer to the data (with metadata stripped away).+///+/// This is useful to see if two smart pointers point to the same allocation.+pub trait DataPtr {+ /// Returns a raw pointer to the data, stripping away all metadata.+ fn data_ptr(this: &Self) -> *const ();++ /// Check if two pointers point to the same data.+ fn data_ptr_eq(this: &Self, other: &Self) -> bool {+ // Discard pointer metadata (including the v-table).+ let this = Self::data_ptr(this);+ let other = Self::data_ptr(other);++ std::ptr::eq(this, other)+ }+}++// Currently, it's brittle to compare `Arc`s of dyn traits with `Arc::ptr_eq`+// due to this check including v-table equality. It may be possible to use+// `Arc::ptr_eq` directly if a fix to https://github.com/rust-lang/rust/issues/103763+// is stabilized.+impl<T: ?Sized> DataPtr for Arc<T> {+ fn data_ptr(this: &Self) -> *const () {+ Arc::as_ptr(this) as *const ()+ }+}+#[cfg(test)]mod tests {use arrow::array::Float64Array;@@ -591,4 +620,24 @@ mod tests {assert_eq!(longest_consecutive_prefix([0, 1, 2, 3, 4]), 5);assert_eq!(longest_consecutive_prefix([1, 2, 3, 4]), 0);}++ #[test]+ fn arc_data_ptr_eq() {+ let x = Arc::new(());+ let y = Arc::new(());+ let y_clone = Arc::clone(&y);++ assert!(+ Arc::data_ptr_eq(&x, &x),+ "same `Arc`s should point to same data"+ );+ assert!(+ !Arc::data_ptr_eq(&x, &y),+ "different `Arc`s should point to different data"+ );+ assert!(+ Arc::data_ptr_eq(&y, &y_clone),+ "cloned `Arc` should point to same data as the original"+ );+ }}diff --git a/datafusion/core/src/avro_to_arrow/arrow_array_reader.rs b/datafusion/core/src/avro_to_arrow/arrow_array_reader.rsindex 0b7f9ca583..921f2150e8 100644--- a/datafusion/core/src/avro_to_arrow/arrow_array_reader.rs+++ b/datafusion/core/src/avro_to_arrow/arrow_array_reader.rs@@ -88,7 +88,6 @@ impl<'a, R: Read> AvroArrowArrayReader<'a, R> {}/// Read the next batch of records- #[allow(clippy::should_implement_trait)]pub fn next_batch(&mut self, batch_size: usize) -> ArrowResult<Option<RecordBatch>> {let rows = self.readerdiff --git a/datafusion/core/src/avro_to_arrow/reader.rs b/datafusion/core/src/avro_to_arrow/reader.rsindex a2fa307285..ddf8cd6982 100644--- a/datafusion/core/src/avro_to_arrow/reader.rs+++ b/datafusion/core/src/avro_to_arrow/reader.rs@@ -153,7 +153,15 @@ impl<'a, R: Read> Reader<'a, R> {}/// Returns the next batch of results (defined by `self.batch_size`), or `None` if there- /// are no more results+ /// are no more results.+ //+ // TODO(clippy): The clippy `allow` could be removed by renaming this method to `next_batch`.+ // This would also make the intent of the method clearer.+ //+ // Another option could be to rework `AvroArrowArrayReader::next_batch` so it returns an+ // `Option<ArrowResult<RecordBatch>>` instead of a `ArrowResult<Option<RecordBatch>>`.+ // This would make it possible to remove this method entirely and move its body into the+ // `Iterator` implementation.#[allow(clippy::should_implement_trait)]pub fn next(&mut self) -> ArrowResult<Option<RecordBatch>> {self.array_reader.next_batch(self.batch_size)diff --git a/datafusion/core/src/catalog/information_schema.rs b/datafusion/core/src/catalog/information_schema.rsindex b414746010..6e3a9acbb5 100644--- a/datafusion/core/src/catalog/information_schema.rs+++ b/datafusion/core/src/catalog/information_schema.rs@@ -143,15 +143,15 @@ impl InformationSchemaConfig {let schema = catalog.schema(&schema_name).unwrap();for table_name in schema.table_names() {let table = schema.table(&table_name).await.unwrap();- for (i, field) in table.schema().fields().iter().enumerate() {+ for (field_position, field) in+ table.schema().fields().iter().enumerate()+ {builder.add_column(&catalog_name,&schema_name,&table_name,- field.name(),- i,- field.is_nullable(),- field.data_type(),+ field_position,+ field,)}}@@ -486,37 +486,35 @@ struct InformationSchemaColumnsBuilder {}impl InformationSchemaColumnsBuilder {- #[allow(clippy::too_many_arguments)]fn add_column(&mut self,- catalog_name: impl AsRef<str>,- schema_name: impl AsRef<str>,- table_name: impl AsRef<str>,- column_name: impl AsRef<str>,- column_position: usize,- is_nullable: bool,- data_type: &DataType,+ catalog_name: &str,+ schema_name: &str,+ table_name: &str,+ field_position: usize,+ field: &Field,) {use DataType::*;// Note: append_value is actually infallable.- self.catalog_names.append_value(catalog_name.as_ref());- self.schema_names.append_value(schema_name.as_ref());- self.table_names.append_value(table_name.as_ref());+ self.catalog_names.append_value(catalog_name);+ self.schema_names.append_value(schema_name);+ self.table_names.append_value(table_name);- self.column_names.append_value(column_name.as_ref());+ self.column_names.append_value(field.name());- self.ordinal_positions.append_value(column_position as u64);+ self.ordinal_positions.append_value(field_position as u64);// DataFusion does not support column default values, so nullself.column_defaults.append_null();// "YES if the column is possibly nullable, NO if it is known not nullable. "- let nullable_str = if is_nullable { "YES" } else { "NO" };+ let nullable_str = if field.is_nullable() { "YES" } else { "NO" };self.is_nullables.append_value(nullable_str);// "System supplied type" --> Use debug format of the datatype- self.data_types.append_value(format!("{data_type:?}"));+ self.data_types+ .append_value(format!("{:?}", field.data_type()));// "If data_type identifies a character or bit string type, the// declared maximum length; null for all other data types or@@ -528,7 +526,7 @@ impl InformationSchemaColumnsBuilder {// "Maximum length, in bytes, for binary data, character data,// or text and image data."- let char_len: Option<u64> = match data_type {+ let char_len: Option<u64> = match field.data_type() {Utf8 | Binary => Some(i32::MAX as u64),LargeBinary | LargeUtf8 => Some(i64::MAX as u64),_ => None,@@ -557,7 +555,7 @@ impl InformationSchemaColumnsBuilder {// terms, as specified in the column// numeric_precision_radix. For all other data types, this// column is null.- let (numeric_precision, numeric_radix, numeric_scale) = match data_type {+ let (numeric_precision, numeric_radix, numeric_scale) = match field.data_type() {Int8 | UInt8 => (Some(8), Some(2), None),Int16 | UInt16 => (Some(16), Some(2), None),Int32 | UInt32 => (Some(32), Some(2), None),diff --git a/datafusion/core/src/catalog/mod.rs b/datafusion/core/src/catalog/mod.rsindex 0eabd8698a..b7843ed66b 100644--- a/datafusion/core/src/catalog/mod.rs+++ b/datafusion/core/src/catalog/mod.rs@@ -18,6 +18,10 @@//! This module contains interfaces and default implementations//! of table namespacing concepts, including catalogs and schemas.+// TODO(clippy): Having a `catalog::catalog` module path is unclear and ambiguous.+// The parent module should probably be renamed to something that more accurately+// describes its content. Something along the lines of `database_meta`, `metadata`+// or `meta`, perhaps?#![allow(clippy::module_inception)]pub mod catalog;pub mod information_schema;diff --git a/datafusion/core/src/datasource/mod.rs b/datafusion/core/src/datasource/mod.rsindex 6fa15ab021..dba4112b1e 100644--- a/datafusion/core/src/datasource/mod.rs+++ b/datafusion/core/src/datasource/mod.rs@@ -17,6 +17,9 @@//! DataFusion data sources+// TODO(clippy): Having a `datasource::datasource` module path is unclear and ambiguous.+// The child module should probably be renamed to something that more accurately+// describes its content. Something along the lines of `provider`, or `providers`.#![allow(clippy::module_inception)]pub mod datasource;pub mod default_table_source;diff --git a/datafusion/core/src/physical_optimizer/dist_enforcement.rs b/datafusion/core/src/physical_optimizer/dist_enforcement.rsindex 4c30170ace..5c2a4d27f6 100644--- a/datafusion/core/src/physical_optimizer/dist_enforcement.rs+++ b/datafusion/core/src/physical_optimizer/dist_enforcement.rs@@ -33,7 +33,6 @@ use crate::physical_plan::union::{can_interleave, InterleaveExec, UnionExec};use crate::physical_plan::windows::WindowAggExec;use crate::physical_plan::Partitioning;use crate::physical_plan::{with_new_children_if_necessary, Distribution, ExecutionPlan};-use arrow::datatypes::SchemaRef;use datafusion_common::tree_node::{Transformed, TreeNode, VisitRecursion};use datafusion_expr::logical_plan::JoinType;use datafusion_physical_expr::equivalence::EquivalenceProperties;@@ -41,8 +40,7 @@ use datafusion_physical_expr::expressions::Column;use datafusion_physical_expr::expressions::NoOp;use datafusion_physical_expr::utils::map_columns_before_projection;use datafusion_physical_expr::{- expr_list_eq_strict_order, normalize_expr_with_equivalence_properties, AggregateExpr,- PhysicalExpr, PhysicalSortExpr,+ expr_list_eq_strict_order, normalize_expr_with_equivalence_properties, PhysicalExpr,};use std::sync::Arc;@@ -249,28 +247,13 @@ fn adjust_input_keys_ordering(sort_options.clone(),&join_constructor,)?)- } else if let Some(AggregateExec {- mode,- group_by,- aggr_expr,- filter_expr,- order_by_expr,- input,- input_schema,- ..- }) = plan_any.downcast_ref::<AggregateExec>()- {+ } else if let Some(aggregate_exec) = plan_any.downcast_ref::<AggregateExec>() {if !parent_required.is_empty() {- match mode {+ match aggregate_exec.mode {AggregateMode::FinalPartitioned => Some(reorder_aggregate_keys(requirements.plan.clone(),&parent_required,- group_by,- aggr_expr,- filter_expr,- order_by_expr,- input.clone(),- input_schema,+ aggregate_exec,)?),_ => Some(PlanWithKeyRequirements::new(requirements.plan.clone())),}@@ -369,18 +352,13 @@ where}}-#[allow(clippy::too_many_arguments)]fn reorder_aggregate_keys(agg_plan: Arc<dyn ExecutionPlan>,parent_required: &[Arc<dyn PhysicalExpr>],- group_by: &PhysicalGroupBy,- aggr_expr: &[Arc<dyn AggregateExpr>],- filter_expr: &[Option<Arc<dyn PhysicalExpr>>],- order_by_expr: &[Option<Vec<PhysicalSortExpr>>],- agg_input: Arc<dyn ExecutionPlan>,- input_schema: &SchemaRef,+ agg_exec: &AggregateExec,) -> Result<PlanWithKeyRequirements> {- let out_put_columns = group_by+ let out_put_columns = agg_exec+ .group_by.expr().iter().enumerate()@@ -393,7 +371,7 @@ fn reorder_aggregate_keys(.collect::<Vec<_>>();if parent_required.len() != out_put_exprs.len()- || !group_by.null_expr().is_empty()+ || !agg_exec.group_by.null_expr().is_empty()|| expr_list_eq_strict_order(&out_put_exprs, parent_required){Ok(PlanWithKeyRequirements::new(agg_plan))@@ -412,7 +390,7 @@ fn reorder_aggregate_keys(input_schema,..}) =- agg_input.as_any().downcast_ref::<AggregateExec>()+ agg_exec.input.as_any().downcast_ref::<AggregateExec>(){if matches!(mode, AggregateMode::Partial) {let mut new_group_exprs = vec![];@@ -457,11 +435,11 @@ fn reorder_aggregate_keys(let new_final_agg = Arc::new(AggregateExec::try_new(AggregateMode::FinalPartitioned,new_group_by,- aggr_expr.to_vec(),- filter_expr.to_vec(),- order_by_expr.to_vec(),+ agg_exec.aggr_expr.to_vec(),+ agg_exec.filter_expr.to_vec(),+ agg_exec.order_by_expr.to_vec(),partial_agg,- input_schema.clone(),+ agg_exec.input_schema.clone(),)?);// Need to create a new projection to change the expr ordering backdiff --git a/datafusion/core/src/physical_optimizer/pipeline_fixer.rs b/datafusion/core/src/physical_optimizer/pipeline_fixer.rsindex 7a55aa607f..caae774345 100644--- a/datafusion/core/src/physical_optimizer/pipeline_fixer.rs+++ b/datafusion/core/src/physical_optimizer/pipeline_fixer.rs@@ -278,6 +278,7 @@ mod hash_join_tests {use crate::test_util::UnboundedExec;use arrow::datatypes::{DataType, Field, Schema};use arrow::record_batch::RecordBatch;+ use datafusion_common::utils::DataPtr;use std::sync::Arc;struct TestCase {@@ -610,7 +611,6 @@ mod hash_join_tests {Ok(())}- #[allow(clippy::vtable_address_comparisons)]async fn test_join_with_maybe_swap_unbounded_case(t: TestCase) -> Result<()> {let left_unbounded = t.initial_sources_unbounded.0 == SourceType::Unbounded;let right_unbounded = t.initial_sources_unbounded.1 == SourceType::Unbounded;@@ -677,8 +677,8 @@ mod hash_join_tests {..}) = plan.as_any().downcast_ref::<HashJoinExec>(){- let left_changed = Arc::ptr_eq(left, &right_exec);- let right_changed = Arc::ptr_eq(right, &left_exec);+ let left_changed = Arc::data_ptr_eq(left, &right_exec);+ let right_changed = Arc::data_ptr_eq(right, &left_exec);// If this is not equal, we have a bigger problem.assert_eq!(left_changed, right_changed);assert_eq!(diff --git a/datafusion/core/src/physical_plan/aggregates/bounded_aggregate_stream.rs b/datafusion/core/src/physical_plan/aggregates/bounded_aggregate_stream.rsindex 41eca116bd..bfdb6828ff 100644--- a/datafusion/core/src/physical_plan/aggregates/bounded_aggregate_stream.rs+++ b/datafusion/core/src/physical_plan/aggregates/bounded_aggregate_stream.rs@@ -59,6 +59,8 @@ use datafusion_physical_expr::hash_utils::create_hashes;use datafusion_row::accessor::RowAccessor;use datafusion_row::layout::RowLayout;+use super::AggregateExec;+/// Grouping aggregate with row-format aggregation states inside.////// For each aggregation entry, we use:@@ -119,25 +121,24 @@ pub(crate) struct BoundedAggregateStream {impl BoundedAggregateStream {/// Create a new BoundedAggregateStream- #[allow(clippy::too_many_arguments)]pub fn new(- mode: AggregateMode,- schema: SchemaRef,- group_by: PhysicalGroupBy,- aggr_expr: Vec<Arc<dyn AggregateExpr>>,- filter_expr: Vec<Option<Arc<dyn PhysicalExpr>>>,- input: SendableRecordBatchStream,- baseline_metrics: BaselineMetrics,- batch_size: usize,- scalar_update_factor: usize,+ agg: &AggregateExec,context: Arc<TaskContext>,partition: usize,- // Stores algorithm mode and output ordering- aggregation_ordering: AggregationOrdering,+ aggregation_ordering: AggregationOrdering, // Stores algorithm mode and output ordering) -> Result<Self> {+ let agg_schema = Arc::clone(&agg.schema);+ let agg_group_by = agg.group_by.clone();+ let agg_filter_expr = agg.filter_expr.clone();++ let batch_size = context.session_config().batch_size();+ let scalar_update_factor = context.session_config().agg_scalar_update_factor();+ let input = agg.input.execute(partition, Arc::clone(&context))?;+ let baseline_metrics = BaselineMetrics::new(&agg.metrics, partition);+let timer = baseline_metrics.elapsed_compute().timer();- let mut start_idx = group_by.expr.len();+ let mut start_idx = agg_group_by.expr.len();let mut row_aggr_expr = vec![];let mut row_agg_indices = vec![];let mut row_aggregate_expressions = vec![];@@ -150,19 +151,20 @@ impl BoundedAggregateStream {// Assuming create_schema() always puts group columns in front of aggregation columns, we set// col_idx_base to the group expression count.let all_aggregate_expressions =- aggregates::aggregate_expressions(&aggr_expr, &mode, start_idx)?;- let filter_expressions = match mode {- AggregateMode::Partial | AggregateMode::Single => filter_expr,+ aggregates::aggregate_expressions(&agg.aggr_expr, &agg.mode, start_idx)?;+ let filter_expressions = match agg.mode {+ AggregateMode::Partial | AggregateMode::Single => agg_filter_expr,AggregateMode::Final | AggregateMode::FinalPartitioned => {- vec![None; aggr_expr.len()]+ vec![None; agg.aggr_expr.len()]}};- for ((expr, others), filter) in aggr_expr+ for ((expr, others), filter) in agg+ .aggr_expr.iter().zip(all_aggregate_expressions.into_iter()).zip(filter_expressions.into_iter()){- let n_fields = match mode {+ let n_fields = match agg.mode {// In partial aggregation, we keep additional fields in order to successfully// merge aggregation results downstream.AggregateMode::Partial => expr.state_fields()?.len(),@@ -191,7 +193,7 @@ impl BoundedAggregateStream {let row_aggr_schema = aggr_state_schema(&row_aggr_expr);- let group_schema = group_schema(&schema, group_by.expr.len());+ let group_schema = group_schema(&agg_schema, agg_group_by.expr.len());let row_converter = RowConverter::new(group_schema.fields()@@ -214,9 +216,9 @@ impl BoundedAggregateStream {let exec_state = ExecutionState::ReadingInput;Ok(BoundedAggregateStream {- schema: Arc::clone(&schema),+ schema: agg_schema,input,- mode,+ mode: agg.mode,normal_aggr_expr,normal_aggregate_expressions,normal_filter_expressions,@@ -226,7 +228,7 @@ impl BoundedAggregateStream {row_converter,row_aggr_schema,row_aggr_layout,- group_by,+ group_by: agg_group_by,aggr_state,exec_state,baseline_metrics,diff --git a/datafusion/core/src/physical_plan/aggregates/mod.rs b/datafusion/core/src/physical_plan/aggregates/mod.rsindex 39e42bbd60..d25f887b7f 100644--- a/datafusion/core/src/physical_plan/aggregates/mod.rs+++ b/datafusion/core/src/physical_plan/aggregates/mod.rs@@ -22,9 +22,7 @@ use crate::physical_plan::aggregates::{bounded_aggregate_stream::BoundedAggregateStream, no_grouping::AggregateStream,row_hash::GroupedHashAggregateStream,};-use crate::physical_plan::metrics::{- BaselineMetrics, ExecutionPlanMetricsSet, MetricsSet,-};+use crate::physical_plan::metrics::{ExecutionPlanMetricsSet, MetricsSet};use crate::physical_plan::{DisplayFormatType, Distribution, EquivalenceProperties, ExecutionPlan, Partitioning,SendableRecordBatchStream, Statistics,@@ -551,52 +549,21 @@ impl AggregateExec {partition: usize,context: Arc<TaskContext>,) -> Result<StreamType> {- let batch_size = context.session_config().batch_size();- let scalar_update_factor = context.session_config().agg_scalar_update_factor();- let input = self.input.execute(partition, Arc::clone(&context))?;- let baseline_metrics = BaselineMetrics::new(&self.metrics, partition);-if self.group_by.expr.is_empty() {Ok(StreamType::AggregateStream(AggregateStream::new(- self.mode,- self.schema.clone(),- self.aggr_expr.clone(),- self.filter_expr.clone(),- input,- baseline_metrics,- context,- partition,+ self, context, partition,)?))} else if let Some(aggregation_ordering) = &self.aggregation_ordering {+ let aggregation_ordering = aggregation_ordering.clone();Ok(StreamType::BoundedAggregate(BoundedAggregateStream::new(- self.mode,- self.schema.clone(),- self.group_by.clone(),- self.aggr_expr.clone(),- self.filter_expr.clone(),- input,- baseline_metrics,- batch_size,- scalar_update_factor,+ self,context,partition,- aggregation_ordering.clone(),+ aggregation_ordering,)?))} else {Ok(StreamType::GroupedHashAggregateStream(- GroupedHashAggregateStream::new(- self.mode,- self.schema.clone(),- self.group_by.clone(),- self.aggr_expr.clone(),- self.filter_expr.clone(),- input,- baseline_metrics,- batch_size,- scalar_update_factor,- context,- partition,- )?,+ GroupedHashAggregateStream::new(self, context, partition)?,))}}diff --git a/datafusion/core/src/physical_plan/aggregates/no_grouping.rs b/datafusion/core/src/physical_plan/aggregates/no_grouping.rsindex 7e4d0794b7..4c289eee9b 100644--- a/datafusion/core/src/physical_plan/aggregates/no_grouping.rs+++ b/datafusion/core/src/physical_plan/aggregates/no_grouping.rs@@ -27,7 +27,7 @@ use crate::physical_plan::{RecordBatchStream, SendableRecordBatchStream};use arrow::datatypes::SchemaRef;use arrow::record_batch::RecordBatch;use datafusion_common::Result;-use datafusion_physical_expr::{AggregateExpr, PhysicalExpr};+use datafusion_physical_expr::PhysicalExpr;use futures::stream::BoxStream;use std::borrow::Cow;use std::sync::Arc;@@ -37,6 +37,8 @@ use crate::execution::memory_pool::{MemoryConsumer, MemoryReservation};use crate::physical_plan::filter::batch_filter;use futures::stream::{Stream, StreamExt};+use super::AggregateExec;+/// stream struct for aggregation without grouping columnspub(crate) struct AggregateStream {stream: BoxStream<'static, Result<RecordBatch>>,@@ -63,33 +65,33 @@ struct AggregateStreamInner {}impl AggregateStream {- #[allow(clippy::too_many_arguments)]/// Create a new AggregateStreampub fn new(- mode: AggregateMode,- schema: SchemaRef,- aggr_expr: Vec<Arc<dyn AggregateExpr>>,- filter_expr: Vec<Option<Arc<dyn PhysicalExpr>>>,- input: SendableRecordBatchStream,- baseline_metrics: BaselineMetrics,+ agg: &AggregateExec,context: Arc<TaskContext>,partition: usize,) -> Result<Self> {- let aggregate_expressions = aggregate_expressions(&aggr_expr, &mode, 0)?;- let filter_expressions = match mode {- AggregateMode::Partial | AggregateMode::Single => filter_expr,+ let agg_schema = Arc::clone(&agg.schema);+ let agg_filter_expr = agg.filter_expr.clone();++ let baseline_metrics = BaselineMetrics::new(&agg.metrics, partition);+ let input = agg.input.execute(partition, Arc::clone(&context))?;++ let aggregate_expressions = aggregate_expressions(&agg.aggr_expr, &agg.mode, 0)?;+ let filter_expressions = match agg.mode {+ AggregateMode::Partial | AggregateMode::Single => agg_filter_expr,AggregateMode::Final | AggregateMode::FinalPartitioned => {- vec![None; aggr_expr.len()]+ vec![None; agg.aggr_expr.len()]}};- let accumulators = create_accumulators(&aggr_expr)?;+ let accumulators = create_accumulators(&agg.aggr_expr)?;let reservation = MemoryConsumer::new(format!("AggregateStream[{partition}]")).register(context.memory_pool());let inner = AggregateStreamInner {- schema: Arc::clone(&schema),- mode,+ schema: Arc::clone(&agg.schema),+ mode: agg.mode,input,baseline_metrics,aggregate_expressions,@@ -155,7 +157,10 @@ impl AggregateStream {let stream = stream.fuse();let stream = Box::pin(stream);- Ok(Self { schema, stream })+ Ok(Self {+ schema: agg_schema,+ stream,+ })}}diff --git a/datafusion/core/src/physical_plan/aggregates/row_hash.rs b/datafusion/core/src/physical_plan/aggregates/row_hash.rsindex 0b98513cce..d39bbd80d0 100644--- a/datafusion/core/src/physical_plan/aggregates/row_hash.rs+++ b/datafusion/core/src/physical_plan/aggregates/row_hash.rs@@ -55,6 +55,8 @@ use datafusion_row::layout::RowLayout;use hashbrown::raw::RawTable;use itertools::izip;+use super::AggregateExec;+/// Grouping aggregate with row-format aggregation states inside.////// For each aggregation entry, we use:@@ -112,23 +114,23 @@ pub(crate) struct GroupedHashAggregateStream {impl GroupedHashAggregateStream {/// Create a new GroupedHashAggregateStream- #[allow(clippy::too_many_arguments)]pub fn new(- mode: AggregateMode,- schema: SchemaRef,- group_by: PhysicalGroupBy,- aggr_expr: Vec<Arc<dyn AggregateExpr>>,- filter_expr: Vec<Option<Arc<dyn PhysicalExpr>>>,- input: SendableRecordBatchStream,- baseline_metrics: BaselineMetrics,- batch_size: usize,- scalar_update_factor: usize,+ agg: &AggregateExec,context: Arc<TaskContext>,partition: usize,) -> Result<Self> {+ let agg_schema = Arc::clone(&agg.schema);+ let agg_group_by = agg.group_by.clone();+ let agg_filter_expr = agg.filter_expr.clone();++ let batch_size = context.session_config().batch_size();+ let scalar_update_factor = context.session_config().agg_scalar_update_factor();+ let input = agg.input.execute(partition, Arc::clone(&context))?;+ let baseline_metrics = BaselineMetrics::new(&agg.metrics, partition);+let timer = baseline_metrics.elapsed_compute().timer();- let mut start_idx = group_by.expr.len();+ let mut start_idx = agg_group_by.expr.len();let mut row_aggr_expr = vec![];let mut row_agg_indices = vec![];let mut row_aggregate_expressions = vec![];@@ -141,19 +143,20 @@ impl GroupedHashAggregateStream {// Assuming create_schema() always puts group columns in front of aggregation columns, we set// col_idx_base to the group expression count.let all_aggregate_expressions =- aggregates::aggregate_expressions(&aggr_expr, &mode, start_idx)?;- let filter_expressions = match mode {- AggregateMode::Partial | AggregateMode::Single => filter_expr,+ aggregates::aggregate_expressions(&agg.aggr_expr, &agg.mode, start_idx)?;+ let filter_expressions = match agg.mode {+ AggregateMode::Partial | AggregateMode::Single => agg_filter_expr,AggregateMode::Final | AggregateMode::FinalPartitioned => {- vec![None; aggr_expr.len()]+ vec![None; agg.aggr_expr.len()]}};- for ((expr, others), filter) in aggr_expr+ for ((expr, others), filter) in agg+ .aggr_expr.iter().zip(all_aggregate_expressions.into_iter()).zip(filter_expressions.into_iter()){- let n_fields = match mode {+ let n_fields = match agg.mode {// In partial aggregation, we keep additional fields in order to successfully// merge aggregation results downstream.AggregateMode::Partial => expr.state_fields()?.len(),@@ -182,7 +185,7 @@ impl GroupedHashAggregateStream {let row_aggr_schema = aggr_state_schema(&row_aggr_expr);- let group_schema = group_schema(&schema, group_by.expr.len());+ let group_schema = group_schema(&agg_schema, agg_group_by.expr.len());let row_converter = RowConverter::new(group_schema.fields()@@ -205,9 +208,9 @@ impl GroupedHashAggregateStream {let exec_state = ExecutionState::ReadingInput;Ok(GroupedHashAggregateStream {- schema: Arc::clone(&schema),+ schema: agg_schema,input,- mode,+ mode: agg.mode,normal_aggr_expr,normal_aggregate_expressions,normal_filter_expressions,@@ -217,7 +220,7 @@ impl GroupedHashAggregateStream {row_converter,row_aggr_schema,row_aggr_layout,- group_by,+ group_by: agg_group_by,aggr_state,exec_state,baseline_metrics,diff --git a/datafusion/core/src/physical_plan/file_format/parquet/row_groups.rs b/datafusion/core/src/physical_plan/file_format/parquet/row_groups.rsindex 86cf06620c..efdc168db3 100644--- a/datafusion/core/src/physical_plan/file_format/parquet/row_groups.rs+++ b/datafusion/core/src/physical_plan/file_format/parquet/row_groups.rs@@ -263,6 +263,48 @@ mod tests {};use std::sync::Arc;+ struct PrimitiveTypeField {+ name: &'static str,+ physical_ty: PhysicalType,+ logical_ty: Option<LogicalType>,+ precision: Option<i32>,+ scale: Option<i32>,+ byte_len: Option<i32>,+ }++ impl PrimitiveTypeField {+ fn new(name: &'static str, physical_ty: PhysicalType) -> Self {+ Self {+ name,+ physical_ty,+ logical_ty: None,+ precision: None,+ scale: None,+ byte_len: None,+ }+ }++ fn with_logical_type(mut self, logical_type: LogicalType) -> Self {+ self.logical_ty = Some(logical_type);+ self+ }++ fn with_precision(mut self, precision: i32) -> Self {+ self.precision = Some(precision);+ self+ }++ fn with_scale(mut self, scale: i32) -> Self {+ self.scale = Some(scale);+ self+ }++ fn with_byte_len(mut self, byte_len: i32) -> Self {+ self.byte_len = Some(byte_len);+ self+ }+ }+#[test]fn row_group_pruning_predicate_simple_expr() {use datafusion_expr::{col, lit};@@ -272,14 +314,9 @@ mod tests {let expr = logical2physical(&expr, &schema);let pruning_predicate =PruningPredicate::try_new(expr, Arc::new(schema)).unwrap();- let schema_descr = get_test_schema_descr(vec![(- "c1",- PhysicalType::INT32,- None,- None,- None,- None,- )]);++ let field = PrimitiveTypeField::new("c1", PhysicalType::INT32);+ let schema_descr = get_test_schema_descr(vec![field]);let rgm1 = get_row_group_meta_data(&schema_descr,vec![ParquetStatistics::int32(Some(1), Some(10), None, 0, false)],@@ -306,14 +343,8 @@ mod tests {let pruning_predicate =PruningPredicate::try_new(expr, Arc::new(schema)).unwrap();- let schema_descr = get_test_schema_descr(vec![(- "c1",- PhysicalType::INT32,- None,- None,- None,- None,- )]);+ let field = PrimitiveTypeField::new("c1", PhysicalType::INT32);+ let schema_descr = get_test_schema_descr(vec![field]);let rgm1 = get_row_group_meta_data(&schema_descr,vec![ParquetStatistics::int32(None, None, None, 0, false)],@@ -347,8 +378,8 @@ mod tests {let pruning_predicate = PruningPredicate::try_new(expr, schema.clone()).unwrap();let schema_descr = get_test_schema_descr(vec![- ("c1", PhysicalType::INT32, None, None, None, None),- ("c2", PhysicalType::INT32, None, None, None, None),+ PrimitiveTypeField::new("c1", PhysicalType::INT32),+ PrimitiveTypeField::new("c2", PhysicalType::INT32),]);let rgm1 = get_row_group_meta_data(&schema_descr,@@ -392,8 +423,8 @@ mod tests {fn gen_row_group_meta_data_for_pruning_predicate() -> Vec<RowGroupMetaData> {let schema_descr = get_test_schema_descr(vec![- ("c1", PhysicalType::INT32, None, None, None, None),- ("c2", PhysicalType::BOOLEAN, None, None, None, None),+ PrimitiveTypeField::new("c1", PhysicalType::INT32),+ PrimitiveTypeField::new("c2", PhysicalType::BOOLEAN),]);let rgm1 = get_row_group_meta_data(&schema_descr,@@ -469,17 +500,14 @@ mod tests {// The type of scalar value if decimal(9,2), don't need to do castlet schema =Schema::new(vec![Field::new("c1", DataType::Decimal128(9, 2), false)]);- let schema_descr = get_test_schema_descr(vec![(- "c1",- PhysicalType::INT32,- Some(LogicalType::Decimal {+ let field = PrimitiveTypeField::new("c1", PhysicalType::INT32)+ .with_logical_type(LogicalType::Decimal {scale: 2,precision: 9,- }),- Some(9),- Some(2),- None,- )]);+ })+ .with_scale(2)+ .with_precision(9);+ let schema_descr = get_test_schema_descr(vec![field]);let expr = col("c1").gt(lit(ScalarValue::Decimal128(Some(500), 9, 2)));let expr = logical2physical(&expr, &schema);let pruning_predicate =@@ -525,17 +553,15 @@ mod tests {// The decimal of arrow is decimal(5,2), the decimal of parquet is decimal(9,0)let schema =Schema::new(vec![Field::new("c1", DataType::Decimal128(9, 0), false)]);- let schema_descr = get_test_schema_descr(vec![(- "c1",- PhysicalType::INT32,- Some(LogicalType::Decimal {++ let field = PrimitiveTypeField::new("c1", PhysicalType::INT32)+ .with_logical_type(LogicalType::Decimal {scale: 0,precision: 9,- }),- Some(9),- Some(0),- None,- )]);+ })+ .with_scale(0)+ .with_precision(9);+ let schema_descr = get_test_schema_descr(vec![field]);let expr = cast(col("c1"), DataType::Decimal128(11, 2)).gt(cast(lit(ScalarValue::Decimal128(Some(500), 5, 2)),Decimal128(11, 2),@@ -587,17 +613,14 @@ mod tests {// INT64: c1 < 5, the c1 is decimal(18,2)let schema =Schema::new(vec![Field::new("c1", DataType::Decimal128(18, 2), false)]);- let schema_descr = get_test_schema_descr(vec![(- "c1",- PhysicalType::INT64,- Some(LogicalType::Decimal {+ let field = PrimitiveTypeField::new("c1", PhysicalType::INT64)+ .with_logical_type(LogicalType::Decimal {scale: 2,precision: 18,- }),- Some(18),- Some(2),- None,- )]);+ })+ .with_scale(2)+ .with_precision(18);+ let schema_descr = get_test_schema_descr(vec![field]);let expr = col("c1").lt(lit(ScalarValue::Decimal128(Some(500), 18, 2)));let expr = logical2physical(&expr, &schema);let pruning_predicate =@@ -638,17 +661,15 @@ mod tests {// the type of parquet is decimal(18,2)let schema =Schema::new(vec![Field::new("c1", DataType::Decimal128(18, 2), false)]);- let schema_descr = get_test_schema_descr(vec![(- "c1",- PhysicalType::FIXED_LEN_BYTE_ARRAY,- Some(LogicalType::Decimal {+ let field = PrimitiveTypeField::new("c1", PhysicalType::FIXED_LEN_BYTE_ARRAY)+ .with_logical_type(LogicalType::Decimal {scale: 2,precision: 18,- }),- Some(18),- Some(2),- Some(16),- )]);+ })+ .with_scale(2)+ .with_precision(18)+ .with_byte_len(16);+ let schema_descr = get_test_schema_descr(vec![field]);// cast the type of c1 to decimal(28,3)let left = cast(col("c1"), DataType::Decimal128(28, 3));let expr = left.eq(lit(ScalarValue::Decimal128(Some(100000), 28, 3)));@@ -710,17 +731,15 @@ mod tests {// the type of parquet is decimal(18,2)let schema =Schema::new(vec![Field::new("c1", DataType::Decimal128(18, 2), false)]);- let schema_descr = get_test_schema_descr(vec![(- "c1",- PhysicalType::BYTE_ARRAY,- Some(LogicalType::Decimal {+ let field = PrimitiveTypeField::new("c1", PhysicalType::BYTE_ARRAY)+ .with_logical_type(LogicalType::Decimal {scale: 2,precision: 18,- }),- Some(18),- Some(2),- Some(16),- )]);+ })+ .with_scale(2)+ .with_precision(18)+ .with_byte_len(16);+ let schema_descr = get_test_schema_descr(vec![field]);// cast the type of c1 to decimal(28,3)let left = cast(col("c1"), DataType::Decimal128(28, 3));let expr = left.eq(lit(ScalarValue::Decimal128(Some(100000), 28, 3)));@@ -789,46 +808,25 @@ mod tests {.unwrap()}- #[allow(clippy::type_complexity)]- fn get_test_schema_descr(- fields: Vec<(- &str,- PhysicalType,- Option<LogicalType>,- Option<i32>, // precision- Option<i32>, // scale- Option<i32>, // length of bytes- )>,- ) -> SchemaDescPtr {+ fn get_test_schema_descr(fields: Vec<PrimitiveTypeField>) -> SchemaDescPtr {use parquet::schema::types::{SchemaDescriptor, Type as SchemaType};let mut schema_fields = fields.iter()- .map(|(n, t, logical, precision, scale, length)| {- let mut builder = SchemaType::primitive_type_builder(n, *t);+ .map(|field| {+ let mut builder =+ SchemaType::primitive_type_builder(field.name, field.physical_ty);// add logical type for the parquet field- match logical {- None => {}- Some(logical_type) => {- builder = builder.with_logical_type(Some(logical_type.clone()));- }- };- match precision {- None => {}- Some(v) => {- builder = builder.with_precision(*v);- }- };- match scale {- None => {}- Some(v) => {- builder = builder.with_scale(*v);- }+ if let Some(logical_type) = &field.logical_ty {+ builder = builder.with_logical_type(Some(logical_type.clone()));}- match length {- None => {}- Some(v) => {- builder = builder.with_length(*v);- }+ if let Some(precision) = field.precision {+ builder = builder.with_precision(precision);+ }+ if let Some(scale) = field.scale {+ builder = builder.with_scale(scale);+ }+ if let Some(byte_len) = field.byte_len {+ builder = builder.with_length(byte_len);}Arc::new(builder.build().unwrap())})diff --git a/datafusion/core/src/physical_plan/filter.rs b/datafusion/core/src/physical_plan/filter.rsindex 67c990a7e3..74f6caa76b 100644--- a/datafusion/core/src/physical_plan/filter.rs+++ b/datafusion/core/src/physical_plan/filter.rs@@ -341,6 +341,7 @@ mod tests {use crate::test::exec::StatisticsExec;use crate::test_util;use arrow::datatypes::{DataType, Field, Schema};+ use datafusion_common::utils::DataPtr;use datafusion_common::ColumnStatistics;use datafusion_common::ScalarValue;use datafusion_expr::Operator;@@ -378,7 +379,6 @@ mod tests {}#[tokio::test]- #[allow(clippy::vtable_address_comparisons)]async fn with_new_children() -> Result<()> {let schema = test_util::aggr_test_schema();let partitions = 4;@@ -391,11 +391,11 @@ mod tests {Arc::new(FilterExec::try_new(predicate, input.clone())?);let new_filter = filter.clone().with_new_children(vec![input.clone()])?;- assert!(!Arc::ptr_eq(&filter, &new_filter));+ assert!(!Arc::data_ptr_eq(&filter, &new_filter));let new_filter2 =with_new_children_if_necessary(filter.clone(), vec![input])?.into();- assert!(Arc::ptr_eq(&filter, &new_filter2));+ assert!(Arc::data_ptr_eq(&filter, &new_filter2));Ok(())}diff --git a/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs b/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rsindex 66c3cbbce6..5602ed4cf3 100644--- a/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs+++ b/datafusion/core/src/physical_plan/joins/symmetric_hash_join.rs@@ -1596,7 +1596,7 @@ mod tests {assert_eq!((i, first_line), (i, second_line));}}- #[allow(clippy::too_many_arguments)]+async fn partitioned_sym_join_with_filter(left: Arc<dyn ExecutionPlan>,right: Arc<dyn ExecutionPlan>,@@ -1647,7 +1647,7 @@ mod tests {Ok(batches)}- #[allow(clippy::too_many_arguments)]+async fn partitioned_hash_join_with_filter(left: Arc<dyn ExecutionPlan>,right: Arc<dyn ExecutionPlan>,diff --git a/datafusion/core/src/physical_plan/mod.rs b/datafusion/core/src/physical_plan/mod.rsindex bedbf84c17..a9881ad435 100644--- a/datafusion/core/src/physical_plan/mod.rs+++ b/datafusion/core/src/physical_plan/mod.rs@@ -29,6 +29,7 @@ use crate::physical_plan::expressions::PhysicalSortExpr;use arrow::datatypes::SchemaRef;use arrow::record_batch::RecordBatch;+use datafusion_common::utils::DataPtr;pub use datafusion_expr::Accumulator;pub use datafusion_expr::ColumnarValue;pub use datafusion_physical_expr::aggregate::row_accumulator::RowAccumulator;@@ -270,9 +271,6 @@ pub fn need_data_exchange(plan: Arc<dyn ExecutionPlan>) -> bool {/// Returns a copy of this plan if we change any child according to the pointer comparison./// The size of `children` must be equal to the size of `ExecutionPlan::children()`.-/// Allow the vtable address comparisons for ExecutionPlan Trait Objects,it is harmless even-/// in the case of 'false-native'.-#[allow(clippy::vtable_address_comparisons)]pub fn with_new_children_if_necessary(plan: Arc<dyn ExecutionPlan>,children: Vec<Arc<dyn ExecutionPlan>>,@@ -286,7 +284,7 @@ pub fn with_new_children_if_necessary(|| children.iter().zip(old_children.iter())- .any(|(c1, c2)| !Arc::ptr_eq(c1, c2))+ .any(|(c1, c2)| !Arc::data_ptr_eq(c1, c2)){Ok(Transformed::Yes(plan.with_new_children(children)?))} else {diff --git a/datafusion/expr/src/expr.rs b/datafusion/expr/src/expr.rsindex 230e2fb916..1f7ee74a02 100644--- a/datafusion/expr/src/expr.rs+++ b/datafusion/expr/src/expr.rs@@ -766,6 +766,7 @@ impl Expr {}/// Return `!self`+ // TODO(clippy): May be solved by https://github.com/apache/arrow-datafusion/issues/6437#[allow(clippy::should_implement_trait)]pub fn not(self) -> Expr {!self@@ -817,13 +818,11 @@ impl Expr {}/// Return `IsNull(Box(self))- #[allow(clippy::wrong_self_convention)]pub fn is_null(self) -> Expr {Expr::IsNull(Box::new(self))}/// Return `IsNotNull(Box(self))- #[allow(clippy::wrong_self_convention)]pub fn is_not_null(self) -> Expr {Expr::IsNotNull(Box::new(self))}diff --git a/datafusion/expr/src/expr_fn.rs b/datafusion/expr/src/expr_fn.rsindex 6aa51be566..6b0a09baf9 100644--- a/datafusion/expr/src/expr_fn.rs+++ b/datafusion/expr/src/expr_fn.rs@@ -691,7 +691,6 @@ pub fn create_udf(/// Creates a new UDAF with a specific signature, state type and return type./// The signature and state type must match the `Accumulator's implementation`.-#[allow(clippy::rc_buffer)]pub fn create_udaf(name: &str,input_type: DataType,diff --git a/datafusion/expr/src/logical_plan/ddl.rs b/datafusion/expr/src/logical_plan/ddl.rsindex 9ddafea3b6..2b02295b79 100644--- a/datafusion/expr/src/logical_plan/ddl.rs+++ b/datafusion/expr/src/logical_plan/ddl.rs@@ -199,7 +199,6 @@ pub struct CreateExternalTable {}// Hashing refers to a subset of fields considered in PartialEq.-#[allow(clippy::derived_hash_with_manual_eq)]impl Hash for CreateExternalTable {fn hash<H: Hasher>(&self, state: &mut H) {self.schema.hash(state);diff --git a/datafusion/expr/src/logical_plan/extension.rs b/datafusion/expr/src/logical_plan/extension.rsindex 7d03353d9b..f87ca45f14 100644--- a/datafusion/expr/src/logical_plan/extension.rs+++ b/datafusion/expr/src/logical_plan/extension.rs@@ -84,6 +84,12 @@ pub trait UserDefinedLogicalNode: fmt::Debug + Send + Sync {/// of self.inputs and self.exprs.////// So, `self.from_template(exprs, ..).expressions() == exprs+ //+ // TODO(clippy): This should probably be renamed to use a `with_*` prefix. Something+ // like `with_template`, or `with_exprs_and_inputs`.+ //+ // Also, I think `ExtensionPlanNode` has been renamed to `UserDefinedLogicalNode`+ // but the doc comments have not been updated.#[allow(clippy::wrong_self_convention)]fn from_template(&self,@@ -228,6 +234,12 @@ pub trait UserDefinedLogicalNodeCore:/// of self.inputs and self.exprs.////// So, `self.from_template(exprs, ..).expressions() == exprs+ //+ // TODO(clippy): This should probably be renamed to use a `with_*` prefix. Something+ // like `with_template`, or `with_exprs_and_inputs`.+ //+ // Also, I think `ExtensionPlanNode` has been renamed to `UserDefinedLogicalNode`+ // but the doc comments have not been updated.#[allow(clippy::wrong_self_convention)]fn from_template(&self, exprs: &[Expr], inputs: &[LogicalPlan]) -> Self;}diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex d95edb7e7c..077187561f 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -1497,19 +1497,22 @@ pub struct Analyze {}/// Extension operator defined outside of DataFusion-#[allow(clippy::derived_hash_with_manual_eq)] // see impl PartialEq for explanation+// TODO(clippy): This clippy `allow` should be removed if+// the manual `PartialEq` is removed in favor of a derive.+// (see `PartialEq` the impl for details.)+#[allow(clippy::derived_hash_with_manual_eq)]#[derive(Clone, Eq, Hash)]pub struct Extension {/// The runtime extension operatorpub node: Arc<dyn UserDefinedLogicalNode>,}+// `PartialEq` cannot be derived for types containing `Arc<dyn Trait>`.+// This manual implementation should be removed if+// https://github.com/rust-lang/rust/issues/39128 is fixed.impl PartialEq for Extension {- #[allow(clippy::op_ref)] // clippy false positivefn eq(&self, other: &Self) -> bool {- // must be manually derived due to a bug in #[derive(PartialEq)]- // https://github.com/rust-lang/rust/issues/39128- &self.node == &other.node+ self.node.eq(&other.node)}}@@ -1771,7 +1774,6 @@ impl Display for PlanType {/// Represents some sort of execution plan, in String form#[derive(Debug, Clone, PartialEq, Eq, Hash)]-#[allow(clippy::rc_buffer)]pub struct StringifiedPlan {/// An identifier of what type of plan this string representspub plan_type: PlanType,diff --git a/datafusion/expr/src/tree_node/expr.rs b/datafusion/expr/src/tree_node/expr.rsindex 3c98844109..3ecf54c9ce 100644--- a/datafusion/expr/src/tree_node/expr.rs+++ b/datafusion/expr/src/tree_node/expr.rs@@ -363,7 +363,6 @@ impl TreeNode for Expr {}}-#[allow(clippy::boxed_local)]fn transform_boxed<F>(boxed_expr: Box<Expr>, transform: &mut F) -> Result<Box<Expr>>whereF: FnMut(Expr) -> Result<Expr>,diff --git a/datafusion/physical-expr/src/expressions/cast.rs b/datafusion/physical-expr/src/expressions/cast.rsindex 07038498ca..8e4e1b57e8 100644--- a/datafusion/physical-expr/src/expressions/cast.rs+++ b/datafusion/physical-expr/src/expressions/cast.rs@@ -277,6 +277,7 @@ mod tests {macro_rules! generic_test_cast {($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr, $CAST_OPTIONS:expr) => {{let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);+ let a_vec_len = $A_VEC.len();let a = $A_ARRAY::from($A_VEC);let batch =RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;@@ -301,7 +302,7 @@ mod tests {assert_eq!(*result.data_type(), $TYPE);// verify that the len is correct- assert_eq!(result.len(), $A_VEC.len());+ assert_eq!(result.len(), a_vec_len);// verify that the data itself is downcastablelet result = result@@ -633,7 +634,6 @@ mod tests {Ok(())}- #[allow(clippy::redundant_clone)]#[test]fn test_cast_i64_t64() -> Result<()> {let original = vec![1, 2, 3, 4, 5];@@ -644,7 +644,7 @@ mod tests {generic_test_cast!(Int64Array,DataType::Int64,- original.clone(),+ original,TimestampNanosecondArray,DataType::Timestamp(TimeUnit::Nanosecond, None),expected,diff --git a/datafusion/physical-expr/src/expressions/try_cast.rs b/datafusion/physical-expr/src/expressions/try_cast.rsindex bceed0a34c..bbb29d6fb5 100644--- a/datafusion/physical-expr/src/expressions/try_cast.rs+++ b/datafusion/physical-expr/src/expressions/try_cast.rs@@ -209,6 +209,7 @@ mod tests {macro_rules! generic_test_cast {($A_ARRAY:ident, $A_TYPE:expr, $A_VEC:expr, $TYPEARRAY:ident, $TYPE:expr, $VEC:expr) => {{let schema = Schema::new(vec![Field::new("a", $A_TYPE, true)]);+ let a_vec_len = $A_VEC.len();let a = $A_ARRAY::from($A_VEC);let batch =RecordBatch::try_new(Arc::new(schema.clone()), vec![Arc::new(a)])?;@@ -232,7 +233,7 @@ mod tests {assert_eq!(*result.data_type(), $TYPE);// verify that the len is correct- assert_eq!(result.len(), $A_VEC.len());+ assert_eq!(result.len(), a_vec_len);// verify that the data itself is downcastablelet result = result@@ -517,7 +518,6 @@ mod tests {Ok(())}- #[allow(clippy::redundant_clone)]#[test]fn test_cast_i64_t64() -> Result<()> {let original = vec![1, 2, 3, 4, 5];@@ -528,7 +528,7 @@ mod tests {generic_test_cast!(Int64Array,DataType::Int64,- original.clone(),+ original,TimestampNanosecondArray,DataType::Timestamp(TimeUnit::Nanosecond, None),expecteddiff --git a/datafusion/physical-expr/src/physical_expr.rs b/datafusion/physical-expr/src/physical_expr.rsindex 04b4393676..d6dd14e8a1 100644--- a/datafusion/physical-expr/src/physical_expr.rs+++ b/datafusion/physical-expr/src/physical_expr.rs@@ -19,6 +19,7 @@ use arrow::datatypes::{DataType, Schema};use arrow::record_batch::RecordBatch;+use datafusion_common::utils::DataPtr;use datafusion_common::{ColumnStatistics, DataFusionError, Result, ScalarValue, Statistics,};@@ -235,9 +236,6 @@ impl ExprBoundaries {/// Returns a copy of this expr if we change any child according to the pointer comparison./// The size of `children` must be equal to the size of `PhysicalExpr::children()`.-/// Allow the vtable address comparisons for PhysicalExpr Trait Objects,it is harmless even-/// in the case of 'false-native'.-#[allow(clippy::vtable_address_comparisons)]pub fn with_new_children_if_necessary(expr: Arc<dyn PhysicalExpr>,children: Vec<Arc<dyn PhysicalExpr>>,@@ -251,7 +249,7 @@ pub fn with_new_children_if_necessary(|| children.iter().zip(old_children.iter())- .any(|(c1, c2)| !Arc::ptr_eq(c1, c2))+ .any(|(c1, c2)| !Arc::data_ptr_eq(c1, c2)){expr.with_new_children(children)} else {diff --git a/datafusion/physical-expr/src/string_expressions.rs b/datafusion/physical-expr/src/string_expressions.rsindex 93d4d86da5..34319b9d97 100644--- a/datafusion/physical-expr/src/string_expressions.rs+++ b/datafusion/physical-expr/src/string_expressions.rs@@ -235,7 +235,6 @@ pub fn concat(args: &[ColumnarValue]) -> Result<ColumnarValue> {.map(|index| {let mut owned_string: String = "".to_owned();for arg in args {- #[allow(clippy::collapsible_match)]match arg {ColumnarValue::Scalar(ScalarValue::Utf8(maybe_value)) => {if let Some(value) = maybe_value {diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rsindex 94e26f2cf2..4c360dc378 100644--- a/datafusion/proto/src/physical_plan/mod.rs+++ b/datafusion/proto/src/physical_plan/mod.rs@@ -61,7 +61,7 @@ use crate::protobuf::physical_expr_node::ExprType;use crate::protobuf::physical_plan_node::PhysicalPlanType;use crate::protobuf::repartition_exec_node::PartitionMethod;use crate::protobuf::{self, PhysicalPlanNode};-use crate::{convert_required, into_physical_plan, into_required};+use crate::{convert_required, into_required};pub mod from_proto;pub mod to_proto;@@ -86,7 +86,6 @@ impl AsExecutionPlan for PhysicalPlanNode {})}- #[allow(clippy::only_used_in_recursion)]fn try_into_physical_plan(&self,registry: &dyn FunctionRegistry,@@ -109,11 +108,11 @@ impl AsExecutionPlan for PhysicalPlanNode {explain.verbose,))),PhysicalPlanType::Projection(projection) => {- let input: Arc<dyn ExecutionPlan> = into_physical_plan!(- projection.input,+ let input: Arc<dyn ExecutionPlan> = into_physical_plan(+ &projection.input,registry,runtime,- extension_codec+ extension_codec,)?;let exprs = projection.expr@@ -129,11 +128,11 @@ impl AsExecutionPlan for PhysicalPlanNode {Ok(Arc::new(ProjectionExec::try_new(exprs, input)?))}PhysicalPlanType::Filter(filter) => {- let input: Arc<dyn ExecutionPlan> = into_physical_plan!(- filter.input,+ let input: Arc<dyn ExecutionPlan> = into_physical_plan(+ &filter.input,registry,runtime,- extension_codec+ extension_codec,)?;let predicate = filter.expr@@ -184,11 +183,11 @@ impl AsExecutionPlan for PhysicalPlanNode {)?)))}PhysicalPlanType::CoalesceBatches(coalesce_batches) => {- let input: Arc<dyn ExecutionPlan> = into_physical_plan!(- coalesce_batches.input,+ let input: Arc<dyn ExecutionPlan> = into_physical_plan(+ &coalesce_batches.input,registry,runtime,- extension_codec+ extension_codec,)?;Ok(Arc::new(CoalesceBatchesExec::new(input,@@ -197,15 +196,15 @@ impl AsExecutionPlan for PhysicalPlanNode {}PhysicalPlanType::Merge(merge) => {let input: Arc<dyn ExecutionPlan> =- into_physical_plan!(merge.input, registry, runtime, extension_codec)?;+ into_physical_plan(&merge.input, registry, runtime, extension_codec)?;Ok(Arc::new(CoalescePartitionsExec::new(input)))}PhysicalPlanType::Repartition(repart) => {- let input: Arc<dyn ExecutionPlan> = into_physical_plan!(- repart.input,+ let input: Arc<dyn ExecutionPlan> = into_physical_plan(+ &repart.input,registry,runtime,- extension_codec+ extension_codec,)?;match repart.partition_method {Some(PartitionMethod::Hash(ref hash_part)) => {@@ -248,7 +247,7 @@ impl AsExecutionPlan for PhysicalPlanNode {}PhysicalPlanType::GlobalLimit(limit) => {let input: Arc<dyn ExecutionPlan> =- into_physical_plan!(limit.input, registry, runtime, extension_codec)?;+ into_physical_plan(&limit.input, registry, runtime, extension_codec)?;let fetch = if limit.fetch >= 0 {Some(limit.fetch as usize)} else {@@ -262,15 +261,15 @@ impl AsExecutionPlan for PhysicalPlanNode {}PhysicalPlanType::LocalLimit(limit) => {let input: Arc<dyn ExecutionPlan> =- into_physical_plan!(limit.input, registry, runtime, extension_codec)?;+ into_physical_plan(&limit.input, registry, runtime, extension_codec)?;Ok(Arc::new(LocalLimitExec::new(input, limit.fetch as usize)))}PhysicalPlanType::Window(window_agg) => {- let input: Arc<dyn ExecutionPlan> = into_physical_plan!(- window_agg.input,+ let input: Arc<dyn ExecutionPlan> = into_physical_plan(+ &window_agg.input,registry,runtime,- extension_codec+ extension_codec,)?;let input_schema = window_agg.input_schema@@ -338,11 +337,11 @@ impl AsExecutionPlan for PhysicalPlanNode {)?))}PhysicalPlanType::Aggregate(hash_agg) => {- let input: Arc<dyn ExecutionPlan> = into_physical_plan!(- hash_agg.input,+ let input: Arc<dyn ExecutionPlan> = into_physical_plan(+ &hash_agg.input,registry,runtime,- extension_codec+ extension_codec,)?;let mode = protobuf::AggregateMode::from_i32(hash_agg.mode).ok_or_else(|| {@@ -491,17 +490,17 @@ impl AsExecutionPlan for PhysicalPlanNode {)?))}PhysicalPlanType::HashJoin(hashjoin) => {- let left: Arc<dyn ExecutionPlan> = into_physical_plan!(- hashjoin.left,+ let left: Arc<dyn ExecutionPlan> = into_physical_plan(+ &hashjoin.left,registry,runtime,- extension_codec+ extension_codec,)?;- let right: Arc<dyn ExecutionPlan> = into_physical_plan!(- hashjoin.right,+ let right: Arc<dyn ExecutionPlan> = into_physical_plan(+ &hashjoin.right,registry,runtime,- extension_codec+ extension_codec,)?;let on: Vec<(Column, Column)> = hashjoin.on@@ -590,17 +589,17 @@ impl AsExecutionPlan for PhysicalPlanNode {Ok(Arc::new(UnionExec::new(inputs)))}PhysicalPlanType::CrossJoin(crossjoin) => {- let left: Arc<dyn ExecutionPlan> = into_physical_plan!(- crossjoin.left,+ let left: Arc<dyn ExecutionPlan> = into_physical_plan(+ &crossjoin.left,registry,runtime,- extension_codec+ extension_codec,)?;- let right: Arc<dyn ExecutionPlan> = into_physical_plan!(- crossjoin.right,+ let right: Arc<dyn ExecutionPlan> = into_physical_plan(+ &crossjoin.right,registry,runtime,- extension_codec+ extension_codec,)?;Ok(Arc::new(CrossJoinExec::new(left, right)))}@@ -610,7 +609,7 @@ impl AsExecutionPlan for PhysicalPlanNode {}PhysicalPlanType::Sort(sort) => {let input: Arc<dyn ExecutionPlan> =- into_physical_plan!(sort.input, registry, runtime, extension_codec)?;+ into_physical_plan(&sort.input, registry, runtime, extension_codec)?;let exprs = sort.expr.iter()@@ -657,7 +656,7 @@ impl AsExecutionPlan for PhysicalPlanNode {}PhysicalPlanType::SortPreservingMerge(sort) => {let input: Arc<dyn ExecutionPlan> =- into_physical_plan!(sort.input, registry, runtime, extension_codec)?;+ into_physical_plan(&sort.input, registry, runtime, extension_codec)?;let exprs = sort.expr.iter()@@ -1237,17 +1236,17 @@ impl PhysicalExtensionCodec for DefaultPhysicalExtensionCodec {}}-#[macro_export]-macro_rules! into_physical_plan {- ($PB:expr, $REG:expr, $RUNTIME:expr, $CODEC:expr) => {{- if let Some(field) = $PB.as_ref() {- field- .as_ref()- .try_into_physical_plan($REG, $RUNTIME, $CODEC)- } else {- Err(proto_error("Missing required field in protobuf"))- }- }};+fn into_physical_plan(+ node: &Option<Box<PhysicalPlanNode>>,+ registry: &dyn FunctionRegistry,+ runtime: &RuntimeEnv,+ extension_codec: &dyn PhysicalExtensionCodec,+) -> Result<Arc<dyn ExecutionPlan>, DataFusionError> {+ if let Some(field) = node {+ field.try_into_physical_plan(registry, runtime, extension_codec)+ } else {+ Err(proto_error("Missing required field in protobuf"))+ }}#[cfg(test)]diff --git a/datafusion/substrait/src/logical_plan/consumer.rs b/datafusion/substrait/src/logical_plan/consumer.rsindex e38f02c638..9343d31130 100644--- a/datafusion/substrait/src/logical_plan/consumer.rs+++ b/datafusion/substrait/src/logical_plan/consumer.rs@@ -404,8 +404,6 @@ pub async fn from_substrait_rel(.iter().map(|i| scan.projected_schema.field(*i).clone()).collect();- // clippy thinks this clone is redundant but it is not- #[allow(clippy::redundant_clone)]let mut scan = scan.clone();scan.projection = Some(column_indices);scan.projected_schema =