You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@datafusion.apache.org by be...@apache.org on 2025/01/15 08:10:20 UTC
(datafusion) branch main updated: Chore: refactor DataSink traits to avoid duplication (#14121)
This is an automated email from the ASF dual-hosted git repository.
berkay pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datafusion.git
The following commit(s) were added to refs/heads/main by this push:
new c7c200a654 Chore: refactor DataSink traits to avoid duplication (#14121)
c7c200a654 is described below
commit c7c200a65404b6ce3c2549c8b8caf6d8701d54a8
Author: mertak-synnada <me...@gmail.com>
AuthorDate: Wed Jan 15 08:10:14 2025 +0000
Chore: refactor DataSink traits to avoid duplication (#14121)
* add some abstractions to file sinkers and centralize FileSinkConfig based behaviors
* satisfy clippy
* typo fix
* move start_demuxer_task back into demux.rs
add file_extension to FileSinkConfig
* fix errors
* merge get_writer_schema functions
add schema() function to DataSink trait
make FileSink a subtrait for DataSink
* Unify write_all for all FileSink implementers
* DRY builder/header fetch
* Remove more duplication
* enrich documentation for spawn_writer_tasks_and_join
* fix cargo doc
---------
Co-authored-by: Mehmet Ozan Kabak <oz...@gmail.com>
---
.../core/src/datasource/file_format/arrow.rs | 136 ++++++---------
datafusion/core/src/datasource/file_format/csv.rs | 73 ++++----
datafusion/core/src/datasource/file_format/json.rs | 56 +++---
.../core/src/datasource/file_format/parquet.rs | 189 ++++++++-------------
.../core/src/datasource/file_format/write/demux.rs | 65 ++++---
.../core/src/datasource/file_format/write/mod.rs | 25 ++-
.../datasource/file_format/write/orchestration.rs | 62 +++----
datafusion/core/src/datasource/listing/table.rs | 15 +-
datafusion/core/src/datasource/memory.rs | 19 +--
.../core/src/datasource/physical_plan/mod.rs | 64 ++++++-
datafusion/core/src/datasource/stream.rs | 6 +-
datafusion/core/src/physical_planner.rs | 7 +-
datafusion/physical-plan/src/insert.rs | 14 +-
datafusion/proto/proto/datafusion.proto | 1 +
datafusion/proto/src/generated/pbjson.rs | 18 ++
datafusion/proto/src/generated/prost.rs | 2 +
datafusion/proto/src/physical_plan/from_proto.rs | 1 +
datafusion/proto/src/physical_plan/mod.rs | 3 -
datafusion/proto/src/physical_plan/to_proto.rs | 2 +
.../proto/tests/cases/roundtrip_physical_plan.rs | 12 +-
20 files changed, 380 insertions(+), 390 deletions(-)
diff --git a/datafusion/core/src/datasource/file_format/arrow.rs b/datafusion/core/src/datasource/file_format/arrow.rs
index 2697e5621a..1d9827ae0a 100644
--- a/datafusion/core/src/datasource/file_format/arrow.rs
+++ b/datafusion/core/src/datasource/file_format/arrow.rs
@@ -26,12 +26,13 @@ use std::fmt::{self, Debug};
use std::sync::Arc;
use super::file_compression_type::FileCompressionType;
-use super::write::demux::start_demuxer_task;
+use super::write::demux::DemuxedStreamReceiver;
use super::write::{create_writer, SharedBuffer};
use super::FileFormatFactory;
+use crate::datasource::file_format::write::get_writer_schema;
use crate::datasource::file_format::FileFormat;
use crate::datasource::physical_plan::{
- ArrowExec, FileGroupDisplay, FileScanConfig, FileSinkConfig,
+ ArrowExec, FileGroupDisplay, FileScanConfig, FileSink, FileSinkConfig,
};
use crate::error::Result;
use crate::execution::context::SessionState;
@@ -46,11 +47,11 @@ use datafusion_common::parsers::CompressionTypeVariant;
use datafusion_common::{
not_impl_err, DataFusionError, GetExt, Statistics, DEFAULT_ARROW_EXTENSION,
};
+use datafusion_common_runtime::SpawnedTask;
use datafusion_execution::{SendableRecordBatchStream, TaskContext};
use datafusion_expr::dml::InsertOp;
use datafusion_physical_expr::PhysicalExpr;
use datafusion_physical_plan::insert::{DataSink, DataSinkExec};
-use datafusion_physical_plan::metrics::MetricsSet;
use async_trait::async_trait;
use bytes::Bytes;
@@ -186,19 +187,13 @@ impl FileFormat for ArrowFormat {
return not_impl_err!("Overwrites are not implemented yet for Arrow format");
}
- let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(ArrowFileSink::new(conf));
- Ok(Arc::new(DataSinkExec::new(
- input,
- sink,
- sink_schema,
- order_requirements,
- )) as _)
+ Ok(Arc::new(DataSinkExec::new(input, sink, order_requirements)) as _)
}
}
-/// Implements [`DataSink`] for writing to arrow_ipc files
+/// Implements [`FileSink`] for writing to arrow_ipc files
struct ArrowFileSink {
config: FileSinkConfig,
}
@@ -207,85 +202,21 @@ impl ArrowFileSink {
fn new(config: FileSinkConfig) -> Self {
Self { config }
}
-
- /// Converts table schema to writer schema, which may differ in the case
- /// of hive style partitioning where some columns are removed from the
- /// underlying files.
- fn get_writer_schema(&self) -> Arc<Schema> {
- if !self.config.table_partition_cols.is_empty() {
- let schema = self.config.output_schema();
- let partition_names: Vec<_> = self
- .config
- .table_partition_cols
- .iter()
- .map(|(s, _)| s)
- .collect();
- Arc::new(Schema::new(
- schema
- .fields()
- .iter()
- .filter(|f| !partition_names.contains(&f.name()))
- .map(|f| (**f).clone())
- .collect::<Vec<_>>(),
- ))
- } else {
- Arc::clone(self.config.output_schema())
- }
- }
-}
-
-impl Debug for ArrowFileSink {
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.debug_struct("ArrowFileSink").finish()
- }
-}
-
-impl DisplayAs for ArrowFileSink {
- fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- match t {
- DisplayFormatType::Default | DisplayFormatType::Verbose => {
- write!(f, "ArrowFileSink(file_groups=",)?;
- FileGroupDisplay(&self.config.file_groups).fmt_as(t, f)?;
- write!(f, ")")
- }
- }
- }
}
#[async_trait]
-impl DataSink for ArrowFileSink {
- fn as_any(&self) -> &dyn Any {
- self
+impl FileSink for ArrowFileSink {
+ fn config(&self) -> &FileSinkConfig {
+ &self.config
}
- fn metrics(&self) -> Option<MetricsSet> {
- None
- }
-
- async fn write_all(
+ async fn spawn_writer_tasks_and_join(
&self,
- data: SendableRecordBatchStream,
- context: &Arc<TaskContext>,
+ _context: &Arc<TaskContext>,
+ demux_task: SpawnedTask<Result<()>>,
+ mut file_stream_rx: DemuxedStreamReceiver,
+ object_store: Arc<dyn ObjectStore>,
) -> Result<u64> {
- let object_store = context
- .runtime_env()
- .object_store(&self.config.object_store_url)?;
-
- let part_col = if !self.config.table_partition_cols.is_empty() {
- Some(self.config.table_partition_cols.clone())
- } else {
- None
- };
-
- let (demux_task, mut file_stream_rx) = start_demuxer_task(
- data,
- context,
- part_col,
- self.config.table_paths[0].clone(),
- "arrow".into(),
- self.config.keep_partition_by_columns,
- );
-
let mut file_write_tasks: JoinSet<std::result::Result<usize, DataFusionError>> =
JoinSet::new();
@@ -296,7 +227,7 @@ impl DataSink for ArrowFileSink {
let shared_buffer = SharedBuffer::new(INITIAL_BUFFER_BYTES);
let mut arrow_writer = arrow_ipc::writer::FileWriter::try_new_with_options(
shared_buffer.clone(),
- &self.get_writer_schema(),
+ &get_writer_schema(&self.config),
ipc_options.clone(),
)?;
let mut object_store_writer = create_writer(
@@ -351,6 +282,43 @@ impl DataSink for ArrowFileSink {
}
}
+impl Debug for ArrowFileSink {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ArrowFileSink").finish()
+ }
+}
+
+impl DisplayAs for ArrowFileSink {
+ fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match t {
+ DisplayFormatType::Default | DisplayFormatType::Verbose => {
+ write!(f, "ArrowFileSink(file_groups=",)?;
+ FileGroupDisplay(&self.config.file_groups).fmt_as(t, f)?;
+ write!(f, ")")
+ }
+ }
+ }
+}
+
+#[async_trait]
+impl DataSink for ArrowFileSink {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn schema(&self) -> &SchemaRef {
+ self.config.output_schema()
+ }
+
+ async fn write_all(
+ &self,
+ data: SendableRecordBatchStream,
+ context: &Arc<TaskContext>,
+ ) -> Result<u64> {
+ FileSink::write_all(self, data, context).await
+ }
+}
+
const ARROW_MAGIC: [u8; 6] = [b'A', b'R', b'R', b'O', b'W', b'1'];
const CONTINUATION_MARKER: [u8; 4] = [0xff; 4];
diff --git a/datafusion/core/src/datasource/file_format/csv.rs b/datafusion/core/src/datasource/file_format/csv.rs
index e8fb3690ef..edf757e539 100644
--- a/datafusion/core/src/datasource/file_format/csv.rs
+++ b/datafusion/core/src/datasource/file_format/csv.rs
@@ -22,15 +22,16 @@ use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::sync::Arc;
-use super::write::orchestration::stateless_multipart_put;
+use super::write::orchestration::spawn_writer_tasks_and_join;
use super::{
Decoder, DecoderDeserializer, FileFormat, FileFormatFactory,
DEFAULT_SCHEMA_INFER_MAX_RECORD,
};
use crate::datasource::file_format::file_compression_type::FileCompressionType;
+use crate::datasource::file_format::write::demux::DemuxedStreamReceiver;
use crate::datasource::file_format::write::BatchSerializer;
use crate::datasource::physical_plan::{
- CsvExec, FileGroupDisplay, FileScanConfig, FileSinkConfig,
+ CsvExec, FileGroupDisplay, FileScanConfig, FileSink, FileSinkConfig,
};
use crate::error::Result;
use crate::execution::context::SessionState;
@@ -48,10 +49,10 @@ use datafusion_common::file_options::csv_writer::CsvWriterOptions;
use datafusion_common::{
exec_err, not_impl_err, DataFusionError, GetExt, DEFAULT_CSV_EXTENSION,
};
+use datafusion_common_runtime::SpawnedTask;
use datafusion_execution::TaskContext;
use datafusion_expr::dml::InsertOp;
use datafusion_physical_expr::PhysicalExpr;
-use datafusion_physical_plan::metrics::MetricsSet;
use async_trait::async_trait;
use bytes::{Buf, Bytes};
@@ -467,15 +468,9 @@ impl FileFormat for CsvFormat {
let writer_options = CsvWriterOptions::try_from(&options)?;
- let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(CsvSink::new(conf, writer_options));
- Ok(Arc::new(DataSinkExec::new(
- input,
- sink,
- sink_schema,
- order_requirements,
- )) as _)
+ Ok(Arc::new(DataSinkExec::new(input, sink, order_requirements)) as _)
}
}
@@ -685,43 +680,42 @@ impl CsvSink {
}
}
- /// Retrieve the inner [`FileSinkConfig`].
- pub fn config(&self) -> &FileSinkConfig {
+ /// Retrieve the writer options
+ pub fn writer_options(&self) -> &CsvWriterOptions {
+ &self.writer_options
+ }
+}
+
+#[async_trait]
+impl FileSink for CsvSink {
+ fn config(&self) -> &FileSinkConfig {
&self.config
}
- async fn multipartput_all(
+ async fn spawn_writer_tasks_and_join(
&self,
- data: SendableRecordBatchStream,
context: &Arc<TaskContext>,
+ demux_task: SpawnedTask<Result<()>>,
+ file_stream_rx: DemuxedStreamReceiver,
+ object_store: Arc<dyn ObjectStore>,
) -> Result<u64> {
- let builder = &self.writer_options.writer_options;
-
- let builder_clone = builder.clone();
- let options_clone = self.writer_options.clone();
- let get_serializer = move || {
- Arc::new(
- CsvSerializer::new()
- .with_builder(builder_clone.clone())
- .with_header(options_clone.writer_options.header()),
- ) as _
- };
-
- stateless_multipart_put(
- data,
+ let builder = self.writer_options.writer_options.clone();
+ let header = builder.header();
+ let serializer = Arc::new(
+ CsvSerializer::new()
+ .with_builder(builder)
+ .with_header(header),
+ ) as _;
+ spawn_writer_tasks_and_join(
context,
- "csv".into(),
- Box::new(get_serializer),
- &self.config,
+ serializer,
self.writer_options.compression.into(),
+ object_store,
+ demux_task,
+ file_stream_rx,
)
.await
}
-
- /// Retrieve the writer options
- pub fn writer_options(&self) -> &CsvWriterOptions {
- &self.writer_options
- }
}
#[async_trait]
@@ -730,8 +724,8 @@ impl DataSink for CsvSink {
self
}
- fn metrics(&self) -> Option<MetricsSet> {
- None
+ fn schema(&self) -> &SchemaRef {
+ self.config.output_schema()
}
async fn write_all(
@@ -739,8 +733,7 @@ impl DataSink for CsvSink {
data: SendableRecordBatchStream,
context: &Arc<TaskContext>,
) -> Result<u64> {
- let total_count = self.multipartput_all(data, context).await?;
- Ok(total_count)
+ FileSink::write_all(self, data, context).await
}
}
diff --git a/datafusion/core/src/datasource/file_format/json.rs b/datafusion/core/src/datasource/file_format/json.rs
index 4bdf336881..5bffb7e582 100644
--- a/datafusion/core/src/datasource/file_format/json.rs
+++ b/datafusion/core/src/datasource/file_format/json.rs
@@ -24,14 +24,15 @@ use std::fmt::Debug;
use std::io::BufReader;
use std::sync::Arc;
-use super::write::orchestration::stateless_multipart_put;
+use super::write::orchestration::spawn_writer_tasks_and_join;
use super::{
Decoder, DecoderDeserializer, FileFormat, FileFormatFactory, FileScanConfig,
DEFAULT_SCHEMA_INFER_MAX_RECORD,
};
use crate::datasource::file_format::file_compression_type::FileCompressionType;
+use crate::datasource::file_format::write::demux::DemuxedStreamReceiver;
use crate::datasource::file_format::write::BatchSerializer;
-use crate::datasource::physical_plan::FileGroupDisplay;
+use crate::datasource::physical_plan::{FileGroupDisplay, FileSink};
use crate::datasource::physical_plan::{FileSinkConfig, NdJsonExec};
use crate::error::Result;
use crate::execution::context::SessionState;
@@ -49,10 +50,10 @@ use arrow_schema::ArrowError;
use datafusion_common::config::{ConfigField, ConfigFileType, JsonOptions};
use datafusion_common::file_options::json_writer::JsonWriterOptions;
use datafusion_common::{not_impl_err, GetExt, DEFAULT_JSON_EXTENSION};
+use datafusion_common_runtime::SpawnedTask;
use datafusion_execution::TaskContext;
use datafusion_expr::dml::InsertOp;
use datafusion_physical_expr::PhysicalExpr;
-use datafusion_physical_plan::metrics::MetricsSet;
use datafusion_physical_plan::ExecutionPlan;
use async_trait::async_trait;
@@ -266,15 +267,9 @@ impl FileFormat for JsonFormat {
let writer_options = JsonWriterOptions::try_from(&self.options)?;
- let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(JsonSink::new(conf, writer_options));
- Ok(Arc::new(DataSinkExec::new(
- input,
- sink,
- sink_schema,
- order_requirements,
- )) as _)
+ Ok(Arc::new(DataSinkExec::new(input, sink, order_requirements)) as _)
}
}
@@ -338,32 +333,36 @@ impl JsonSink {
}
}
- /// Retrieve the inner [`FileSinkConfig`].
- pub fn config(&self) -> &FileSinkConfig {
+ /// Retrieve the writer options
+ pub fn writer_options(&self) -> &JsonWriterOptions {
+ &self.writer_options
+ }
+}
+
+#[async_trait]
+impl FileSink for JsonSink {
+ fn config(&self) -> &FileSinkConfig {
&self.config
}
- async fn multipartput_all(
+ async fn spawn_writer_tasks_and_join(
&self,
- data: SendableRecordBatchStream,
context: &Arc<TaskContext>,
+ demux_task: SpawnedTask<Result<()>>,
+ file_stream_rx: DemuxedStreamReceiver,
+ object_store: Arc<dyn ObjectStore>,
) -> Result<u64> {
- let get_serializer = move || Arc::new(JsonSerializer::new()) as _;
-
- stateless_multipart_put(
- data,
+ let serializer = Arc::new(JsonSerializer::new()) as _;
+ spawn_writer_tasks_and_join(
context,
- "json".into(),
- Box::new(get_serializer),
- &self.config,
+ serializer,
self.writer_options.compression.into(),
+ object_store,
+ demux_task,
+ file_stream_rx,
)
.await
}
- /// Retrieve the writer options
- pub fn writer_options(&self) -> &JsonWriterOptions {
- &self.writer_options
- }
}
#[async_trait]
@@ -372,8 +371,8 @@ impl DataSink for JsonSink {
self
}
- fn metrics(&self) -> Option<MetricsSet> {
- None
+ fn schema(&self) -> &SchemaRef {
+ self.config.output_schema()
}
async fn write_all(
@@ -381,8 +380,7 @@ impl DataSink for JsonSink {
data: SendableRecordBatchStream,
context: &Arc<TaskContext>,
) -> Result<u64> {
- let total_count = self.multipartput_all(data, context).await?;
- Ok(total_count)
+ FileSink::write_all(self, data, context).await
}
}
diff --git a/datafusion/core/src/datasource/file_format/parquet.rs b/datafusion/core/src/datasource/file_format/parquet.rs
index 8f64bea39d..9243f6f12b 100644
--- a/datafusion/core/src/datasource/file_format/parquet.rs
+++ b/datafusion/core/src/datasource/file_format/parquet.rs
@@ -23,7 +23,7 @@ use std::fmt::Debug;
use std::ops::Range;
use std::sync::Arc;
-use super::write::demux::start_demuxer_task;
+use super::write::demux::DemuxedStreamReceiver;
use super::write::{create_writer, SharedBuffer};
use super::{
coerce_file_schema_to_string_type, coerce_file_schema_to_view_type,
@@ -33,7 +33,11 @@ use super::{
use crate::arrow::array::RecordBatch;
use crate::arrow::datatypes::{Fields, Schema, SchemaRef};
use crate::datasource::file_format::file_compression_type::FileCompressionType;
-use crate::datasource::physical_plan::{FileGroupDisplay, FileSinkConfig};
+use crate::datasource::file_format::write::get_writer_schema;
+use crate::datasource::physical_plan::parquet::{
+ can_expr_be_pushed_down_with_schemas, ParquetExecBuilder,
+};
+use crate::datasource::physical_plan::{FileGroupDisplay, FileSink, FileSinkConfig};
use crate::datasource::statistics::{create_max_min_accs, get_col_stats};
use crate::error::Result;
use crate::execution::context::SessionState;
@@ -47,6 +51,7 @@ use arrow::compute::sum;
use datafusion_common::config::{ConfigField, ConfigFileType, TableParquetOptions};
use datafusion_common::parsers::CompressionTypeVariant;
use datafusion_common::stats::Precision;
+use datafusion_common::HashMap;
use datafusion_common::{
internal_datafusion_err, internal_err, not_impl_err, DataFusionError, GetExt,
DEFAULT_PARQUET_EXTENSION,
@@ -58,20 +63,26 @@ use datafusion_expr::dml::InsertOp;
use datafusion_expr::Expr;
use datafusion_functions_aggregate::min_max::{MaxAccumulator, MinAccumulator};
use datafusion_physical_expr::PhysicalExpr;
-use datafusion_physical_plan::metrics::MetricsSet;
+use datafusion_physical_expr_common::sort_expr::LexRequirement;
use async_trait::async_trait;
use bytes::Bytes;
-use datafusion_common::HashMap;
+use futures::future::BoxFuture;
+use futures::{FutureExt, StreamExt, TryStreamExt};
use log::debug;
use object_store::buffered::BufWriter;
+use object_store::path::Path;
+use object_store::{ObjectMeta, ObjectStore};
+use parquet::arrow::arrow_reader::statistics::StatisticsConverter;
use parquet::arrow::arrow_writer::{
compute_leaves, get_column_writers, ArrowColumnChunk, ArrowColumnWriter,
ArrowLeafColumn, ArrowWriterOptions,
};
+use parquet::arrow::async_reader::MetadataFetch;
use parquet::arrow::{
arrow_to_parquet_schema, parquet_to_arrow_schema, AsyncArrowWriter,
};
+use parquet::errors::ParquetError;
use parquet::file::metadata::{ParquetMetaData, ParquetMetaDataReader, RowGroupMetaData};
use parquet::file::properties::{WriterProperties, WriterPropertiesBuilder};
use parquet::file::writer::SerializedFileWriter;
@@ -80,18 +91,6 @@ use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::mpsc::{self, Receiver, Sender};
use tokio::task::JoinSet;
-use crate::datasource::physical_plan::parquet::{
- can_expr_be_pushed_down_with_schemas, ParquetExecBuilder,
-};
-use datafusion_physical_expr_common::sort_expr::LexRequirement;
-use futures::future::BoxFuture;
-use futures::{FutureExt, StreamExt, TryStreamExt};
-use object_store::path::Path;
-use object_store::{ObjectMeta, ObjectStore};
-use parquet::arrow::arrow_reader::statistics::StatisticsConverter;
-use parquet::arrow::async_reader::MetadataFetch;
-use parquet::errors::ParquetError;
-
/// Initial writing buffer size. Note this is just a size hint for efficiency. It
/// will grow beyond the set value if needed.
const INITIAL_BUFFER_BYTES: usize = 1048576;
@@ -431,15 +430,9 @@ impl FileFormat for ParquetFormat {
return not_impl_err!("Overwrites are not implemented yet for Parquet");
}
- let sink_schema = Arc::clone(conf.output_schema());
let sink = Arc::new(ParquetSink::new(conf, self.options.clone()));
- Ok(Arc::new(DataSinkExec::new(
- input,
- sink,
- sink_schema,
- order_requirements,
- )) as _)
+ Ok(Arc::new(DataSinkExec::new(input, sink, order_requirements)) as _)
}
fn supports_filters_pushdown(
@@ -529,7 +522,7 @@ async fn fetch_schema(
/// Read and parse the statistics of the Parquet file at location `path`
///
-/// See [`statistics_from_parquet_meta`] for more details
+/// See [`statistics_from_parquet_meta_calc`] for more details
async fn fetch_statistics(
store: &dyn ObjectStore,
table_schema: SchemaRef,
@@ -710,53 +703,20 @@ impl ParquetSink {
}
}
- /// Retrieve the inner [`FileSinkConfig`].
- pub fn config(&self) -> &FileSinkConfig {
- &self.config
- }
-
/// Retrieve the file metadata for the written files, keyed to the path
/// which may be partitioned (in the case of hive style partitioning).
pub fn written(&self) -> HashMap<Path, FileMetaData> {
self.written.lock().clone()
}
- /// Converts table schema to writer schema, which may differ in the case
- /// of hive style partitioning where some columns are removed from the
- /// underlying files.
- fn get_writer_schema(&self) -> Arc<Schema> {
- if !self.config.table_partition_cols.is_empty()
- && !self.config.keep_partition_by_columns
- {
- let schema = self.config.output_schema();
- let partition_names: Vec<_> = self
- .config
- .table_partition_cols
- .iter()
- .map(|(s, _)| s)
- .collect();
- Arc::new(Schema::new_with_metadata(
- schema
- .fields()
- .iter()
- .filter(|f| !partition_names.contains(&f.name()))
- .map(|f| (**f).clone())
- .collect::<Vec<_>>(),
- schema.metadata().clone(),
- ))
- } else {
- Arc::clone(self.config.output_schema())
- }
- }
-
/// Create writer properties based upon configuration settings,
/// including partitioning and the inclusion of arrow schema metadata.
fn create_writer_props(&self) -> Result<WriterProperties> {
let schema = if self.parquet_options.global.allow_single_file_parallelism {
// If parallelizing writes, we may be also be doing hive style partitioning
// into multiple files which impacts the schema per file.
- // Refer to `self.get_writer_schema()`
- &self.get_writer_schema()
+ // Refer to `get_writer_schema()`
+ &get_writer_schema(&self.config)
} else {
self.config.output_schema()
};
@@ -786,7 +746,7 @@ impl ParquetSink {
let writer = AsyncArrowWriter::try_new_with_options(
buf_writer,
- self.get_writer_schema(),
+ get_writer_schema(&self.config),
options,
)?;
Ok(writer)
@@ -799,36 +759,27 @@ impl ParquetSink {
}
#[async_trait]
-impl DataSink for ParquetSink {
- fn as_any(&self) -> &dyn Any {
- self
- }
-
- fn metrics(&self) -> Option<MetricsSet> {
- None
+impl FileSink for ParquetSink {
+ fn config(&self) -> &FileSinkConfig {
+ &self.config
}
- async fn write_all(
+ async fn spawn_writer_tasks_and_join(
&self,
- data: SendableRecordBatchStream,
context: &Arc<TaskContext>,
+ demux_task: SpawnedTask<Result<()>>,
+ mut file_stream_rx: DemuxedStreamReceiver,
+ object_store: Arc<dyn ObjectStore>,
) -> Result<u64> {
- let parquet_props = self.create_writer_props()?;
-
- let object_store = context
- .runtime_env()
- .object_store(&self.config.object_store_url)?;
-
let parquet_opts = &self.parquet_options;
let allow_single_file_parallelism =
parquet_opts.global.allow_single_file_parallelism;
- let part_col = if !self.config.table_partition_cols.is_empty() {
- Some(self.config.table_partition_cols.clone())
- } else {
- None
- };
+ let mut file_write_tasks: JoinSet<
+ std::result::Result<(Path, FileMetaData), DataFusionError>,
+ > = JoinSet::new();
+ let parquet_props = self.create_writer_props()?;
let parallel_options = ParallelParquetWriterOptions {
max_parallel_row_groups: parquet_opts
.global
@@ -838,19 +789,6 @@ impl DataSink for ParquetSink {
.maximum_buffered_record_batches_per_stream,
};
- let (demux_task, mut file_stream_rx) = start_demuxer_task(
- data,
- context,
- part_col,
- self.config.table_paths[0].clone(),
- "parquet".into(),
- self.config.keep_partition_by_columns,
- );
-
- let mut file_write_tasks: JoinSet<
- std::result::Result<(Path, FileMetaData), DataFusionError>,
- > = JoinSet::new();
-
while let Some((path, mut rx)) = file_stream_rx.recv().await {
if !allow_single_file_parallelism {
let mut writer = self
@@ -883,7 +821,7 @@ impl DataSink for ParquetSink {
Arc::clone(&object_store),
)
.await?;
- let schema = self.get_writer_schema();
+ let schema = get_writer_schema(&self.config);
let props = parquet_props.clone();
let parallel_options_clone = parallel_options.clone();
let pool = Arc::clone(context.memory_pool());
@@ -933,6 +871,25 @@ impl DataSink for ParquetSink {
}
}
+#[async_trait]
+impl DataSink for ParquetSink {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn schema(&self) -> &SchemaRef {
+ self.config.output_schema()
+ }
+
+ async fn write_all(
+ &self,
+ data: SendableRecordBatchStream,
+ context: &Arc<TaskContext>,
+ ) -> Result<u64> {
+ FileSink::write_all(self, data, context).await
+ }
+}
+
/// Consumes a stream of [ArrowLeafColumn] via a channel and serializes them using an [ArrowColumnWriter]
/// Once the channel is exhausted, returns the ArrowColumnWriter.
async fn column_serializer_task(
@@ -2581,6 +2538,7 @@ mod tests {
table_partition_cols: vec![],
insert_op: InsertOp::Overwrite,
keep_partition_by_columns: false,
+ file_extension: "parquet".into(),
};
let parquet_sink = Arc::new(ParquetSink::new(
file_sink_config,
@@ -2600,16 +2558,15 @@ mod tests {
let batch = RecordBatch::try_from_iter(vec![("a", col_a), ("b", col_b)]).unwrap();
// write stream
- parquet_sink
- .write_all(
- Box::pin(RecordBatchStreamAdapter::new(
- schema,
- futures::stream::iter(vec![Ok(batch)]),
- )),
- &build_ctx(object_store_url.as_ref()),
- )
- .await
- .unwrap();
+ FileSink::write_all(
+ parquet_sink.as_ref(),
+ Box::pin(RecordBatchStreamAdapter::new(
+ schema,
+ futures::stream::iter(vec![Ok(batch)]),
+ )),
+ &build_ctx(object_store_url.as_ref()),
+ )
+ .await?;
Ok(parquet_sink)
}
@@ -2666,6 +2623,7 @@ mod tests {
table_partition_cols: vec![("a".to_string(), DataType::Utf8)], // add partitioning
insert_op: InsertOp::Overwrite,
keep_partition_by_columns: false,
+ file_extension: "parquet".into(),
};
let parquet_sink = Arc::new(ParquetSink::new(
file_sink_config,
@@ -2678,16 +2636,15 @@ mod tests {
let batch = RecordBatch::try_from_iter(vec![("a", col_a), ("b", col_b)]).unwrap();
// write stream
- parquet_sink
- .write_all(
- Box::pin(RecordBatchStreamAdapter::new(
- schema,
- futures::stream::iter(vec![Ok(batch)]),
- )),
- &build_ctx(object_store_url.as_ref()),
- )
- .await
- .unwrap();
+ FileSink::write_all(
+ parquet_sink.as_ref(),
+ Box::pin(RecordBatchStreamAdapter::new(
+ schema,
+ futures::stream::iter(vec![Ok(batch)]),
+ )),
+ &build_ctx(object_store_url.as_ref()),
+ )
+ .await?;
// assert written
let mut written = parquet_sink.written();
@@ -2749,6 +2706,7 @@ mod tests {
table_partition_cols: vec![],
insert_op: InsertOp::Overwrite,
keep_partition_by_columns: false,
+ file_extension: "parquet".into(),
};
let parquet_sink = Arc::new(ParquetSink::new(
file_sink_config,
@@ -2776,7 +2734,8 @@ mod tests {
"no bytes are reserved yet"
);
- let mut write_task = parquet_sink.write_all(
+ let mut write_task = FileSink::write_all(
+ parquet_sink.as_ref(),
Box::pin(RecordBatchStreamAdapter::new(
schema,
bounded_stream(batch, 1000),
diff --git a/datafusion/core/src/datasource/file_format/write/demux.rs b/datafusion/core/src/datasource/file_format/write/demux.rs
index 115d1ea710..48db2c0802 100644
--- a/datafusion/core/src/datasource/file_format/write/demux.rs
+++ b/datafusion/core/src/datasource/file_format/write/demux.rs
@@ -20,11 +20,10 @@
use std::borrow::Cow;
use std::collections::HashMap;
-
use std::sync::Arc;
use crate::datasource::listing::ListingTableUrl;
-
+use crate::datasource::physical_plan::FileSinkConfig;
use crate::error::Result;
use crate::physical_plan::SendableRecordBatchStream;
@@ -32,7 +31,6 @@ use arrow_array::builder::UInt64Builder;
use arrow_array::cast::AsArray;
use arrow_array::{downcast_dictionary_array, RecordBatch, StringArray, StructArray};
use arrow_schema::{DataType, Schema};
-use chrono::NaiveDate;
use datafusion_common::cast::{
as_boolean_array, as_date32_array, as_date64_array, as_int32_array, as_int64_array,
as_string_array, as_string_view_array,
@@ -41,15 +39,14 @@ use datafusion_common::{exec_datafusion_err, not_impl_err, DataFusionError};
use datafusion_common_runtime::SpawnedTask;
use datafusion_execution::TaskContext;
+use chrono::NaiveDate;
use futures::StreamExt;
use object_store::path::Path;
-
use rand::distributions::DistString;
-
use tokio::sync::mpsc::{self, Receiver, Sender, UnboundedReceiver, UnboundedSender};
type RecordBatchReceiver = Receiver<RecordBatch>;
-type DemuxedStreamReceiver = UnboundedReceiver<(Path, RecordBatchReceiver)>;
+pub type DemuxedStreamReceiver = UnboundedReceiver<(Path, RecordBatchReceiver)>;
/// Splits a single [SendableRecordBatchStream] into a dynamically determined
/// number of partitions at execution time.
@@ -92,45 +89,45 @@ type DemuxedStreamReceiver = UnboundedReceiver<(Path, RecordBatchReceiver)>;
/// └───────────┘ └────────────┘ └─────────────┘
/// ```
pub(crate) fn start_demuxer_task(
- input: SendableRecordBatchStream,
+ config: &FileSinkConfig,
+ data: SendableRecordBatchStream,
context: &Arc<TaskContext>,
- partition_by: Option<Vec<(String, DataType)>>,
- base_output_path: ListingTableUrl,
- default_extension: String,
- keep_partition_by_columns: bool,
) -> (SpawnedTask<Result<()>>, DemuxedStreamReceiver) {
let (tx, rx) = mpsc::unbounded_channel();
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 {
- Some(parts) => {
- // There could be an arbitrarily large number of parallel hive style partitions being written to, so we cannot
- // bound this channel without risking a deadlock.
- SpawnedTask::spawn(async move {
- hive_style_partitions_demuxer(
- tx,
- input,
- context,
- parts,
- base_output_path,
- default_extension,
- keep_partition_by_columns,
- )
- .await
- })
- }
- None => SpawnedTask::spawn(async move {
+ let file_extension = config.file_extension.clone();
+ let base_output_path = config.table_paths[0].clone();
+ let task = if config.table_partition_cols.is_empty() {
+ let single_file_output = !base_output_path.is_collection()
+ && base_output_path.file_extension().is_some();
+ SpawnedTask::spawn(async move {
row_count_demuxer(
tx,
- input,
+ data,
context,
base_output_path,
- default_extension,
+ file_extension,
single_file_output,
)
.await
- }),
+ })
+ } else {
+ // There could be an arbitrarily large number of parallel hive style partitions being written to, so we cannot
+ // bound this channel without risking a deadlock.
+ let partition_by = config.table_partition_cols.clone();
+ let keep_partition_by_columns = config.keep_partition_by_columns;
+ SpawnedTask::spawn(async move {
+ hive_style_partitions_demuxer(
+ tx,
+ data,
+ context,
+ partition_by,
+ base_output_path,
+ file_extension,
+ keep_partition_by_columns,
+ )
+ .await
+ })
};
(task, rx)
diff --git a/datafusion/core/src/datasource/file_format/write/mod.rs b/datafusion/core/src/datasource/file_format/write/mod.rs
index 42115fc7b9..c064999c1e 100644
--- a/datafusion/core/src/datasource/file_format/write/mod.rs
+++ b/datafusion/core/src/datasource/file_format/write/mod.rs
@@ -22,10 +22,11 @@ use std::io::Write;
use std::sync::Arc;
use crate::datasource::file_format::file_compression_type::FileCompressionType;
+use crate::datasource::physical_plan::FileSinkConfig;
use crate::error::Result;
use arrow_array::RecordBatch;
-
+use arrow_schema::Schema;
use bytes::Bytes;
use object_store::buffered::BufWriter;
use object_store::path::Path;
@@ -86,3 +87,25 @@ pub(crate) async fn create_writer(
let buf_writer = BufWriter::new(object_store, location.clone());
file_compression_type.convert_async_writer(buf_writer)
}
+
+/// Converts table schema to writer schema, which may differ in the case
+/// of hive style partitioning where some columns are removed from the
+/// underlying files.
+pub(crate) fn get_writer_schema(config: &FileSinkConfig) -> Arc<Schema> {
+ if !config.table_partition_cols.is_empty() && !config.keep_partition_by_columns {
+ let schema = config.output_schema();
+ let partition_names: Vec<_> =
+ config.table_partition_cols.iter().map(|(s, _)| s).collect();
+ Arc::new(Schema::new_with_metadata(
+ schema
+ .fields()
+ .iter()
+ .filter(|f| !partition_names.contains(&f.name()))
+ .map(|f| (**f).clone())
+ .collect::<Vec<_>>(),
+ schema.metadata().clone(),
+ ))
+ } else {
+ Arc::clone(config.output_schema())
+ }
+}
diff --git a/datafusion/core/src/datasource/file_format/write/orchestration.rs b/datafusion/core/src/datasource/file_format/write/orchestration.rs
index 457481b5ad..7a271def7d 100644
--- a/datafusion/core/src/datasource/file_format/write/orchestration.rs
+++ b/datafusion/core/src/datasource/file_format/write/orchestration.rs
@@ -21,12 +21,10 @@
use std::sync::Arc;
-use super::demux::start_demuxer_task;
+use super::demux::DemuxedStreamReceiver;
use super::{create_writer, BatchSerializer};
use crate::datasource::file_format::file_compression_type::FileCompressionType;
-use crate::datasource::physical_plan::FileSinkConfig;
use crate::error::Result;
-use crate::physical_plan::SendableRecordBatchStream;
use arrow_array::RecordBatch;
use datafusion_common::{internal_datafusion_err, internal_err, DataFusionError};
@@ -35,6 +33,7 @@ use datafusion_execution::TaskContext;
use bytes::Bytes;
use futures::join;
+use object_store::ObjectStore;
use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::mpsc::{self, Receiver};
use tokio::task::JoinSet;
@@ -53,11 +52,11 @@ pub(crate) enum SerializedRecordBatchResult {
},
Failure {
/// As explained in [`serialize_rb_stream_to_object_store`]:
- /// - If an IO error occured that involved the ObjectStore writer, then the writer will not be returned to the caller
+ /// - If an IO error occurred that involved the ObjectStore writer, then the writer will not be returned to the caller
/// - Otherwise, the writer is returned to the caller
writer: Option<WriterType>,
- /// the actual error that occured
+ /// the actual error that occurred
err: DataFusionError,
},
}
@@ -238,34 +237,14 @@ pub(crate) async fn stateless_serialize_and_write_files(
/// Orchestrates multipart put of a dynamic number of output files from a single input stream
/// for any statelessly serialized file type. That is, any file type for which each [RecordBatch]
/// can be serialized independently of all other [RecordBatch]s.
-pub(crate) async fn stateless_multipart_put(
- data: SendableRecordBatchStream,
+pub(crate) async fn spawn_writer_tasks_and_join(
context: &Arc<TaskContext>,
- file_extension: String,
- get_serializer: Box<dyn Fn() -> Arc<dyn BatchSerializer> + Send>,
- config: &FileSinkConfig,
+ serializer: Arc<dyn BatchSerializer>,
compression: FileCompressionType,
+ object_store: Arc<dyn ObjectStore>,
+ demux_task: SpawnedTask<Result<()>>,
+ mut file_stream_rx: DemuxedStreamReceiver,
) -> Result<u64> {
- let object_store = context
- .runtime_env()
- .object_store(&config.object_store_url)?;
-
- let base_output_path = &config.table_paths[0];
- let part_cols = if !config.table_partition_cols.is_empty() {
- Some(config.table_partition_cols.clone())
- } else {
- None
- };
-
- let (demux_task, mut file_stream_rx) = start_demuxer_task(
- data,
- context,
- part_cols,
- base_output_path.clone(),
- file_extension,
- config.keep_partition_by_columns,
- );
-
let rb_buffer_size = &context
.session_config()
.options()
@@ -278,18 +257,18 @@ pub(crate) async fn stateless_multipart_put(
stateless_serialize_and_write_files(rx_file_bundle, tx_row_cnt).await
});
while let Some((location, rb_stream)) = file_stream_rx.recv().await {
- let serializer = get_serializer();
let writer =
create_writer(compression, &location, Arc::clone(&object_store)).await?;
- tx_file_bundle
- .send((rb_stream, serializer, writer))
+ if tx_file_bundle
+ .send((rb_stream, Arc::clone(&serializer), writer))
.await
- .map_err(|_| {
- internal_datafusion_err!(
- "Writer receive file bundle channel closed unexpectedly!"
- )
- })?;
+ .is_err()
+ {
+ internal_datafusion_err!(
+ "Writer receive file bundle channel closed unexpectedly!"
+ );
+ }
}
// Signal to the write coordinator that no more files are coming
@@ -302,9 +281,8 @@ pub(crate) async fn stateless_multipart_put(
r1.map_err(DataFusionError::ExecutionJoin)??;
r2.map_err(DataFusionError::ExecutionJoin)??;
- let total_count = rx_row_cnt.await.map_err(|_| {
+ // Return total row count:
+ rx_row_cnt.await.map_err(|_| {
internal_datafusion_err!("Did not receive row count from write coordinator")
- })?;
-
- Ok(total_count)
+ })
}
diff --git a/datafusion/core/src/datasource/listing/table.rs b/datafusion/core/src/datasource/listing/table.rs
index 06b94f8042..b2a96d1115 100644
--- a/datafusion/core/src/datasource/listing/table.rs
+++ b/datafusion/core/src/datasource/listing/table.rs
@@ -1050,21 +1050,22 @@ impl TableProvider for ListingTable {
table_partition_cols: self.options.table_partition_cols.clone(),
insert_op,
keep_partition_by_columns,
+ file_extension: self.options().format.get_ext(),
};
let order_requirements = if !self.options().file_sort_order.is_empty() {
// Multiple sort orders in outer vec are equivalent, so we pass only the first one
- let ordering = self
- .try_create_output_ordering()?
- .first()
- .ok_or(DataFusionError::Internal(
- "Expected ListingTable to have a sort order, but none found!".into(),
- ))?
- .clone();
+ let orderings = self.try_create_output_ordering()?;
+ let Some(ordering) = orderings.first() else {
+ return internal_err!(
+ "Expected ListingTable to have a sort order, but none found!"
+ );
+ };
// Converts Vec<Vec<SortExpr>> into type required by execution plan to specify its required input ordering
Some(LexRequirement::new(
ordering
.into_iter()
+ .cloned()
.map(PhysicalSortRequirement::from)
.collect::<Vec<_>>(),
))
diff --git a/datafusion/core/src/datasource/memory.rs b/datafusion/core/src/datasource/memory.rs
index 095dab9d91..e368ee3fec 100644
--- a/datafusion/core/src/datasource/memory.rs
+++ b/datafusion/core/src/datasource/memory.rs
@@ -42,7 +42,6 @@ use datafusion_common::{not_impl_err, plan_err, Constraints, DFSchema, SchemaExt
use datafusion_execution::TaskContext;
use datafusion_expr::dml::InsertOp;
use datafusion_expr::SortExpr;
-use datafusion_physical_plan::metrics::MetricsSet;
use async_trait::async_trait;
use futures::StreamExt;
@@ -293,13 +292,8 @@ impl TableProvider for MemTable {
if insert_op != InsertOp::Append {
return not_impl_err!("{insert_op} not implemented for MemoryTable yet");
}
- let sink = Arc::new(MemSink::try_new(self.batches.clone())?);
- Ok(Arc::new(DataSinkExec::new(
- input,
- sink,
- Arc::clone(&self.schema),
- None,
- )))
+ let sink = MemSink::try_new(self.batches.clone(), Arc::clone(&self.schema))?;
+ Ok(Arc::new(DataSinkExec::new(input, Arc::new(sink), None)))
}
fn get_column_default(&self, column: &str) -> Option<&Expr> {
@@ -311,6 +305,7 @@ impl TableProvider for MemTable {
struct MemSink {
/// Target locations for writing data
batches: Vec<PartitionData>,
+ schema: SchemaRef,
}
impl Debug for MemSink {
@@ -336,11 +331,11 @@ impl MemSink {
/// Creates a new [`MemSink`].
///
/// The caller is responsible for ensuring that there is at least one partition to insert into.
- fn try_new(batches: Vec<PartitionData>) -> Result<Self> {
+ fn try_new(batches: Vec<PartitionData>, schema: SchemaRef) -> Result<Self> {
if batches.is_empty() {
return plan_err!("Cannot insert into MemTable with zero partitions");
}
- Ok(Self { batches })
+ Ok(Self { batches, schema })
}
}
@@ -350,8 +345,8 @@ impl DataSink for MemSink {
self
}
- fn metrics(&self) -> Option<MetricsSet> {
- None
+ fn schema(&self) -> &SchemaRef {
+ &self.schema
}
async fn write_all(
diff --git a/datafusion/core/src/datasource/physical_plan/mod.rs b/datafusion/core/src/datasource/physical_plan/mod.rs
index 3146d124d9..80f92325bd 100644
--- a/datafusion/core/src/datasource/physical_plan/mod.rs
+++ b/datafusion/core/src/datasource/physical_plan/mod.rs
@@ -51,7 +51,8 @@ use std::{
vec,
};
-use super::listing::ListingTableUrl;
+use super::{file_format::write::demux::start_demuxer_task, listing::ListingTableUrl};
+use crate::datasource::file_format::write::demux::DemuxedStreamReceiver;
use crate::error::Result;
use crate::physical_plan::{DisplayAs, DisplayFormatType};
use crate::{
@@ -63,14 +64,73 @@ use crate::{
};
use arrow::datatypes::{DataType, SchemaRef};
+use datafusion_common_runtime::SpawnedTask;
+use datafusion_execution::{SendableRecordBatchStream, TaskContext};
use datafusion_physical_expr::expressions::Column;
use datafusion_physical_expr::PhysicalSortExpr;
use datafusion_physical_expr_common::sort_expr::LexOrdering;
+use datafusion_physical_plan::insert::DataSink;
+use async_trait::async_trait;
use futures::StreamExt;
use log::debug;
use object_store::{path::Path, GetOptions, GetRange, ObjectMeta, ObjectStore};
+/// General behaviors for files that do `DataSink` operations
+#[async_trait]
+pub trait FileSink: DataSink {
+ /// Retrieves the file sink configuration.
+ fn config(&self) -> &FileSinkConfig;
+
+ /// Spawns writer tasks and joins them to perform file writing operations.
+ /// Is a critical part of `FileSink` trait, since it's the very last step for `write_all`.
+ ///
+ /// This function handles the process of writing data to files by:
+ /// 1. Spawning tasks for writing data to individual files.
+ /// 2. Coordinating the tasks using a demuxer to distribute data among files.
+ /// 3. Collecting results using `tokio::join`, ensuring that all tasks complete successfully.
+ ///
+ /// # Parameters
+ /// - `context`: The execution context (`TaskContext`) that provides resources
+ /// like memory management and runtime environment.
+ /// - `demux_task`: A spawned task that handles demuxing, responsible for splitting
+ /// an input [`SendableRecordBatchStream`] into dynamically determined partitions.
+ /// See `start_demuxer_task()`
+ /// - `file_stream_rx`: A receiver that yields streams of record batches and their
+ /// corresponding file paths for writing. See `start_demuxer_task()`
+ /// - `object_store`: A handle to the object store where the files are written.
+ ///
+ /// # Returns
+ /// - `Result<u64>`: Returns the total number of rows written across all files.
+ async fn spawn_writer_tasks_and_join(
+ &self,
+ context: &Arc<TaskContext>,
+ demux_task: SpawnedTask<Result<()>>,
+ file_stream_rx: DemuxedStreamReceiver,
+ object_store: Arc<dyn ObjectStore>,
+ ) -> Result<u64>;
+
+ /// File sink implementation of the [`DataSink::write_all`] method.
+ async fn write_all(
+ &self,
+ data: SendableRecordBatchStream,
+ context: &Arc<TaskContext>,
+ ) -> Result<u64> {
+ let config = self.config();
+ let object_store = context
+ .runtime_env()
+ .object_store(&config.object_store_url)?;
+ let (demux_task, file_stream_rx) = start_demuxer_task(config, data, context);
+ self.spawn_writer_tasks_and_join(
+ context,
+ demux_task,
+ file_stream_rx,
+ object_store,
+ )
+ .await
+ }
+}
+
/// The base configurations to provide when creating a physical plan for
/// writing to any given file format.
pub struct FileSinkConfig {
@@ -90,6 +150,8 @@ pub struct FileSinkConfig {
pub insert_op: InsertOp,
/// Controls whether partition columns are kept for the file
pub keep_partition_by_columns: bool,
+ /// File extension without a dot(.)
+ pub file_extension: String,
}
impl FileSinkConfig {
diff --git a/datafusion/core/src/datasource/stream.rs b/datafusion/core/src/datasource/stream.rs
index 768761bb9c..56cbb126d0 100644
--- a/datafusion/core/src/datasource/stream.rs
+++ b/datafusion/core/src/datasource/stream.rs
@@ -36,7 +36,6 @@ use datafusion_execution::{SendableRecordBatchStream, TaskContext};
use datafusion_expr::dml::InsertOp;
use datafusion_expr::{CreateExternalTable, Expr, SortExpr, TableType};
use datafusion_physical_plan::insert::{DataSink, DataSinkExec};
-use datafusion_physical_plan::metrics::MetricsSet;
use datafusion_physical_plan::stream::RecordBatchReceiverStreamBuilder;
use datafusion_physical_plan::streaming::{PartitionStream, StreamingTableExec};
use datafusion_physical_plan::{DisplayAs, DisplayFormatType, ExecutionPlan};
@@ -366,7 +365,6 @@ impl TableProvider for StreamTable {
Ok(Arc::new(DataSinkExec::new(
input,
Arc::new(StreamWrite(Arc::clone(&self.0))),
- Arc::clone(self.0.source.schema()),
ordering,
)))
}
@@ -413,8 +411,8 @@ impl DataSink for StreamWrite {
self
}
- fn metrics(&self) -> Option<MetricsSet> {
- None
+ fn schema(&self) -> &SchemaRef {
+ self.0.source.schema()
}
async fn write_all(
diff --git a/datafusion/core/src/physical_planner.rs b/datafusion/core/src/physical_planner.rs
index 6a4f379e4d..b0232abbe4 100644
--- a/datafusion/core/src/physical_planner.rs
+++ b/datafusion/core/src/physical_planner.rs
@@ -521,6 +521,9 @@ impl DefaultPhysicalPlanner {
return Err(DataFusionError::Configuration(format!("provided value for 'execution.keep_partition_by_columns' was not recognized: \"{}\"", value))),
};
+ let sink_format = file_type_to_format(file_type)?
+ .create(session_state, source_option_tuples)?;
+
// Set file sink related options
let config = FileSinkConfig {
object_store_url,
@@ -530,11 +533,9 @@ impl DefaultPhysicalPlanner {
table_partition_cols,
insert_op: InsertOp::Append,
keep_partition_by_columns,
+ file_extension: sink_format.get_ext(),
};
- let sink_format = file_type_to_format(file_type)?
- .create(session_state, source_option_tuples)?;
-
sink_format
.create_writer_physical_plan(input_exec, session_state, config, None)
.await?
diff --git a/datafusion/physical-plan/src/insert.rs b/datafusion/physical-plan/src/insert.rs
index e848640386..bfb1e9d53d 100644
--- a/datafusion/physical-plan/src/insert.rs
+++ b/datafusion/physical-plan/src/insert.rs
@@ -57,7 +57,12 @@ pub trait DataSink: DisplayAs + Debug + Send + Sync {
/// [DataSink].
///
/// See [ExecutionPlan::metrics()] for more details
- fn metrics(&self) -> Option<MetricsSet>;
+ fn metrics(&self) -> Option<MetricsSet> {
+ None
+ }
+
+ /// Returns the sink schema
+ fn schema(&self) -> &SchemaRef;
// TODO add desired input ordering
// How does this sink want its input ordered?
@@ -83,8 +88,6 @@ pub struct DataSinkExec {
input: Arc<dyn ExecutionPlan>,
/// Sink to which to write
sink: Arc<dyn DataSink>,
- /// Schema of the sink for validating the input data
- sink_schema: SchemaRef,
/// Schema describing the structure of the output data.
count_schema: SchemaRef,
/// Optional required sort order for output data.
@@ -103,7 +106,6 @@ impl DataSinkExec {
pub fn new(
input: Arc<dyn ExecutionPlan>,
sink: Arc<dyn DataSink>,
- sink_schema: SchemaRef,
sort_order: Option<LexRequirement>,
) -> Self {
let count_schema = make_count_schema();
@@ -111,7 +113,6 @@ impl DataSinkExec {
Self {
input,
sink,
- sink_schema,
count_schema: make_count_schema(),
sort_order,
cache,
@@ -209,7 +210,6 @@ impl ExecutionPlan for DataSinkExec {
Ok(Arc::new(Self::new(
Arc::clone(&children[0]),
Arc::clone(&self.sink),
- Arc::clone(&self.sink_schema),
self.sort_order.clone(),
)))
}
@@ -226,7 +226,7 @@ impl ExecutionPlan for DataSinkExec {
}
let data = execute_input_stream(
Arc::clone(&self.input),
- Arc::clone(&self.sink_schema),
+ Arc::clone(self.sink.schema()),
0,
Arc::clone(&context),
)?;
diff --git a/datafusion/proto/proto/datafusion.proto b/datafusion/proto/proto/datafusion.proto
index 4868017aa7..5e05311737 100644
--- a/datafusion/proto/proto/datafusion.proto
+++ b/datafusion/proto/proto/datafusion.proto
@@ -745,6 +745,7 @@ message FileSinkConfig {
repeated PartitionColumn table_partition_cols = 5;
bool keep_partition_by_columns = 9;
InsertOp insert_op = 10;
+ string file_extension = 11;
}
enum InsertOp {
diff --git a/datafusion/proto/src/generated/pbjson.rs b/datafusion/proto/src/generated/pbjson.rs
index 2850d350f6..84a1e73dec 100644
--- a/datafusion/proto/src/generated/pbjson.rs
+++ b/datafusion/proto/src/generated/pbjson.rs
@@ -5972,6 +5972,9 @@ impl serde::Serialize for FileSinkConfig {
if self.insert_op != 0 {
len += 1;
}
+ if !self.file_extension.is_empty() {
+ len += 1;
+ }
let mut struct_ser = serializer.serialize_struct("datafusion.FileSinkConfig", len)?;
if !self.object_store_url.is_empty() {
struct_ser.serialize_field("objectStoreUrl", &self.object_store_url)?;
@@ -5996,6 +5999,9 @@ impl serde::Serialize for FileSinkConfig {
.map_err(|_| serde::ser::Error::custom(format!("Invalid variant {}", self.insert_op)))?;
struct_ser.serialize_field("insertOp", &v)?;
}
+ if !self.file_extension.is_empty() {
+ struct_ser.serialize_field("fileExtension", &self.file_extension)?;
+ }
struct_ser.end()
}
}
@@ -6020,6 +6026,8 @@ impl<'de> serde::Deserialize<'de> for FileSinkConfig {
"keepPartitionByColumns",
"insert_op",
"insertOp",
+ "file_extension",
+ "fileExtension",
];
#[allow(clippy::enum_variant_names)]
@@ -6031,6 +6039,7 @@ impl<'de> serde::Deserialize<'de> for FileSinkConfig {
TablePartitionCols,
KeepPartitionByColumns,
InsertOp,
+ FileExtension,
}
impl<'de> serde::Deserialize<'de> for GeneratedField {
fn deserialize<D>(deserializer: D) -> std::result::Result<GeneratedField, D::Error>
@@ -6059,6 +6068,7 @@ impl<'de> serde::Deserialize<'de> for FileSinkConfig {
"tablePartitionCols" | "table_partition_cols" => Ok(GeneratedField::TablePartitionCols),
"keepPartitionByColumns" | "keep_partition_by_columns" => Ok(GeneratedField::KeepPartitionByColumns),
"insertOp" | "insert_op" => Ok(GeneratedField::InsertOp),
+ "fileExtension" | "file_extension" => Ok(GeneratedField::FileExtension),
_ => Err(serde::de::Error::unknown_field(value, FIELDS)),
}
}
@@ -6085,6 +6095,7 @@ impl<'de> serde::Deserialize<'de> for FileSinkConfig {
let mut table_partition_cols__ = None;
let mut keep_partition_by_columns__ = None;
let mut insert_op__ = None;
+ let mut file_extension__ = None;
while let Some(k) = map_.next_key()? {
match k {
GeneratedField::ObjectStoreUrl => {
@@ -6129,6 +6140,12 @@ impl<'de> serde::Deserialize<'de> for FileSinkConfig {
}
insert_op__ = Some(map_.next_value::<InsertOp>()? as i32);
}
+ GeneratedField::FileExtension => {
+ if file_extension__.is_some() {
+ return Err(serde::de::Error::duplicate_field("fileExtension"));
+ }
+ file_extension__ = Some(map_.next_value()?);
+ }
}
}
Ok(FileSinkConfig {
@@ -6139,6 +6156,7 @@ impl<'de> serde::Deserialize<'de> for FileSinkConfig {
table_partition_cols: table_partition_cols__.unwrap_or_default(),
keep_partition_by_columns: keep_partition_by_columns__.unwrap_or_default(),
insert_op: insert_op__.unwrap_or_default(),
+ file_extension: file_extension__.unwrap_or_default(),
})
}
}
diff --git a/datafusion/proto/src/generated/prost.rs b/datafusion/proto/src/generated/prost.rs
index a25e21739f..602b3edbbf 100644
--- a/datafusion/proto/src/generated/prost.rs
+++ b/datafusion/proto/src/generated/prost.rs
@@ -1136,6 +1136,8 @@ pub struct FileSinkConfig {
pub keep_partition_by_columns: bool,
#[prost(enumeration = "InsertOp", tag = "10")]
pub insert_op: i32,
+ #[prost(string, tag = "11")]
+ pub file_extension: ::prost::alloc::string::String,
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct JsonSink {
diff --git a/datafusion/proto/src/physical_plan/from_proto.rs b/datafusion/proto/src/physical_plan/from_proto.rs
index d1fe48cfec..db6239b56f 100644
--- a/datafusion/proto/src/physical_plan/from_proto.rs
+++ b/datafusion/proto/src/physical_plan/from_proto.rs
@@ -656,6 +656,7 @@ impl TryFrom<&protobuf::FileSinkConfig> for FileSinkConfig {
table_partition_cols,
insert_op,
keep_partition_by_columns: conf.keep_partition_by_columns,
+ file_extension: conf.file_extension.clone(),
})
}
}
diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rs
index 292ce13d0e..9eee72925f 100644
--- a/datafusion/proto/src/physical_plan/mod.rs
+++ b/datafusion/proto/src/physical_plan/mod.rs
@@ -1043,7 +1043,6 @@ impl AsExecutionPlan for protobuf::PhysicalPlanNode {
Ok(Arc::new(DataSinkExec::new(
input,
Arc::new(data_sink),
- sink_schema,
sort_order,
)))
}
@@ -1073,7 +1072,6 @@ impl AsExecutionPlan for protobuf::PhysicalPlanNode {
Ok(Arc::new(DataSinkExec::new(
input,
Arc::new(data_sink),
- sink_schema,
sort_order,
)))
}
@@ -1110,7 +1108,6 @@ impl AsExecutionPlan for protobuf::PhysicalPlanNode {
Ok(Arc::new(DataSinkExec::new(
input,
Arc::new(data_sink),
- sink_schema,
sort_order,
)))
}
diff --git a/datafusion/proto/src/physical_plan/to_proto.rs b/datafusion/proto/src/physical_plan/to_proto.rs
index 000d0521de..643815786b 100644
--- a/datafusion/proto/src/physical_plan/to_proto.rs
+++ b/datafusion/proto/src/physical_plan/to_proto.rs
@@ -19,6 +19,7 @@ use std::sync::Arc;
#[cfg(feature = "parquet")]
use datafusion::datasource::file_format::parquet::ParquetSink;
+use datafusion::datasource::physical_plan::FileSink;
use datafusion::physical_expr::window::{SlidingAggregateWindowExpr, StandardWindowExpr};
use datafusion::physical_expr::{LexOrdering, PhysicalSortExpr, ScalarFunctionExpr};
use datafusion::physical_plan::expressions::{
@@ -609,6 +610,7 @@ impl TryFrom<&FileSinkConfig> for protobuf::FileSinkConfig {
table_partition_cols,
keep_partition_by_columns: conf.keep_partition_by_columns,
insert_op: conf.insert_op as i32,
+ file_extension: conf.file_extension.to_string(),
})
}
}
diff --git a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs b/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
index 0a6ea6c7ff..48eba78d61 100644
--- a/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
+++ b/datafusion/proto/tests/cases/roundtrip_physical_plan.rs
@@ -1275,6 +1275,7 @@ fn roundtrip_json_sink() -> Result<()> {
table_partition_cols: vec![("plan_type".to_string(), DataType::Utf8)],
insert_op: InsertOp::Overwrite,
keep_partition_by_columns: true,
+ file_extension: "json".into(),
};
let data_sink = Arc::new(JsonSink::new(
file_sink_config,
@@ -1291,7 +1292,6 @@ fn roundtrip_json_sink() -> Result<()> {
roundtrip_test(Arc::new(DataSinkExec::new(
input,
data_sink,
- schema,
Some(sort_order),
)))
}
@@ -1311,6 +1311,7 @@ fn roundtrip_csv_sink() -> Result<()> {
table_partition_cols: vec![("plan_type".to_string(), DataType::Utf8)],
insert_op: InsertOp::Overwrite,
keep_partition_by_columns: true,
+ file_extension: "csv".into(),
};
let data_sink = Arc::new(CsvSink::new(
file_sink_config,
@@ -1327,12 +1328,7 @@ fn roundtrip_csv_sink() -> Result<()> {
let ctx = SessionContext::new();
let codec = DefaultPhysicalExtensionCodec {};
let roundtrip_plan = roundtrip_test_and_return(
- Arc::new(DataSinkExec::new(
- input,
- data_sink,
- schema,
- Some(sort_order),
- )),
+ Arc::new(DataSinkExec::new(input, data_sink, Some(sort_order))),
&ctx,
&codec,
)
@@ -1370,6 +1366,7 @@ fn roundtrip_parquet_sink() -> Result<()> {
table_partition_cols: vec![("plan_type".to_string(), DataType::Utf8)],
insert_op: InsertOp::Overwrite,
keep_partition_by_columns: true,
+ file_extension: "parquet".into(),
};
let data_sink = Arc::new(ParquetSink::new(
file_sink_config,
@@ -1386,7 +1383,6 @@ fn roundtrip_parquet_sink() -> Result<()> {
roundtrip_test(Arc::new(DataSinkExec::new(
input,
data_sink,
- schema,
Some(sort_order),
)))
}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@datafusion.apache.org
For additional commands, e-mail: commits-help@datafusion.apache.org