Skip to content

Apache DataFusion SQL Query Engine

Enable `clone_on_ref_ptr` clippy lint on core crate (#13338)

Namgung Chan1bbe13f013de
diff --git a/datafusion/core/src/catalog_common/information_schema.rs b/datafusion/core/src/catalog_common/information_schema.rs
index 72f842d367..1d4a3c15f7 100644
--- a/datafusion/core/src/catalog_common/information_schema.rs
+++ b/datafusion/core/src/catalog_common/information_schema.rs
@@ -493,7 +493,7 @@ impl SchemaProvider for InformationSchemaProvider {
};
Ok(Some(Arc::new(
- StreamingTable::try_new(table.schema().clone(), vec![table]).unwrap(),
+ StreamingTable::try_new(Arc::clone(table.schema()), vec![table]).unwrap(),
)))
}
@@ -526,7 +526,7 @@ impl InformationSchemaTables {
schema_names: StringBuilder::new(),
table_names: StringBuilder::new(),
table_types: StringBuilder::new(),
- schema: self.schema.clone(),
+ schema: Arc::clone(&self.schema),
}
}
}
@@ -540,7 +540,7 @@ impl PartitionStream for InformationSchemaTables {
let mut builder = self.builder();
let config = self.config.clone();
Box::pin(RecordBatchStreamAdapter::new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
// TODO: Stream this
futures::stream::once(async move {
config.make_tables(&mut builder).await?;
@@ -582,7 +582,7 @@ impl InformationSchemaTablesBuilder {
fn finish(&mut self) -> RecordBatch {
RecordBatch::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
vec![
Arc::new(self.catalog_names.finish()),
Arc::new(self.schema_names.finish()),
@@ -618,7 +618,7 @@ impl InformationSchemaViews {
schema_names: StringBuilder::new(),
table_names: StringBuilder::new(),
definitions: StringBuilder::new(),
- schema: self.schema.clone(),
+ schema: Arc::clone(&self.schema),
}
}
}
@@ -632,7 +632,7 @@ impl PartitionStream for InformationSchemaViews {
let mut builder = self.builder();
let config = self.config.clone();
Box::pin(RecordBatchStreamAdapter::new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
// TODO: Stream this
futures::stream::once(async move {
config.make_views(&mut builder).await?;
@@ -670,7 +670,7 @@ impl InformationSchemaViewBuilder {
fn finish(&mut self) -> RecordBatch {
RecordBatch::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
vec![
Arc::new(self.catalog_names.finish()),
Arc::new(self.schema_names.finish()),
@@ -733,7 +733,7 @@ impl InformationSchemaColumns {
numeric_scales: UInt64Builder::with_capacity(default_capacity),
datetime_precisions: UInt64Builder::with_capacity(default_capacity),
interval_types: StringBuilder::new(),
- schema: self.schema.clone(),
+ schema: Arc::clone(&self.schema),
}
}
}
@@ -747,7 +747,7 @@ impl PartitionStream for InformationSchemaColumns {
let mut builder = self.builder();
let config = self.config.clone();
Box::pin(RecordBatchStreamAdapter::new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
// TODO: Stream this
futures::stream::once(async move {
config.make_columns(&mut builder).await?;
@@ -876,7 +876,7 @@ impl InformationSchemaColumnsBuilder {
fn finish(&mut self) -> RecordBatch {
RecordBatch::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
vec![
Arc::new(self.catalog_names.finish()),
Arc::new(self.schema_names.finish()),
@@ -921,7 +921,7 @@ impl InformationSchemata {
fn builder(&self) -> InformationSchemataBuilder {
InformationSchemataBuilder {
- schema: self.schema.clone(),
+ schema: Arc::clone(&self.schema),
catalog_name: StringBuilder::new(),
schema_name: StringBuilder::new(),
schema_owner: StringBuilder::new(),
@@ -967,7 +967,7 @@ impl InformationSchemataBuilder {
fn finish(&mut self) -> RecordBatch {
RecordBatch::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
vec![
Arc::new(self.catalog_name.finish()),
Arc::new(self.schema_name.finish()),
@@ -991,7 +991,7 @@ impl PartitionStream for InformationSchemata {
let mut builder = self.builder();
let config = self.config.clone();
Box::pin(RecordBatchStreamAdapter::new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
// TODO: Stream this
futures::stream::once(async move {
config.make_schemata(&mut builder).await;
@@ -1023,7 +1023,7 @@ impl InformationSchemaDfSettings {
names: StringBuilder::new(),
values: StringBuilder::new(),
descriptions: StringBuilder::new(),
- schema: self.schema.clone(),
+ schema: Arc::clone(&self.schema),
}
}
}
@@ -1037,7 +1037,7 @@ impl PartitionStream for InformationSchemaDfSettings {
let config = self.config.clone();
let mut builder = self.builder();
Box::pin(RecordBatchStreamAdapter::new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
// TODO: Stream this
futures::stream::once(async move {
// create a mem table with the names of tables
@@ -1064,7 +1064,7 @@ impl InformationSchemaDfSettingsBuilder {
fn finish(&mut self) -> RecordBatch {
RecordBatch::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
vec![
Arc::new(self.names.finish()),
Arc::new(self.values.finish()),
@@ -1102,7 +1102,7 @@ impl InformationSchemaRoutines {
fn builder(&self) -> InformationSchemaRoutinesBuilder {
InformationSchemaRoutinesBuilder {
- schema: self.schema.clone(),
+ schema: Arc::clone(&self.schema),
specific_catalog: StringBuilder::new(),
specific_schema: StringBuilder::new(),
specific_name: StringBuilder::new(),
@@ -1161,7 +1161,7 @@ impl InformationSchemaRoutinesBuilder {
fn finish(&mut self) -> RecordBatch {
RecordBatch::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
vec![
Arc::new(self.specific_catalog.finish()),
Arc::new(self.specific_schema.finish()),
@@ -1189,7 +1189,7 @@ impl PartitionStream for InformationSchemaRoutines {
let config = self.config.clone();
let mut builder = self.builder();
Box::pin(RecordBatchStreamAdapter::new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
futures::stream::once(async move {
config.make_routines(
ctx.scalar_functions(),
@@ -1229,7 +1229,7 @@ impl InformationSchemaParameters {
fn builder(&self) -> InformationSchemaParametersBuilder {
InformationSchemaParametersBuilder {
- schema: self.schema.clone(),
+ schema: Arc::clone(&self.schema),
specific_catalog: StringBuilder::new(),
specific_schema: StringBuilder::new(),
specific_name: StringBuilder::new(),
@@ -1295,7 +1295,7 @@ impl InformationSchemaParametersBuilder {
fn finish(&mut self) -> RecordBatch {
RecordBatch::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
vec![
Arc::new(self.specific_catalog.finish()),
Arc::new(self.specific_schema.finish()),
@@ -1321,7 +1321,7 @@ impl PartitionStream for InformationSchemaParameters {
let config = self.config.clone();
let mut builder = self.builder();
Box::pin(RecordBatchStreamAdapter::new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
futures::stream::once(async move {
config.make_parameters(
ctx.scalar_functions(),
diff --git a/datafusion/core/src/catalog_common/listing_schema.rs b/datafusion/core/src/catalog_common/listing_schema.rs
index 67952770f4..dc55a07ef8 100644
--- a/datafusion/core/src/catalog_common/listing_schema.rs
+++ b/datafusion/core/src/catalog_common/listing_schema.rs
@@ -148,7 +148,8 @@ impl ListingSchemaProvider {
},
)
.await?;
- let _ = self.register_table(table_name.to_string(), provider.clone())?;
+ let _ =
+ self.register_table(table_name.to_string(), Arc::clone(&provider))?;
}
}
Ok(())
@@ -190,7 +191,7 @@ impl SchemaProvider for ListingSchemaProvider {
self.tables
.lock()
.expect("Can't lock tables")
- .insert(name, table.clone());
+ .insert(name, Arc::clone(&table));
Ok(Some(table))
}
diff --git a/datafusion/core/src/catalog_common/memory.rs b/datafusion/core/src/catalog_common/memory.rs
index f251466168..6cdefc31f1 100644
--- a/datafusion/core/src/catalog_common/memory.rs
+++ b/datafusion/core/src/catalog_common/memory.rs
@@ -67,7 +67,7 @@ impl CatalogProviderList for MemoryCatalogProviderList {
}
fn catalog(&self, name: &str) -> Option<Arc<dyn CatalogProvider>> {
- self.catalogs.get(name).map(|c| c.value().clone())
+ self.catalogs.get(name).map(|c| Arc::clone(c.value()))
}
}
@@ -102,7 +102,7 @@ impl CatalogProvider for MemoryCatalogProvider {
}
fn schema(&self, name: &str) -> Option<Arc<dyn SchemaProvider>> {
- self.schemas.get(name).map(|s| s.value().clone())
+ self.schemas.get(name).map(|s| Arc::clone(s.value()))
}
fn register_schema(
@@ -175,7 +175,7 @@ impl SchemaProvider for MemorySchemaProvider {
&self,
name: &str,
) -> datafusion_common::Result<Option<Arc<dyn TableProvider>>, DataFusionError> {
- Ok(self.tables.get(name).map(|table| table.value().clone()))
+ Ok(self.tables.get(name).map(|table| Arc::clone(table.value())))
}
fn register_table(
diff --git a/datafusion/core/src/datasource/avro_to_arrow/reader.rs b/datafusion/core/src/datasource/avro_to_arrow/reader.rs
index 5dc53c5c86..e6310cec74 100644
--- a/datafusion/core/src/datasource/avro_to_arrow/reader.rs
+++ b/datafusion/core/src/datasource/avro_to_arrow/reader.rs
@@ -142,7 +142,7 @@ impl<'a, R: Read> Reader<'a, R> {
Ok(Self {
array_reader: AvroArrowArrayReader::try_new(
reader,
- schema.clone(),
+ Arc::clone(&schema),
projection,
)?,
schema,
@@ -153,7 +153,7 @@ impl<'a, R: Read> Reader<'a, R> {
/// Returns the schema of the reader, useful for getting the schema without reading
/// record batches
pub fn schema(&self) -> SchemaRef {
- self.schema.clone()
+ Arc::clone(&self.schema)
}
}
diff --git a/datafusion/core/src/datasource/cte_worktable.rs b/datafusion/core/src/datasource/cte_worktable.rs
index 9504721cec..b63755f644 100644
--- a/datafusion/core/src/datasource/cte_worktable.rs
+++ b/datafusion/core/src/datasource/cte_worktable.rs
@@ -77,7 +77,7 @@ impl TableProvider for CteWorkTable {
}
fn schema(&self) -> SchemaRef {
- self.table_schema.clone()
+ Arc::clone(&self.table_schema)
}
fn table_type(&self) -> TableType {
@@ -94,7 +94,7 @@ impl TableProvider for CteWorkTable {
// TODO: pushdown filters and limits
Ok(Arc::new(WorkTableExec::new(
self.name.clone(),
- self.table_schema.clone(),
+ Arc::clone(&self.table_schema),
)))
}
diff --git a/datafusion/core/src/datasource/default_table_source.rs b/datafusion/core/src/datasource/default_table_source.rs
index b4a5a76fc9..c37c3b97f4 100644
--- a/datafusion/core/src/datasource/default_table_source.rs
+++ b/datafusion/core/src/datasource/default_table_source.rs
@@ -96,7 +96,7 @@ pub fn source_as_provider(
.as_any()
.downcast_ref::<DefaultTableSource>()
{
- Some(source) => Ok(source.table_provider.clone()),
+ Some(source) => Ok(Arc::clone(&source.table_provider)),
_ => internal_err!("TableSource was not DefaultTableSource"),
}
}
diff --git a/datafusion/core/src/datasource/empty.rs b/datafusion/core/src/datasource/empty.rs
index bc5b82bd8c..abda7fa9ec 100644
--- a/datafusion/core/src/datasource/empty.rs
+++ b/datafusion/core/src/datasource/empty.rs
@@ -61,7 +61,7 @@ impl TableProvider for EmptyTable {
}
fn schema(&self) -> SchemaRef {
- self.schema.clone()
+ Arc::clone(&self.schema)
}
fn table_type(&self) -> TableType {
diff --git a/datafusion/core/src/datasource/file_format/arrow.rs b/datafusion/core/src/datasource/file_format/arrow.rs
index c10ebbd6c9..fd0935c6e0 100644
--- a/datafusion/core/src/datasource/file_format/arrow.rs
+++ b/datafusion/core/src/datasource/file_format/arrow.rs
@@ -186,7 +186,7 @@ impl FileFormat for ArrowFormat {
return not_impl_err!("Overwrites are not implemented yet for Arrow format");
}
- let sink_schema = conf.output_schema().clone();
+ let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(ArrowFileSink::new(conf));
Ok(Arc::new(DataSinkExec::new(
@@ -229,7 +229,7 @@ impl ArrowFileSink {
.collect::<Vec<_>>(),
))
} else {
- self.config.output_schema().clone()
+ Arc::clone(self.config.output_schema())
}
}
}
@@ -302,7 +302,7 @@ impl DataSink for ArrowFileSink {
let mut object_store_writer = create_writer(
FileCompressionType::UNCOMPRESSED,
&path,
- object_store.clone(),
+ Arc::clone(&object_store),
)
.await?;
file_write_tasks.spawn(async move {
diff --git a/datafusion/core/src/datasource/file_format/csv.rs b/datafusion/core/src/datasource/file_format/csv.rs
index 2b5570dc33..d59e2bf71d 100644
--- a/datafusion/core/src/datasource/file_format/csv.rs
+++ b/datafusion/core/src/datasource/file_format/csv.rs
@@ -417,7 +417,7 @@ impl FileFormat for CsvFormat {
let writer_options = CsvWriterOptions::try_from(&options)?;
- let sink_schema = conf.output_schema().clone();
+ let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(CsvSink::new(conf, writer_options));
Ok(Arc::new(DataSinkExec::new(
diff --git a/datafusion/core/src/datasource/file_format/json.rs b/datafusion/core/src/datasource/file_format/json.rs
index 6a7bfd2040..4f51dd5ae1 100644
--- a/datafusion/core/src/datasource/file_format/json.rs
+++ b/datafusion/core/src/datasource/file_format/json.rs
@@ -264,7 +264,7 @@ impl FileFormat for JsonFormat {
let writer_options = JsonWriterOptions::try_from(&self.options)?;
- let sink_schema = conf.output_schema().clone();
+ let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(JsonSink::new(conf, writer_options));
Ok(Arc::new(DataSinkExec::new(
diff --git a/datafusion/core/src/datasource/file_format/mod.rs b/datafusion/core/src/datasource/file_format/mod.rs
index b0e1df5183..5c9eb7f20a 100644
--- a/datafusion/core/src/datasource/file_format/mod.rs
+++ b/datafusion/core/src/datasource/file_format/mod.rs
@@ -230,7 +230,7 @@ pub fn file_type_to_format(
.as_any()
.downcast_ref::<DefaultFileType>()
{
- Some(source) => Ok(source.file_format_factory.clone()),
+ Some(source) => Ok(Arc::clone(&source.file_format_factory)),
_ => internal_err!("FileType was not DefaultFileType"),
}
}
@@ -255,7 +255,7 @@ pub fn transform_schema_to_view(schema: &Schema) -> Schema {
DataType::Binary | DataType::LargeBinary => {
field_with_new_type(field, DataType::BinaryView)
}
- _ => field.clone(),
+ _ => Arc::clone(field),
})
.collect();
Schema::new_with_metadata(transformed_fields, schema.metadata.clone())
@@ -297,7 +297,7 @@ pub(crate) fn coerce_file_schema_to_view_type(
Some(DataType::BinaryView),
DataType::Binary | DataType::LargeBinary,
) => field_with_new_type(field, DataType::BinaryView),
- _ => field.clone(),
+ _ => Arc::clone(field),
},
)
.collect();
@@ -317,7 +317,7 @@ pub fn transform_binary_to_string(schema: &Schema) -> Schema {
DataType::Binary => field_with_new_type(field, DataType::Utf8),
DataType::LargeBinary => field_with_new_type(field, DataType::LargeUtf8),
DataType::BinaryView => field_with_new_type(field, DataType::Utf8View),
- _ => field.clone(),
+ _ => Arc::clone(field),
})
.collect();
Schema::new_with_metadata(transformed_fields, schema.metadata.clone())
@@ -365,7 +365,7 @@ pub(crate) fn coerce_file_schema_to_string_type(
transform = true;
field_with_new_type(field, DataType::Utf8View)
}
- _ => field.clone(),
+ _ => Arc::clone(field),
},
)
.collect();
diff --git a/datafusion/core/src/datasource/file_format/parquet.rs b/datafusion/core/src/datasource/file_format/parquet.rs
index e27a13b6e7..c1314bdb86 100644
--- a/datafusion/core/src/datasource/file_format/parquet.rs
+++ b/datafusion/core/src/datasource/file_format/parquet.rs
@@ -434,7 +434,7 @@ impl FileFormat for ParquetFormat {
return not_impl_err!("Overwrites are not implemented yet for Parquet");
}
- let sink_schema = conf.output_schema().clone();
+ let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(ParquetSink::new(conf, self.options.clone()));
Ok(Arc::new(DataSinkExec::new(
@@ -748,7 +748,7 @@ impl ParquetSink {
schema.metadata().clone(),
))
} else {
- self.config.output_schema().clone()
+ Arc::clone(self.config.output_schema())
}
}
@@ -833,7 +833,7 @@ impl DataSink for ParquetSink {
let mut writer = self
.create_async_arrow_writer(
&path,
- object_store.clone(),
+ Arc::clone(&object_store),
parquet_props.writer_options().clone(),
)
.await?;
@@ -857,7 +857,7 @@ impl DataSink for ParquetSink {
// manage compressed blocks themselves.
FileCompressionType::UNCOMPRESSED,
&path,
- object_store.clone(),
+ Arc::clone(&object_store),
)
.await?;
let schema = self.get_writer_schema();
@@ -1044,8 +1044,8 @@ fn spawn_parquet_parallel_serialization_task(
let max_row_group_rows = writer_props.max_row_group_size();
let (mut column_writer_handles, mut col_array_channels) =
spawn_column_parallel_row_group_writer(
- schema.clone(),
- writer_props.clone(),
+ Arc::clone(&schema),
+ Arc::clone(&writer_props),
max_buffer_rb,
&pool,
)?;
@@ -1057,15 +1057,23 @@ fn spawn_parquet_parallel_serialization_task(
// function.
loop {
if current_rg_rows + rb.num_rows() < max_row_group_rows {
- send_arrays_to_col_writers(&col_array_channels, &rb, schema.clone())
- .await?;
+ send_arrays_to_col_writers(
+ &col_array_channels,
+ &rb,
+ Arc::clone(&schema),
+ )
+ .await?;
current_rg_rows += rb.num_rows();
break;
} else {
let rows_left = max_row_group_rows - current_rg_rows;
let a = rb.slice(0, rows_left);
- send_arrays_to_col_writers(&col_array_channels, &a, schema.clone())
- .await?;
+ send_arrays_to_col_writers(
+ &col_array_channels,
+ &a,
+ Arc::clone(&schema),
+ )
+ .await?;
// Signal the parallel column writers that the RowGroup is done, join and finalize RowGroup
// on a separate task, so that we can immediately start on the next RG before waiting
@@ -1088,8 +1096,8 @@ fn spawn_parquet_parallel_serialization_task(
(column_writer_handles, col_array_channels) =
spawn_column_parallel_row_group_writer(
- schema.clone(),
- writer_props.clone(),
+ Arc::clone(&schema),
+ Arc::clone(&writer_props),
max_buffer_rb,
&pool,
)?;
@@ -1192,15 +1200,15 @@ async fn output_single_parquet_file_parallelized(
let launch_serialization_task = spawn_parquet_parallel_serialization_task(
data,
serialize_tx,
- output_schema.clone(),
- arc_props.clone(),
+ Arc::clone(&output_schema),
+ Arc::clone(&arc_props),
parallel_options,
Arc::clone(&pool),
);
let file_metadata = concatenate_parallel_row_groups(
serialize_rx,
- output_schema.clone(),
- arc_props.clone(),
+ Arc::clone(&output_schema),
+ Arc::clone(&arc_props),
object_store_writer,
pool,
)
diff --git a/datafusion/core/src/datasource/file_format/write/demux.rs b/datafusion/core/src/datasource/file_format/write/demux.rs
index 56ded495c8..71cf747c32 100644
--- a/datafusion/core/src/datasource/file_format/write/demux.rs
+++ b/datafusion/core/src/datasource/file_format/write/demux.rs
@@ -100,7 +100,7 @@ pub(crate) fn start_demuxer_task(
keep_partition_by_columns: bool,
) -> (SpawnedTask<Result<()>>, DemuxedStreamReceiver) {
let (tx, rx) = mpsc::unbounded_channel();
- let context = context.clone();
+ let context = Arc::clone(context);
let single_file_output =
!base_output_path.is_collection() && base_output_path.file_extension().is_some();
let task = match partition_by {
@@ -478,7 +478,7 @@ fn remove_partition_by_columns(
.zip(parted_batch.schema().fields())
.filter_map(|(a, f)| {
if !partition_names.contains(&f.name()) {
- Some((a.clone(), (**f).clone()))
+ Some((Arc::clone(a), (**f).clone()))
} else {
None
}
diff --git a/datafusion/core/src/datasource/file_format/write/orchestration.rs b/datafusion/core/src/datasource/file_format/write/orchestration.rs
index 6f27e6f388..457481b5ad 100644
--- a/datafusion/core/src/datasource/file_format/write/orchestration.rs
+++ b/datafusion/core/src/datasource/file_format/write/orchestration.rs
@@ -94,7 +94,7 @@ pub(crate) async fn serialize_rb_stream_to_object_store(
// subsequent batches, so we track that here.
let mut initial = true;
while let Some(batch) = data_rx.recv().await {
- let serializer_clone = serializer.clone();
+ let serializer_clone = Arc::clone(&serializer);
let task = SpawnedTask::spawn(async move {
let num_rows = batch.num_rows();
let bytes = serializer_clone.serialize(batch, initial)?;
@@ -279,7 +279,8 @@ pub(crate) async fn stateless_multipart_put(
});
while let Some((location, rb_stream)) = file_stream_rx.recv().await {
let serializer = get_serializer();
- let writer = create_writer(compression, &location, object_store.clone()).await?;
+ let writer =
+ create_writer(compression, &location, Arc::clone(&object_store)).await?;
tx_file_bundle
.send((rb_stream, serializer, writer))
diff --git a/datafusion/core/src/datasource/listing/table.rs b/datafusion/core/src/datasource/listing/table.rs
index b937a28e93..ffe49dd2ba 100644
--- a/datafusion/core/src/datasource/listing/table.rs
+++ b/datafusion/core/src/datasource/listing/table.rs
@@ -1137,14 +1137,14 @@ impl ListingTable {
.infer_stats(
ctx,
store,
- self.file_schema.clone(),
+ Arc::clone(&self.file_schema),
&part_file.object_meta,
)
.await?;
let statistics = Arc::new(statistics);
self.collected_statistics.put_with_extra(
&part_file.object_meta.location,
- statistics.clone(),
+ Arc::clone(&statistics),
&part_file.object_meta,
);
Ok(statistics)
diff --git a/datafusion/core/src/datasource/listing_table_factory.rs b/datafusion/core/src/datasource/listing_table_factory.rs
index 1f6a19ceb5..636d1623c5 100644
--- a/datafusion/core/src/datasource/listing_table_factory.rs
+++ b/datafusion/core/src/datasource/listing_table_factory.rs
@@ -127,7 +127,7 @@ impl TableProviderFactory for ListingTableFactory {
// See: https://github.com/apache/datafusion/issues/7317
None => {
let schema = options.infer_schema(session_state, &table_path).await?;
- let df_schema = schema.clone().to_dfschema()?;
+ let df_schema = Arc::clone(&schema).to_dfschema()?;
let column_refs: HashSet<_> = cmd
.order_exprs
.iter()
diff --git a/datafusion/core/src/datasource/memory.rs b/datafusion/core/src/datasource/memory.rs
index 3c2d1b0205..c1e0bea0b3 100644
--- a/datafusion/core/src/datasource/memory.rs
+++ b/datafusion/core/src/datasource/memory.rs
@@ -139,7 +139,7 @@ impl MemTable {
for part_idx in 0..partition_count {
let task = state.task_ctx();
- let exec = exec.clone();
+ let exec = Arc::clone(&exec);
join_set.spawn(async move {
let stream = exec.execute(part_idx, task)?;
common::collect(stream).await
@@ -162,7 +162,7 @@ impl MemTable {
}
}
- let exec = MemoryExec::try_new(&data, schema.clone(), None)?;
+ let exec = MemoryExec::try_new(&data, Arc::clone(&schema), None)?;
if let Some(num_partitions) = output_partitions {
let exec = RepartitionExec::try_new(
@@ -183,9 +183,9 @@ impl MemTable {
output_partitions.push(batches);
}
- return MemTable::try_new(schema.clone(), output_partitions);
+ return MemTable::try_new(Arc::clone(&schema), output_partitions);
}
- MemTable::try_new(schema.clone(), data)
+ MemTable::try_new(Arc::clone(&schema), data)
}
}
@@ -196,7 +196,7 @@ impl TableProvider for MemTable {
}
fn schema(&self) -> SchemaRef {
- self.schema.clone()
+ Arc::clone(&self.schema)
}
fn constraints(&self) -> Option<&Constraints> {
@@ -297,7 +297,7 @@ impl TableProvider for MemTable {
Ok(Arc::new(DataSinkExec::new(
input,
sink,
- self.schema.clone(),
+ Arc::clone(&self.schema),
None,
)))
}
diff --git a/datafusion/core/src/datasource/physical_plan/arrow_file.rs b/datafusion/core/src/datasource/physical_plan/arrow_file.rs
index 39625a55ca..df5ede5e83 100644
--- a/datafusion/core/src/datasource/physical_plan/arrow_file.rs
+++ b/datafusion/core/src/datasource/physical_plan/arrow_file.rs
@@ -63,7 +63,7 @@ impl ArrowExec {
let (projected_schema, projected_statistics, projected_output_ordering) =
base_config.project();
let cache = Self::compute_properties(
- projected_schema.clone(),
+ Arc::clone(&projected_schema),
&projected_output_ordering,
&base_config,
);
@@ -207,7 +207,7 @@ impl ExecutionPlan for ArrowExec {
Some(Arc::new(Self {
base_config: new_config,
projected_statistics: self.projected_statistics.clone(),
- projected_schema: self.projected_schema.clone(),
+ projected_schema: Arc::clone(&self.projected_schema),
projected_output_ordering: self.projected_output_ordering.clone(),
metrics: self.metrics.clone(),
cache: self.cache.clone(),
@@ -222,7 +222,7 @@ pub struct ArrowOpener {
impl FileOpener for ArrowOpener {
fn open(&self, file_meta: FileMeta) -> Result<FileOpenFuture> {
- let object_store = self.object_store.clone();
+ let object_store = Arc::clone(&self.object_store);
let projection = self.projection.clone();
Ok(Box::pin(async move {
let range = file_meta.range.clone();
diff --git a/datafusion/core/src/datasource/physical_plan/avro.rs b/datafusion/core/src/datasource/physical_plan/avro.rs
index ce72c40874..2e83be212f 100644
--- a/datafusion/core/src/datasource/physical_plan/avro.rs
+++ b/datafusion/core/src/datasource/physical_plan/avro.rs
@@ -51,7 +51,7 @@ impl AvroExec {
let (projected_schema, projected_statistics, projected_output_ordering) =
base_config.project();
let cache = Self::compute_properties(
- projected_schema.clone(),
+ Arc::clone(&projected_schema),
&projected_output_ordering,
&base_config,
);
@@ -175,7 +175,7 @@ impl ExecutionPlan for AvroExec {
Some(Arc::new(Self {
base_config: new_config,
projected_statistics: self.projected_statistics.clone(),
- projected_schema: self.projected_schema.clone(),
+ projected_schema: Arc::clone(&self.projected_schema),
projected_output_ordering: self.projected_output_ordering.clone(),
metrics: self.metrics.clone(),
cache: self.cache.clone(),
@@ -205,7 +205,7 @@ mod private {
fn open<R: std::io::Read>(&self, reader: R) -> Result<AvroReader<'static, R>> {
AvroReader::try_new(
reader,
- self.schema.clone(),
+ Arc::clone(&self.schema),
self.batch_size,
self.projection.clone(),
)
@@ -218,7 +218,7 @@ mod private {
impl FileOpener for AvroOpener {
fn open(&self, file_meta: FileMeta) -> Result<FileOpenFuture> {
- let config = self.config.clone();
+ let config = Arc::clone(&self.config);
Ok(Box::pin(async move {
let r = config.object_store.get(file_meta.location()).await?;
match r.payload {
diff --git a/datafusion/core/src/datasource/physical_plan/csv.rs b/datafusion/core/src/datasource/physical_plan/csv.rs
index 5beffc3b05..1679acf303 100644
--- a/datafusion/core/src/datasource/physical_plan/csv.rs
+++ b/datafusion/core/src/datasource/physical_plan/csv.rs
@@ -521,7 +521,7 @@ impl CsvConfig {
}
fn builder(&self) -> csv::ReaderBuilder {
- let mut builder = csv::ReaderBuilder::new(self.file_schema.clone())
+ let mut builder = csv::ReaderBuilder::new(Arc::clone(&self.file_schema))
.with_delimiter(self.delimiter)
.with_batch_size(self.batch_size)
.with_header(self.has_header)
@@ -611,7 +611,7 @@ impl FileOpener for CsvOpener {
);
}
- let store = self.config.object_store.clone();
+ let store = Arc::clone(&self.config.object_store);
Ok(Box::pin(async move {
// Current partition contains bytes [start_byte, end_byte) (might contain incomplete lines at boundaries)
@@ -698,12 +698,12 @@ pub async fn plan_to_csv(
let store = task_ctx.runtime_env().object_store(&object_store_url)?;
let mut join_set = JoinSet::new();
for i in 0..plan.output_partitioning().partition_count() {
- let storeref = store.clone();
- let plan: Arc<dyn ExecutionPlan> = plan.clone();
+ let storeref = Arc::clone(&store);
+ let plan: Arc<dyn ExecutionPlan> = Arc::clone(&plan);
let filename = format!("{}/part-{i}.csv", parsed.prefix());
let file = object_store::path::Path::parse(filename)?;
- let mut stream = plan.execute(i, task_ctx.clone())?;
+ let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;
join_set.spawn(async move {
let mut buf_writer = BufWriter::new(storeref, file.clone());
let mut buffer = Vec::with_capacity(1024);
diff --git a/datafusion/core/src/datasource/physical_plan/file_stream.rs b/datafusion/core/src/datasource/physical_plan/file_stream.rs
index 9d78a0f2e3..18cda4524a 100644
--- a/datafusion/core/src/datasource/physical_plan/file_stream.rs
+++ b/datafusion/core/src/datasource/physical_plan/file_stream.rs
@@ -24,6 +24,7 @@
use std::collections::VecDeque;
use std::mem;
use std::pin::Pin;
+use std::sync::Arc;
use std::task::{Context, Poll};
use crate::datasource::listing::PartitionedFile;
@@ -252,7 +253,7 @@ impl<F: FileOpener> FileStream<F> {
) -> Result<Self> {
let (projected_schema, ..) = config.project();
let pc_projector = PartitionColumnProjector::new(
- projected_schema.clone(),
+ Arc::clone(&projected_schema),
&config
.table_partition_cols
.iter()
@@ -510,7 +511,7 @@ impl<F: FileOpener> Stream for FileStream<F> {
impl<F: FileOpener> RecordBatchStream for FileStream<F> {
fn schema(&self) -> SchemaRef {
- self.projected_schema.clone()
+ Arc::clone(&self.projected_schema)
}
}
diff --git a/datafusion/core/src/datasource/physical_plan/json.rs b/datafusion/core/src/datasource/physical_plan/json.rs
index cf8f129a50..6cb9d9df70 100644
--- a/datafusion/core/src/datasource/physical_plan/json.rs
+++ b/datafusion/core/src/datasource/physical_plan/json.rs
@@ -262,8 +262,8 @@ impl FileOpener for JsonOpener {
///
/// See [`CsvOpener`](super::CsvOpener) for an example.
fn open(&self, file_meta: FileMeta) -> Result<FileOpenFuture> {
- let store = self.object_store.clone();
- let schema = self.projected_schema.clone();
+ let store = Arc::clone(&self.object_store);
+ let schema = Arc::clone(&self.projected_schema);
let batch_size = self.batch_size;
let file_compression_type = self.file_compression_type.to_owned();
@@ -355,12 +355,12 @@ pub async fn plan_to_json(
let store = task_ctx.runtime_env().object_store(&object_store_url)?;
let mut join_set = JoinSet::new();
for i in 0..plan.output_partitioning().partition_count() {
- let storeref = store.clone();
- let plan: Arc<dyn ExecutionPlan> = plan.clone();
+ let storeref = Arc::clone(&store);
+ let plan: Arc<dyn ExecutionPlan> = Arc::clone(&plan);
let filename = format!("{}/part-{i}.json", parsed.prefix());
let file = object_store::path::Path::parse(filename)?;
- let mut stream = plan.execute(i, task_ctx.clone())?;
+ let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;
join_set.spawn(async move {
let mut buf_writer = BufWriter::new(storeref, file.clone());
diff --git a/datafusion/core/src/datasource/physical_plan/parquet/mod.rs b/datafusion/core/src/datasource/physical_plan/parquet/mod.rs
index 980f796a53..9dd0b9e206 100644
--- a/datafusion/core/src/datasource/physical_plan/parquet/mod.rs
+++ b/datafusion/core/src/datasource/physical_plan/parquet/mod.rs
@@ -425,7 +425,7 @@ impl ParquetExecBuilder {
let pruning_predicate = predicate
.clone()
.and_then(|predicate_expr| {
- match PruningPredicate::try_new(predicate_expr, file_schema.clone()) {
+ match PruningPredicate::try_new(predicate_expr, Arc::clone(file_schema)) {
Ok(pruning_predicate) => Some(Arc::new(pruning_predicate)),
Err(e) => {
debug!("Could not create pruning predicate for: {e}");
@@ -439,7 +439,7 @@ impl ParquetExecBuilder {
let page_pruning_predicate = predicate
.as_ref()
.map(|predicate_expr| {
- PagePruningAccessPlanFilter::new(predicate_expr, file_schema.clone())
+ PagePruningAccessPlanFilter::new(predicate_expr, Arc::clone(file_schema))
})
.map(Arc::new);
@@ -807,7 +807,7 @@ impl ExecutionPlan for ParquetExec {
predicate: self.predicate.clone(),
pruning_predicate: self.pruning_predicate.clone(),
page_pruning_predicate: self.page_pruning_predicate.clone(),
- table_schema: self.base_config.file_schema.clone(),
+ table_schema: Arc::clone(&self.base_config.file_schema),
metadata_size_hint: self.metadata_size_hint,
metrics: self.metrics.clone(),
parquet_file_reader_factory,
diff --git a/datafusion/core/src/datasource/physical_plan/parquet/opener.rs b/datafusion/core/src/datasource/physical_plan/parquet/opener.rs
index 3492bcc85f..883f296f3b 100644
--- a/datafusion/core/src/datasource/physical_plan/parquet/opener.rs
+++ b/datafusion/core/src/datasource/physical_plan/parquet/opener.rs
@@ -105,11 +105,11 @@ impl FileOpener for ParquetOpener {
SchemaRef::from(self.table_schema.project(&self.projection)?);
let schema_adapter = self
.schema_adapter_factory
- .create(projected_schema, self.table_schema.clone());
+ .create(projected_schema, Arc::clone(&self.table_schema));
let predicate = self.predicate.clone();
let pruning_predicate = self.pruning_predicate.clone();
let page_pruning_predicate = self.page_pruning_predicate.clone();
- let table_schema = self.table_schema.clone();
+ let table_schema = Arc::clone(&self.table_schema);
let reorder_predicates = self.reorder_filters;
let pushdown_filters = self.pushdown_filters;
let enable_page_index = should_enable_page_index(
diff --git a/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rs b/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rs
index ced07de974..07f50bca1d 100644
--- a/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rs
+++ b/datafusion/core/src/datasource/physical_plan/parquet/page_filter.rs
@@ -118,14 +118,16 @@ impl PagePruningAccessPlanFilter {
let predicates = split_conjunction(expr)
.into_iter()
.filter_map(|predicate| {
- let pp =
- match PruningPredicate::try_new(predicate.clone(), schema.clone()) {
- Ok(pp) => pp,
- Err(e) => {
- debug!("Ignoring error creating page pruning predicate: {e}");
- return None;
- }
- };
+ let pp = match PruningPredicate::try_new(
+ Arc::clone(predicate),
+ Arc::clone(&schema),
+ ) {
+ Ok(pp) => pp,
+ Err(e) => {
+ debug!("Ignoring error creating page pruning predicate: {e}");
+ return None;
+ }
+ };
if pp.always_true() {
debug!("Ignoring always true page pruning predicate: {predicate}");
diff --git a/datafusion/core/src/datasource/physical_plan/parquet/row_filter.rs b/datafusion/core/src/datasource/physical_plan/parquet/row_filter.rs
index e876f840d1..a97e7c7d25 100644
--- a/datafusion/core/src/datasource/physical_plan/parquet/row_filter.rs
+++ b/datafusion/core/src/datasource/physical_plan/parquet/row_filter.rs
@@ -541,7 +541,7 @@ pub fn build_row_filter(
let mut candidates: Vec<FilterCandidate> = predicates
.into_iter()
.map(|expr| {
- FilterCandidateBuilder::new(expr.clone(), file_schema, table_schema)
+ FilterCandidateBuilder::new(Arc::clone(expr), file_schema, table_schema)
.build(metadata)
})
.collect::<Result<Vec<_>, _>>()?
diff --git a/datafusion/core/src/datasource/physical_plan/parquet/writer.rs b/datafusion/core/src/datasource/physical_plan/parquet/writer.rs
index 0c0c546910..00926dc233 100644
--- a/datafusion/core/src/datasource/physical_plan/parquet/writer.rs
+++ b/datafusion/core/src/datasource/physical_plan/parquet/writer.rs
@@ -40,14 +40,14 @@ pub async fn plan_to_parquet(
let store = task_ctx.runtime_env().object_store(&object_store_url)?;
let mut join_set = JoinSet::new();
for i in 0..plan.output_partitioning().partition_count() {
- let plan: Arc<dyn ExecutionPlan> = plan.clone();
+ let plan: Arc<dyn ExecutionPlan> = Arc::clone(&plan);
let filename = format!("{}/part-{i}.parquet", parsed.prefix());
let file = Path::parse(filename)?;
let propclone = writer_properties.clone();
- let storeref = store.clone();
+ let storeref = Arc::clone(&store);
let buf_writer = BufWriter::new(storeref, file.clone());
- let mut stream = plan.execute(i, task_ctx.clone())?;
+ let mut stream = plan.execute(i, Arc::clone(&task_ctx))?;
join_set.spawn(async move {
let mut writer =
AsyncArrowWriter::try_new(buf_writer, plan.schema(), propclone)?;
diff --git a/datafusion/core/src/datasource/schema_adapter.rs b/datafusion/core/src/datasource/schema_adapter.rs
index 71f947e2c0..b27cf9c5f8 100644
--- a/datafusion/core/src/datasource/schema_adapter.rs
+++ b/datafusion/core/src/datasource/schema_adapter.rs
@@ -288,9 +288,9 @@ impl SchemaAdapter for DefaultSchemaAdapter {
Ok((
Arc::new(SchemaMapping {
- projected_table_schema: self.projected_table_schema.clone(),
+ projected_table_schema: Arc::clone(&self.projected_table_schema),
field_mappings,
- table_schema: self.table_schema.clone(),
+ table_schema: Arc::clone(&self.table_schema),
}),
projection,
))
@@ -372,7 +372,7 @@ impl SchemaMapper for SchemaMapping {
// Necessary to handle empty batches
let options = RecordBatchOptions::new().with_row_count(Some(batch.num_rows()));
- let schema = self.projected_table_schema.clone();
+ let schema = Arc::clone(&self.projected_table_schema);
let record_batch = RecordBatch::try_new_with_options(schema, cols, &options)?;
Ok(record_batch)
}
diff --git a/datafusion/core/src/datasource/stream.rs b/datafusion/core/src/datasource/stream.rs
index 34023fbbb6..d8fad5b6cd 100644
--- a/datafusion/core/src/datasource/stream.rs
+++ b/datafusion/core/src/datasource/stream.rs
@@ -187,7 +187,7 @@ impl StreamProvider for FileStreamProvider {
fn reader(&self) -> Result<Box<dyn RecordBatchReader>> {
let file = File::open(&self.location)?;
- let schema = self.schema.clone();
+ let schema = Arc::clone(&self.schema);
match &self.encoding {
StreamEncoding::Csv => {
let reader = arrow::csv::ReaderBuilder::new(schema)
@@ -311,7 +311,7 @@ impl TableProvider for StreamTable {
}
fn schema(&self) -> SchemaRef {
- self.0.source.schema().clone()
+ Arc::clone(self.0.source.schema())
}
fn constraints(&self) -> Option<&Constraints> {
@@ -338,8 +338,8 @@ impl TableProvider for StreamTable {
};
Ok(Arc::new(StreamingTableExec::try_new(
- self.0.source.schema().clone(),
- vec![Arc::new(StreamRead(self.0.clone())) as _],
+ Arc::clone(self.0.source.schema()),
+ vec![Arc::new(StreamRead(Arc::clone(&self.0))) as _],
projection,
projected_schema,
true,
@@ -365,8 +365,8 @@ impl TableProvider for StreamTable {
Ok(Arc::new(DataSinkExec::new(
input,
- Arc::new(StreamWrite(self.0.clone())),
- self.0.source.schema().clone(),
+ Arc::new(StreamWrite(Arc::clone(&self.0))),
+ Arc::clone(self.0.source.schema()),
ordering,
)))
}
@@ -381,8 +381,8 @@ impl PartitionStream for StreamRead {
}
fn execute(&self, _ctx: Arc<TaskContext>) -> SendableRecordBatchStream {
- let config = self.0.clone();
- let schema = self.0.source.schema().clone();
+ let config = Arc::clone(&self.0);
+ let schema = Arc::clone(self.0.source.schema());
let mut builder = RecordBatchReceiverStreamBuilder::new(schema, 2);
let tx = builder.tx();
builder.spawn_blocking(move || {
@@ -422,7 +422,7 @@ impl DataSink for StreamWrite {
mut data: SendableRecordBatchStream,
_context: &Arc<TaskContext>,
) -> Result<u64> {
- let config = self.0.clone();
+ let config = Arc::clone(&self.0);
let (sender, mut receiver) = tokio::sync::mpsc::channel::<RecordBatch>(2);
// Note: FIFO Files support poll so this could use AsyncFd
let write_task = SpawnedTask::spawn_blocking(move || {
diff --git a/datafusion/core/src/datasource/streaming.rs b/datafusion/core/src/datasource/streaming.rs
index 0a14cfefcd..1da3c3da9c 100644
--- a/datafusion/core/src/datasource/streaming.rs
+++ b/datafusion/core/src/datasource/streaming.rs
@@ -76,7 +76,7 @@ impl TableProvider for StreamingTable {
}
fn schema(&self) -> SchemaRef {
- self.schema.clone()
+ Arc::clone(&self.schema)
}
fn table_type(&self) -> TableType {
@@ -91,7 +91,7 @@ impl TableProvider for StreamingTable {
limit: Option<usize>,
) -> Result<Arc<dyn ExecutionPlan>> {
Ok(Arc::new(StreamingTableExec::try_new(
- self.schema.clone(),
+ Arc::clone(&self.schema),
self.partitions.clone(),
projection,
None,
diff --git a/datafusion/core/src/execution/context/mod.rs b/datafusion/core/src/execution/context/mod.rs
index e04fe6bdde..a2093c39fc 100644
--- a/datafusion/core/src/execution/context/mod.rs
+++ b/datafusion/core/src/execution/context/mod.rs
@@ -508,7 +508,7 @@ impl SessionContext {
/// Return the [RuntimeEnv] used to run queries with this `SessionContext`
pub fn runtime_env(&self) -> Arc<RuntimeEnv> {
- self.state.read().runtime_env().clone()
+ Arc::clone(self.state.read().runtime_env())
}
/// Returns an id that uniquely identifies this `SessionContext`.
@@ -1545,7 +1545,7 @@ impl SessionContext {
/// Get reference to [`SessionState`]
pub fn state_ref(&self) -> Arc<RwLock<SessionState>> {
- self.state.clone()
+ Arc::clone(&self.state)
}
/// Get weak reference to [`SessionState`]
diff --git a/datafusion/core/src/execution/session_state.rs b/datafusion/core/src/execution/session_state.rs
index d0bbc95a1b..6172783ab8 100644
--- a/datafusion/core/src/execution/session_state.rs
+++ b/datafusion/core/src/execution/session_state.rs
@@ -300,9 +300,9 @@ impl SessionState {
let resolved_ref = self.resolve_table_ref(table_ref);
if self.config.information_schema() && *resolved_ref.schema == *INFORMATION_SCHEMA
{
- return Ok(Arc::new(InformationSchemaProvider::new(
- self.catalog_list.clone(),
- )));
+ return Ok(Arc::new(InformationSchemaProvider::new(Arc::clone(
+ &self.catalog_list,
+ ))));
}
self.catalog_list
@@ -649,9 +649,9 @@ impl SessionState {
return Ok(LogicalPlan::Explain(Explain {
verbose: e.verbose,
- plan: e.plan.clone(),
+ plan: Arc::clone(&e.plan),
stringified_plans,
- schema: e.schema.clone(),
+ schema: Arc::clone(&e.schema),
logical_optimization_succeeded: false,
}));
}
@@ -678,7 +678,7 @@ impl SessionState {
let plan_type = PlanType::OptimizedLogicalPlan { optimizer_name };
stringified_plans
.push(StringifiedPlan::new(plan_type, err.to_string()));
- (e.plan.clone(), false)
+ (Arc::clone(&e.plan), false)
}
Err(e) => return Err(e),
};
@@ -687,7 +687,7 @@ impl SessionState {
verbose: e.verbose,
plan,
stringified_plans,
- schema: e.schema.clone(),
+ schema: Arc::clone(&e.schema),
logical_optimization_succeeded,
}))
} else {
@@ -909,7 +909,7 @@ impl SessionState {
name: &str,
) -> datafusion_common::Result<Option<Arc<dyn TableFunctionImpl>>> {
let udtf = self.table_functions.remove(name);
- Ok(udtf.map(|x| x.function().clone()))
+ Ok(udtf.map(|x| Arc::clone(x.function())))
}
/// Store the logical plan and the parameter types of a prepared statement.
@@ -1711,7 +1711,7 @@ impl<'a> ContextProvider for SessionContextProvider<'a> {
.ok_or(plan_datafusion_err!(
"There is no registered file format with ext {ext}"
))
- .map(|file_type| format_as_file_type(file_type.clone()))
+ .map(|file_type| format_as_file_type(Arc::clone(file_type)))
}
}
@@ -1749,7 +1749,8 @@ impl FunctionRegistry for SessionState {
udf: Arc<ScalarUDF>,
) -> datafusion_common::Result<Option<Arc<ScalarUDF>>> {
udf.aliases().iter().for_each(|alias| {
- self.scalar_functions.insert(alias.clone(), udf.clone());
+ self.scalar_functions
+ .insert(alias.clone(), Arc::clone(&udf));
});
Ok(self.scalar_functions.insert(udf.name().into(), udf))
}
@@ -1759,7 +1760,8 @@ impl FunctionRegistry for SessionState {
udaf: Arc<AggregateUDF>,
) -> datafusion_common::Result<Option<Arc<AggregateUDF>>> {
udaf.aliases().iter().for_each(|alias| {
- self.aggregate_functions.insert(alias.clone(), udaf.clone());
+ self.aggregate_functions
+ .insert(alias.clone(), Arc::clone(&udaf));
});
Ok(self.aggregate_functions.insert(udaf.name().into(), udaf))
}
@@ -1769,7 +1771,8 @@ impl FunctionRegistry for SessionState {
udwf: Arc<WindowUDF>,
) -> datafusion_common::Result<Option<Arc<WindowUDF>>> {
udwf.aliases().iter().for_each(|alias| {
- self.window_functions.insert(alias.clone(), udwf.clone());
+ self.window_functions
+ .insert(alias.clone(), Arc::clone(&udwf));
});
Ok(self.window_functions.insert(udwf.name().into(), udwf))
}
@@ -1863,7 +1866,7 @@ impl From<&SessionState> for TaskContext {
state.scalar_functions.clone(),
state.aggregate_functions.clone(),
state.window_functions.clone(),
- state.runtime_env.clone(),
+ Arc::clone(&state.runtime_env),
)
}
}
diff --git a/datafusion/core/src/execution/session_state_defaults.rs b/datafusion/core/src/execution/session_state_defaults.rs
index b5370efa0a..7ba332c520 100644
--- a/datafusion/core/src/execution/session_state_defaults.rs
+++ b/datafusion/core/src/execution/session_state_defaults.rs
@@ -193,8 +193,13 @@ impl SessionStateDefaults {
Some(factory) => factory,
_ => return,
};
- let schema =
- ListingSchemaProvider::new(authority, path, factory.clone(), store, format);
+ let schema = ListingSchemaProvider::new(
+ authority,
+ path,
+ Arc::clone(factory),
+ store,
+ format,
+ );
let _ = default_catalog
.register_schema("default", Arc::new(schema))
.expect("Failed to register default schema");
diff --git a/datafusion/core/src/lib.rs b/datafusion/core/src/lib.rs
index 9d1574f515..b2df32a62e 100644
--- a/datafusion/core/src/lib.rs
+++ b/datafusion/core/src/lib.rs
@@ -15,6 +15,8 @@
// specific language governing permissions and limitations
// under the License.
+// Make cheap clones clear: https://github.com/apache/datafusion/issues/11143
+#![cfg_attr(not(test), deny(clippy::clone_on_ref_ptr))]
#![warn(missing_docs, clippy::needless_borrow)]
//! [DataFusion] is an extensible query engine written in Rust that
diff --git a/datafusion/core/src/physical_optimizer/enforce_distribution.rs b/datafusion/core/src/physical_optimizer/enforce_distribution.rs
index 4bbb995c36..82fde60de0 100644
--- a/datafusion/core/src/physical_optimizer/enforce_distribution.rs
+++ b/datafusion/core/src/physical_optimizer/enforce_distribution.rs
@@ -274,7 +274,7 @@ impl PhysicalOptimizerRule for EnforceDistribution {
fn adjust_input_keys_ordering(
mut requirements: PlanWithKeyRequirements,
) -> Result<Transformed<PlanWithKeyRequirements>> {
- let plan = requirements.plan.clone();
+ let plan = Arc::clone(&requirements.plan);
if let Some(HashJoinExec {
left,
@@ -295,8 +295,8 @@ fn adjust_input_keys_ordering(
Vec<SortOptions>,
)| {
HashJoinExec::try_new(
- left.clone(),
- right.clone(),
+ Arc::clone(left),
+ Arc::clone(right),
new_conditions.0,
filter.clone(),
join_type,
@@ -362,8 +362,8 @@ fn adjust_input_keys_ordering(
Vec<SortOptions>,
)| {
SortMergeJoinExec::try_new(
- left.clone(),
- right.clone(),
+ Arc::clone(left),
+ Arc::clone(right),
new_conditions.0,
filter.clone(),
*join_type,
@@ -495,8 +495,8 @@ fn reorder_aggregate_keys(
PhysicalGroupBy::new_single(new_group_exprs),
agg_exec.aggr_expr().to_vec(),
agg_exec.filter_expr().to_vec(),
- agg_exec.input().clone(),
- agg_exec.input_schema.clone(),
+ Arc::clone(agg_exec.input()),
+ Arc::clone(&agg_exec.input_schema),
)?);
// Build new group expressions that correspond to the output
// of the "reordered" aggregator:
@@ -514,11 +514,11 @@ fn reorder_aggregate_keys(
new_group_by,
agg_exec.aggr_expr().to_vec(),
agg_exec.filter_expr().to_vec(),
- partial_agg.clone(),
+ Arc::clone(&partial_agg) as _,
agg_exec.input_schema(),
)?);
- agg_node.plan = new_final_agg.clone();
+ agg_node.plan = Arc::clone(&new_final_agg) as _;
agg_node.data.clear();
agg_node.children = vec![PlanWithKeyRequirements::new(
partial_agg as _,
@@ -624,8 +624,8 @@ pub(crate) fn reorder_join_keys_to_inputs(
} = join_keys;
let new_join_on = new_join_conditions(&left_keys, &right_keys);
return Ok(Arc::new(HashJoinExec::try_new(
- left.clone(),
- right.clone(),
+ Arc::clone(left),
+ Arc::clone(right),
new_join_on,
filter.clone(),
join_type,
@@ -664,8 +664,8 @@ pub(crate) fn reorder_join_keys_to_inputs(
.map(|idx| sort_options[positions[idx]])
.collect();
return SortMergeJoinExec::try_new(
- left.clone(),
- right.clone(),
+ Arc::clone(left),
+ Arc::clone(right),
new_join_on,
filter.clone(),
*join_type,
@@ -726,19 +726,19 @@ fn try_reorder(
} else if !equivalence_properties.eq_group().is_empty() {
normalized_expected = expected
.iter()
- .map(|e| eq_groups.normalize_expr(e.clone()))
+ .map(|e| eq_groups.normalize_expr(Arc::clone(e)))
.collect();
normalized_left_keys = join_keys
.left_keys
.iter()
- .map(|e| eq_groups.normalize_expr(e.clone()))
+ .map(|e| eq_groups.normalize_expr(Arc::clone(e)))
.collect();
normalized_right_keys = join_keys
.right_keys
.iter()
- .map(|e| eq_groups.normalize_expr(e.clone()))
+ .map(|e| eq_groups.normalize_expr(Arc::clone(e)))
.collect();
if physical_exprs_equal(&normalized_expected, &normalized_left_keys)
@@ -761,8 +761,8 @@ fn try_reorder(
let mut new_left_keys = vec![];
let mut new_right_keys = vec![];
for pos in positions.iter() {
- new_left_keys.push(join_keys.left_keys[*pos].clone());
- new_right_keys.push(join_keys.right_keys[*pos].clone());
+ new_left_keys.push(Arc::clone(&join_keys.left_keys[*pos]));
+ new_right_keys.push(Arc::clone(&join_keys.right_keys[*pos]));
}
let pairs = JoinKeyPairs {
left_keys: new_left_keys,
@@ -800,7 +800,7 @@ fn expected_expr_positions(
fn extract_join_keys(on: &[(PhysicalExprRef, PhysicalExprRef)]) -> JoinKeyPairs {
let (left_keys, right_keys) = on
.iter()
- .map(|(l, r)| (l.clone() as _, r.clone() as _))
+ .map(|(l, r)| (Arc::clone(l) as _, Arc::clone(r) as _))
.unzip();
JoinKeyPairs {
left_keys,
@@ -815,7 +815,7 @@ fn new_join_conditions(
new_left_keys
.iter()
.zip(new_right_keys.iter())
- .map(|(l_key, r_key)| (l_key.clone(), r_key.clone()))
+ .map(|(l_key, r_key)| (Arc::clone(l_key), Arc::clone(r_key)))
.collect()
}
@@ -844,8 +844,9 @@ fn add_roundrobin_on_top(
// - Usage of order preserving variants is not desirable
// (determined by flag `config.optimizer.prefer_existing_sort`)
let partitioning = Partitioning::RoundRobinBatch(n_target);
- let repartition = RepartitionExec::try_new(input.plan.clone(), partitioning)?
- .with_preserve_order();
+ let repartition =
+ RepartitionExec::try_new(Arc::clone(&input.plan), partitioning)?
+ .with_preserve_order();
let new_plan = Arc::new(repartition) as _;
@@ -902,8 +903,9 @@ fn add_hash_on_top(
// - Usage of order preserving variants is not desirable (per the flag
// `config.optimizer.prefer_existing_sort`).
let partitioning = dist.create_partitioning(n_target);
- let repartition = RepartitionExec::try_new(input.plan.clone(), partitioning)?
- .with_preserve_order();
+ let repartition =
+ RepartitionExec::try_new(Arc::clone(&input.plan), partitioning)?
+ .with_preserve_order();
let plan = Arc::new(repartition) as _;
return Ok(DistributionContext::new(plan, true, vec![input]));
@@ -941,10 +943,10 @@ fn add_spm_on_top(input: DistributionContext) -> DistributionContext {
.output_ordering()
.unwrap_or(&LexOrdering::default())
.clone(),
- input.plan.clone(),
+ Arc::clone(&input.plan),
)) as _
} else {
- Arc::new(CoalescePartitionsExec::new(input.plan.clone())) as _
+ Arc::new(CoalescePartitionsExec::new(Arc::clone(&input.plan))) as _
};
DistributionContext::new(new_plan, true, vec![input])
@@ -1020,7 +1022,7 @@ fn replace_order_preserving_variants(
.collect::<Result<Vec<_>>>()?;
if is_sort_preserving_merge(&context.plan) {
- let child_plan = context.children[0].plan.clone();
+ let child_plan = Arc::clone(&context.children[0].plan);
context.plan = Arc::new(CoalescePartitionsExec::new(child_plan));
return Ok(context);
} else if let Some(repartition) =
@@ -1028,7 +1030,7 @@ fn replace_order_preserving_variants(
{
if repartition.preserve_order() {
context.plan = Arc::new(RepartitionExec::try_new(
- context.children[0].plan.clone(),
+ Arc::clone(&context.children[0].plan),
repartition.partitioning().clone(),
)?);
return Ok(context);
@@ -1306,7 +1308,10 @@ fn ensure_distribution(
)
.collect::<Result<Vec<_>>>()?;
- let children_plans = children.iter().map(|c| c.plan.clone()).collect::<Vec<_>>();
+ let children_plans = children
+ .iter()
+ .map(|c| Arc::clone(&c.plan))
+ .collect::<Vec<_>>();
plan = if plan.as_any().is::<UnionExec>()
&& !config.optimizer.prefer_existing_union
diff --git a/datafusion/core/src/physical_optimizer/enforce_sorting.rs b/datafusion/core/src/physical_optimizer/enforce_sorting.rs
index 636d52ccc9..cfc08562f7 100644
--- a/datafusion/core/src/physical_optimizer/enforce_sorting.rs
+++ b/datafusion/core/src/physical_optimizer/enforce_sorting.rs
@@ -213,7 +213,7 @@ fn replace_with_partial_sort(
) -> Result<Arc<dyn ExecutionPlan>> {
let plan_any = plan.as_any();
if let Some(sort_plan) = plan_any.downcast_ref::<SortExec>() {
- let child = sort_plan.children()[0].clone();
+ let child = Arc::clone(sort_plan.children()[0]);
if !child.execution_mode().is_unbounded() {
return Ok(plan);
}
@@ -233,7 +233,7 @@ fn replace_with_partial_sort(
return Ok(Arc::new(
PartialSortExec::new(
LexOrdering::new(sort_plan.expr().to_vec()),
- sort_plan.input().clone(),
+ Arc::clone(sort_plan.input()),
common_prefix_length,
)
.with_preserve_partitioning(sort_plan.preserve_partitioning())
@@ -290,7 +290,8 @@ fn parallelize_sorts(
requirements = add_sort_above_with_check(requirements, sort_reqs, fetch);
- let spm = SortPreservingMergeExec::new(sort_exprs, requirements.plan.clone());
+ let spm =
+ SortPreservingMergeExec::new(sort_exprs, Arc::clone(&requirements.plan));
Ok(Transformed::yes(
PlanWithCorrespondingCoalescePartitions::new(
Arc::new(spm.with_fetch(fetch)),
@@ -307,7 +308,7 @@ fn parallelize_sorts(
Ok(Transformed::yes(
PlanWithCorrespondingCoalescePartitions::new(
- Arc::new(CoalescePartitionsExec::new(requirements.plan.clone())),
+ Arc::new(CoalescePartitionsExec::new(Arc::clone(&requirements.plan))),
false,
vec![requirements],
),
@@ -402,7 +403,7 @@ fn analyze_immediate_sort_removal(
{
// Replace the sort with a sort-preserving merge:
let expr = LexOrdering::new(sort_exec.expr().to_vec());
- Arc::new(SortPreservingMergeExec::new(expr, sort_input.clone())) as _
+ Arc::new(SortPreservingMergeExec::new(expr, Arc::clone(sort_input))) as _
} else {
// Remove the sort:
node.children = node.children.swap_remove(0).children;
@@ -414,12 +415,16 @@ fn analyze_immediate_sort_removal(
.partition_count()
== 1
{
- Arc::new(GlobalLimitExec::new(sort_input.clone(), 0, Some(fetch)))
+ Arc::new(GlobalLimitExec::new(
+ Arc::clone(sort_input),
+ 0,
+ Some(fetch),
+ ))
} else {
- Arc::new(LocalLimitExec::new(sort_input.clone(), fetch))
+ Arc::new(LocalLimitExec::new(Arc::clone(sort_input), fetch))
}
} else {
- sort_input.clone()
+ Arc::clone(sort_input)
}
};
for child in node.children.iter_mut() {
@@ -479,7 +484,7 @@ fn adjust_window_sort_removal(
// Satisfy the ordering requirement so that the window can run:
let mut child_node = window_tree.children.swap_remove(0);
child_node = add_sort_above(child_node, reqs, None);
- let child_plan = child_node.plan.clone();
+ let child_plan = Arc::clone(&child_node.plan);
window_tree.children.push(child_node);
if window_expr.iter().all(|e| e.uses_bounded_memory()) {
@@ -604,12 +609,12 @@ fn remove_corresponding_sort_from_sub_plan(
// Replace with variants that do not preserve order.
if is_sort_preserving_merge(&node.plan) {
node.children = node.children.swap_remove(0).children;
- node.plan = node.plan.children().swap_remove(0).clone();
+ node.plan = Arc::clone(node.plan.children().swap_remove(0));
} else if let Some(repartition) =
node.plan.as_any().downcast_ref::<RepartitionExec>()
{
node.plan = Arc::new(RepartitionExec::try_new(
- node.children[0].plan.clone(),
+ Arc::clone(&node.children[0].plan),
repartition.properties().output_partitioning().clone(),
)?) as _;
}
@@ -620,7 +625,7 @@ fn remove_corresponding_sort_from_sub_plan(
{
// If there is existing ordering, to preserve ordering use
// `SortPreservingMergeExec` instead of a `CoalescePartitionsExec`.
- let plan = node.plan.clone();
+ let plan = Arc::clone(&node.plan);
let plan = if let Some(ordering) = plan.output_ordering() {
Arc::new(SortPreservingMergeExec::new(
LexOrdering::new(ordering.to_vec()),
diff --git a/datafusion/core/src/physical_optimizer/join_selection.rs b/datafusion/core/src/physical_optimizer/join_selection.rs
index 0312e362af..9b2402c6bb 100644
--- a/datafusion/core/src/physical_optimizer/join_selection.rs
+++ b/datafusion/core/src/physical_optimizer/join_selection.rs
@@ -187,7 +187,7 @@ pub fn swap_hash_join(
hash_join
.on()
.iter()
- .map(|(l, r)| (r.clone(), l.clone()))
+ .map(|(l, r)| (Arc::clone(r), Arc::clone(l)))
.collect(),
swap_join_filter(hash_join.filter()),
&swap_join_type(*hash_join.join_type()),
@@ -289,7 +289,7 @@ fn swap_filter(filter: &JoinFilter) -> JoinFilter {
.collect();
JoinFilter::new(
- filter.expression().clone(),
+ Arc::clone(filter.expression()),
column_indices,
filter.schema().clone(),
)
@@ -605,8 +605,8 @@ fn hash_join_convert_symmetric_subrule(
let right_order = determine_order(JoinSide::Right);
return SymmetricHashJoinExec::try_new(
- hash_join.left().clone(),
- hash_join.right().clone(),
+ Arc::clone(hash_join.left()),
+ Arc::clone(hash_join.right()),
hash_join.on().to_vec(),
hash_join.filter().cloned(),
hash_join.join_type(),
diff --git a/datafusion/core/src/physical_optimizer/projection_pushdown.rs b/datafusion/core/src/physical_optimizer/projection_pushdown.rs
index 5aecf036ce..2c2ff6d48a 100644
--- a/datafusion/core/src/physical_optimizer/projection_pushdown.rs
+++ b/datafusion/core/src/physical_optimizer/projection_pushdown.rs
@@ -101,7 +101,7 @@ pub fn remove_unnecessary_projections(
// If the projection does not cause any change on the input, we can
// safely remove it:
if is_projection_removable(projection) {
- return Ok(Transformed::yes(projection.input().clone()));
+ return Ok(Transformed::yes(Arc::clone(projection.input())));
}
// If it does, check if we can push it under its child(ren):
let input = projection.input().as_any();
@@ -261,7 +261,7 @@ fn try_swapping_with_streaming_table(
}
StreamingTableExec::try_new(
- streaming_table.partition_schema().clone(),
+ Arc::clone(streaming_table.partition_schema()),
streaming_table.partitions().clone(),
Some(new_projections.as_ref()),
lex_orderings,
@@ -297,7 +297,7 @@ fn try_unifying_projections(
// beneficial as caching mechanism for non-trivial computations.
// See discussion in: https://github.com/apache/datafusion/issues/8296
if column_ref_map.iter().any(|(column, count)| {
- *count > 1 && !is_expr_trivial(&child.expr()[column.index()].0.clone())
+ *count > 1 && !is_expr_trivial(&Arc::clone(&child.expr()[column.index()].0))
}) {
return Ok(None);
}
@@ -312,7 +312,7 @@ fn try_unifying_projections(
projected_exprs.push((expr, alias.clone()));
}
- ProjectionExec::try_new(projected_exprs, child.input().clone())
+ ProjectionExec::try_new(projected_exprs, Arc::clone(child.input()))
.map(|e| Some(Arc::new(e) as _))
}
@@ -603,7 +603,7 @@ fn try_embed_projection<Exec: EmbeddedProjection + 'static>(
// Old projection may contain some alias or expression such as `a + 1` and `CAST('true' AS BOOLEAN)`, but our projection_exprs in hash join just contain column, so we need to create the new projection to keep the original projection.
let new_projection = Arc::new(ProjectionExec::try_new(
new_projection_exprs,
- new_execution_plan.clone(),
+ Arc::clone(&new_execution_plan) as _,
)?);
if is_projection_removable(&new_projection) {
Ok(Some(new_execution_plan))
@@ -1005,8 +1005,7 @@ fn update_expr(
let mut state = RewriteState::Unchanged;
- let new_expr = expr
- .clone()
+ let new_expr = Arc::clone(expr)
.transform_up(|expr: Arc<dyn PhysicalExpr>| {
if state == RewriteState::RewrittenInvalid {
return Ok(Transformed::no(expr));
@@ -1018,7 +1017,9 @@ fn update_expr(
if sync_with_child {
state = RewriteState::RewrittenValid;
// Update the index of `column`:
- Ok(Transformed::yes(projected_exprs[column.index()].0.clone()))
+ Ok(Transformed::yes(Arc::clone(
+ &projected_exprs[column.index()].0,
+ )))
} else {
// default to invalid, in case we can't find the relevant column
state = RewriteState::RewrittenInvalid;
@@ -1055,7 +1056,7 @@ fn make_with_child(
projection: &ProjectionExec,
child: &Arc<dyn ExecutionPlan>,
) -> Result<Arc<dyn ExecutionPlan>> {
- ProjectionExec::try_new(projection.expr().to_vec(), child.clone())
+ ProjectionExec::try_new(projection.expr().to_vec(), Arc::clone(child))
.map(|e| Arc::new(e) as _)
}
@@ -1155,8 +1156,7 @@ fn new_columns_for_join_on(
.iter()
.filter_map(|on| {
// Rewrite all columns in `on`
- (*on)
- .clone()
+ Arc::clone(*on)
.transform(|expr| {
if let Some(column) = expr.as_any().downcast_ref::<Column>() {
// Find the column in the projection expressions
@@ -1219,7 +1219,7 @@ fn update_join_filter(
== join_filter.column_indices().len())
.then(|| {
JoinFilter::new(
- join_filter.expression().clone(),
+ Arc::clone(join_filter.expression()),
join_filter
.column_indices()
.iter()
@@ -1302,7 +1302,7 @@ fn new_join_children(
)
})
.collect_vec(),
- left_child.clone(),
+ Arc::clone(left_child),
)?;
let left_size = left_child.schema().fields().len() as i32;
let new_right = ProjectionExec::try_new(
@@ -1320,7 +1320,7 @@ fn new_join_children(
)
})
.collect_vec(),
- right_child.clone(),
+ Arc::clone(right_child),
)?;
Ok((new_left, new_right))
diff --git a/datafusion/core/src/physical_optimizer/pruning.rs b/datafusion/core/src/physical_optimizer/pruning.rs
index eb03b33777..89b8647156 100644
--- a/datafusion/core/src/physical_optimizer/pruning.rs
+++ b/datafusion/core/src/physical_optimizer/pruning.rs
@@ -504,7 +504,7 @@ impl Default for ConstantUnhandledPredicateHook {
impl UnhandledPredicateHook for ConstantUnhandledPredicateHook {
fn handle(&self, _expr: &Arc<dyn PhysicalExpr>) -> Arc<dyn PhysicalExpr> {
- self.default.clone()
+ Arc::clone(&self.default)
}
}
@@ -857,7 +857,7 @@ impl RequiredColumns {
Field::new(stat_column.name(), field.data_type().clone(), nullable);
self.columns.push((column.clone(), stat_type, stat_field));
}
- rewrite_column_expr(column_expr.clone(), column, &stat_column)
+ rewrite_column_expr(Arc::clone(column_expr), column, &stat_column)
}
/// rewrite col --> col_min
@@ -1130,7 +1130,7 @@ fn rewrite_expr_to_prunable(
.is_some()
{
// `col op lit()`
- Ok((column_expr.clone(), op, scalar_expr.clone()))
+ Ok((Arc::clone(column_expr), op, Arc::clone(scalar_expr)))
} else if let Some(cast) = column_expr_any.downcast_ref::<phys_expr::CastExpr>() {
// `cast(col) op lit()`
let arrow_schema: SchemaRef = schema.clone().into();
@@ -1175,8 +1175,8 @@ fn rewrite_expr_to_prunable(
.downcast_ref::<phys_expr::Column>()
.is_some()
{
- let left = not.arg().clone();
- let right = Arc::new(phys_expr::NotExpr::new(scalar_expr.clone()));
+ let left = Arc::clone(not.arg());
+ let right = Arc::new(phys_expr::NotExpr::new(Arc::clone(scalar_expr)));
Ok((left, reverse_operator(op)?, right))
} else {
plan_err!("Not with complex expression {column_expr:?} is not supported")
@@ -1462,9 +1462,9 @@ fn build_predicate_expression(
.iter()
.map(|e| {
Arc::new(phys_expr::BinaryExpr::new(
- in_list.expr().clone(),
+ Arc::clone(in_list.expr()),
eq_op,
- e.clone(),
+ Arc::clone(e),
)) as _
})
.reduce(|a, b| Arc::new(phys_expr::BinaryExpr::new(a, re_op, b)) as _)
@@ -1483,9 +1483,9 @@ fn build_predicate_expression(
let (left, op, right) = {
if let Some(bin_expr) = expr_any.downcast_ref::<phys_expr::BinaryExpr>() {
(
- bin_expr.left().clone(),
+ Arc::clone(bin_expr.left()),
*bin_expr.op(),
- bin_expr.right().clone(),
+ Arc::clone(bin_expr.right()),
)
} else {
return unhandled_hook.handle(expr);
@@ -1538,11 +1538,11 @@ fn build_statistics_expr(
Arc::new(phys_expr::BinaryExpr::new(
min_column_expr,
Operator::NotEq,
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
)),
Operator::Or,
Arc::new(phys_expr::BinaryExpr::new(
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
Operator::NotEq,
max_column_expr,
)),
@@ -1557,11 +1557,11 @@ fn build_statistics_expr(
Arc::new(phys_expr::BinaryExpr::new(
min_column_expr,
Operator::LtEq,
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
)),
Operator::And,
Arc::new(phys_expr::BinaryExpr::new(
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
Operator::LtEq,
max_column_expr,
)),
@@ -1572,7 +1572,7 @@ fn build_statistics_expr(
Arc::new(phys_expr::BinaryExpr::new(
expr_builder.max_column_expr()?,
Operator::Gt,
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
))
}
Operator::GtEq => {
@@ -1580,7 +1580,7 @@ fn build_statistics_expr(
Arc::new(phys_expr::BinaryExpr::new(
expr_builder.max_column_expr()?,
Operator::GtEq,
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
))
}
Operator::Lt => {
@@ -1588,7 +1588,7 @@ fn build_statistics_expr(
Arc::new(phys_expr::BinaryExpr::new(
expr_builder.min_column_expr()?,
Operator::Lt,
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
))
}
Operator::LtEq => {
@@ -1596,7 +1596,7 @@ fn build_statistics_expr(
Arc::new(phys_expr::BinaryExpr::new(
expr_builder.min_column_expr()?,
Operator::LtEq,
- expr_builder.scalar_expr().clone(),
+ Arc::clone(expr_builder.scalar_expr()),
))
}
// other expressions are not supported
diff --git a/datafusion/core/src/physical_optimizer/replace_with_order_preserving_variants.rs b/datafusion/core/src/physical_optimizer/replace_with_order_preserving_variants.rs
index c80aea411f..7fc3adf784 100644
--- a/datafusion/core/src/physical_optimizer/replace_with_order_preserving_variants.rs
+++ b/datafusion/core/src/physical_optimizer/replace_with_order_preserving_variants.rs
@@ -120,7 +120,7 @@ fn plan_with_order_preserving_variants(
{
// When a `RepartitionExec` doesn't preserve ordering, replace it with
// a sort-preserving variant if appropriate:
- let child = sort_input.children[0].plan.clone();
+ let child = Arc::clone(&sort_input.children[0].plan);
let partitioning = sort_input.plan.output_partitioning().clone();
sort_input.plan = Arc::new(
RepartitionExec::try_new(child, partitioning)?.with_preserve_order(),
@@ -134,7 +134,7 @@ fn plan_with_order_preserving_variants(
// replace it with a `SortPreservingMergeExec` if appropriate:
let spm = SortPreservingMergeExec::new(
LexOrdering::new(ordering.inner.clone()),
- child.clone(),
+ Arc::clone(child),
);
sort_input.plan = Arc::new(spm) as _;
sort_input.children[0].data = true;
@@ -179,12 +179,12 @@ fn plan_with_order_breaking_variants(
if is_repartition(plan) && plan.maintains_input_order()[0] {
// When a `RepartitionExec` preserves ordering, replace it with a
// non-sort-preserving variant:
- let child = sort_input.children[0].plan.clone();
+ let child = Arc::clone(&sort_input.children[0].plan);
let partitioning = plan.output_partitioning().clone();
sort_input.plan = Arc::new(RepartitionExec::try_new(child, partitioning)?) as _;
} else if is_sort_preserving_merge(plan) {
// Replace `SortPreservingMergeExec` with a `CoalescePartitionsExec`:
- let child = sort_input.children[0].plan.clone();
+ let child = Arc::clone(&sort_input.children[0].plan);
let coalesce = CoalescePartitionsExec::new(child);
sort_input.plan = Arc::new(coalesce) as _;
} else {
diff --git a/datafusion/core/src/physical_optimizer/sanity_checker.rs b/datafusion/core/src/physical_optimizer/sanity_checker.rs
index 01d3cd1aab..b2f2c933c1 100644
--- a/datafusion/core/src/physical_optimizer/sanity_checker.rs
+++ b/datafusion/core/src/physical_optimizer/sanity_checker.rs
@@ -119,7 +119,7 @@ pub fn check_plan_sanity(
plan: Arc<dyn ExecutionPlan>,
optimizer_options: &OptimizerOptions,
) -> Result<Transformed<Arc<dyn ExecutionPlan>>> {
- check_finiteness_requirements(plan.clone(), optimizer_options)?;
+ check_finiteness_requirements(Arc::clone(&plan), optimizer_options)?;
for ((idx, child), sort_req, dist_req) in izip!(
plan.children().iter().enumerate(),
diff --git a/datafusion/core/src/physical_optimizer/sort_pushdown.rs b/datafusion/core/src/physical_optimizer/sort_pushdown.rs
index 42d682169d..d48c7118cb 100644
--- a/datafusion/core/src/physical_optimizer/sort_pushdown.rs
+++ b/datafusion/core/src/physical_optimizer/sort_pushdown.rs
@@ -571,9 +571,7 @@ fn handle_custom_pushdown(
.iter()
.map(|req| {
let child_schema = plan.children()[maintained_child_idx].schema();
- let updated_columns = req
- .expr
- .clone()
+ let updated_columns = Arc::clone(&req.expr)
.transform_up(|expr| {
if let Some(col) = expr.as_any().downcast_ref::<Column>() {
let new_index = col.index() - sub_offset;
diff --git a/datafusion/core/src/physical_optimizer/utils.rs b/datafusion/core/src/physical_optimizer/utils.rs
index 9acd3f67c2..cdecc9d318 100644
--- a/datafusion/core/src/physical_optimizer/utils.rs
+++ b/datafusion/core/src/physical_optimizer/utils.rs
@@ -46,7 +46,7 @@ pub fn add_sort_above<T: Clone + Default>(
.equivalence_properties()
.is_expr_constant(&sort_expr.expr)
});
- let mut new_sort = SortExec::new(sort_expr, node.plan.clone()).with_fetch(fetch);
+ let mut new_sort = SortExec::new(sort_expr, Arc::clone(&node.plan)).with_fetch(fetch);
if node.plan.output_partitioning().partition_count() > 1 {
new_sort = new_sort.with_preserve_partitioning(true);
}
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index 2d3899adb0..26f6b12908 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -327,7 +327,7 @@ impl DefaultPhysicalPlanner {
// Spawning tasks which will traverse leaf up to the root.
let tasks = flat_tree_leaf_indices
.into_iter()
- .map(|index| self.task_helper(index, flat_tree.clone(), session_state));
+ .map(|index| self.task_helper(index, Arc::clone(&flat_tree), session_state));
let mut outputs = futures::stream::iter(tasks)
.buffer_unordered(max_concurrency)
.try_collect::<Vec<_>>()
@@ -486,7 +486,7 @@ impl DefaultPhysicalPlanner {
output_schema,
}) => {
let output_schema: Schema = output_schema.as_ref().into();
- self.plan_describe(schema.clone(), Arc::new(output_schema))?
+ self.plan_describe(Arc::clone(schema), Arc::new(output_schema))?
}
// 1 Child
@@ -690,7 +690,7 @@ impl DefaultPhysicalPlanner {
aggregates,
filters.clone(),
input_exec,
- physical_input_schema.clone(),
+ Arc::clone(&physical_input_schema),
)?);
let can_repartition = !groups.is_empty()
@@ -721,7 +721,7 @@ impl DefaultPhysicalPlanner {
updated_aggregates,
filters,
initial_aggr,
- physical_input_schema.clone(),
+ Arc::clone(&physical_input_schema),
)?)
}
LogicalPlan::Projection(Projection { input, expr, .. }) => self
@@ -893,8 +893,8 @@ impl DefaultPhysicalPlanner {
let right = Arc::new(right);
let new_join = LogicalPlan::Join(Join::try_new_with_project_input(
node,
- left.clone(),
- right.clone(),
+ Arc::clone(&left),
+ Arc::clone(&right),
column_on,
)?);
diff --git a/datafusion/core/src/test_util/mod.rs b/datafusion/core/src/test_util/mod.rs
index e03c18fec7..c4c84d667a 100644
--- a/datafusion/core/src/test_util/mod.rs
+++ b/datafusion/core/src/test_util/mod.rs
@@ -209,7 +209,7 @@ impl TableProvider for TestTableProvider {
}
fn schema(&self) -> SchemaRef {
- self.schema.clone()
+ Arc::clone(&self.schema)
}
fn table_type(&self) -> TableType {
@@ -425,7 +425,7 @@ impl TestAggregate {
/// Create a new COUNT(column) aggregate
pub fn new_count_column(schema: &Arc<Schema>) -> Self {
- Self::ColumnA(schema.clone())
+ Self::ColumnA(Arc::clone(schema))
}
/// Return appropriate expr depending if COUNT is for col or table (*)
diff --git a/datafusion/core/src/test_util/parquet.rs b/datafusion/core/src/test_util/parquet.rs
index 4e4a374720..fc6b4ad9d0 100644
--- a/datafusion/core/src/test_util/parquet.rs
+++ b/datafusion/core/src/test_util/parquet.rs
@@ -87,7 +87,8 @@ impl TestParquetFile {
let first_batch = batches.next().expect("need at least one record batch");
let schema = first_batch.schema();
- let mut writer = ArrowWriter::try_new(file, schema.clone(), Some(props)).unwrap();
+ let mut writer =
+ ArrowWriter::try_new(file, Arc::clone(&schema), Some(props)).unwrap();
writer.write(&first_batch).unwrap();
let mut num_rows = first_batch.num_rows();
@@ -144,7 +145,7 @@ impl TestParquetFile {
maybe_filter: Option<Expr>,
) -> Result<Arc<dyn ExecutionPlan>> {
let scan_config =
- FileScanConfig::new(self.object_store_url.clone(), self.schema.clone())
+ FileScanConfig::new(self.object_store_url.clone(), Arc::clone(&self.schema))
.with_file(PartitionedFile {
object_meta: self.object_meta.clone(),
partition_values: vec![],
@@ -154,11 +155,11 @@ impl TestParquetFile {
metadata_size_hint: None,
});
- let df_schema = self.schema.clone().to_dfschema_ref()?;
+ let df_schema = Arc::clone(&self.schema).to_dfschema_ref()?;
// run coercion on the filters to coerce types etc.
let props = ExecutionProps::new();
- let context = SimplifyContext::new(&props).with_schema(df_schema.clone());
+ let context = SimplifyContext::new(&props).with_schema(Arc::clone(&df_schema));
let parquet_options = ctx.copied_table_options().parquet;
if let Some(filter) = maybe_filter {
let simplifier = ExprSimplifier::new(context);
@@ -168,7 +169,7 @@ impl TestParquetFile {
let parquet_exec =
ParquetExecBuilder::new_with_options(scan_config, parquet_options)
- .with_predicate(physical_filter_expr.clone())
+ .with_predicate(Arc::clone(&physical_filter_expr))
.build_arc();
let exec = Arc::new(FilterExec::try_new(physical_filter_expr, parquet_exec)?);
@@ -200,7 +201,7 @@ impl TestParquetFile {
/// The schema of this parquet file
pub fn schema(&self) -> SchemaRef {
- self.schema.clone()
+ Arc::clone(&self.schema)
}
/// The path to the parquet file