Skip to main content

datafusion_datasource/
file_sink_config.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use std::sync::Arc;
6
7use crate::ListingTableUrl;
8use crate::file_groups::FileGroup;
9use crate::sink::DataSink;
10use crate::write::demux::{DemuxedStreamReceiver, start_demuxer_task};
11
12use arrow::datatypes::{DataType, SchemaRef};
13use datafusion_common::Result;
14use datafusion_common_runtime::SpawnedTask;
15use datafusion_execution::object_store::ObjectStoreUrl;
16use datafusion_execution::{SendableRecordBatchStream, TaskContext};
17use datafusion_expr::dml::InsertOp;
18
19use async_trait::async_trait;
20use object_store::ObjectStore;
21
22#[cfg(feature = "proto")]
23mod proto;
24
25/// Determines how `FileSink` output paths are interpreted.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum FileOutputMode {
28    /// Infer output mode from the output URL (for example, by extension / trailing `/`).
29    #[default]
30    Automatic,
31    /// Write to a single output file at the exact output path.
32    SingleFile,
33    /// Write to a directory under the output path with generated filenames.
34    Directory,
35}
36
37impl FileOutputMode {
38    /// Resolve this mode into a `single_file_output` boolean for the demuxer.
39    pub fn single_file_output(self, base_output_path: &ListingTableUrl) -> bool {
40        match self {
41            Self::Automatic => {
42                !base_output_path.is_collection()
43                    && base_output_path.file_extension().is_some()
44            }
45            Self::SingleFile => true,
46            Self::Directory => false,
47        }
48    }
49}
50
51impl From<Option<bool>> for FileOutputMode {
52    fn from(value: Option<bool>) -> Self {
53        match value {
54            None => Self::Automatic,
55            Some(true) => Self::SingleFile,
56            Some(false) => Self::Directory,
57        }
58    }
59}
60
61impl From<FileOutputMode> for Option<bool> {
62    fn from(value: FileOutputMode) -> Self {
63        match value {
64            FileOutputMode::Automatic => None,
65            FileOutputMode::SingleFile => Some(true),
66            FileOutputMode::Directory => Some(false),
67        }
68    }
69}
70
71/// General behaviors for files that do `DataSink` operations
72#[async_trait]
73pub trait FileSink: DataSink {
74    /// Retrieves the file sink configuration.
75    fn config(&self) -> &FileSinkConfig;
76
77    /// Spawns writer tasks and joins them to perform file writing operations.
78    /// Is a critical part of `FileSink` trait, since it's the very last step for `write_all`.
79    ///
80    /// This function handles the process of writing data to files by:
81    /// 1. Spawning tasks for writing data to individual files.
82    /// 2. Coordinating the tasks using a demuxer to distribute data among files.
83    /// 3. Collecting results using `tokio::join`, ensuring that all tasks complete successfully.
84    ///
85    /// # Parameters
86    /// - `context`: The execution context (`TaskContext`) that provides resources
87    ///   like memory management and runtime environment.
88    /// - `demux_task`: A spawned task that handles demuxing, responsible for splitting
89    ///   an input [`SendableRecordBatchStream`] into dynamically determined partitions.
90    ///   See `start_demuxer_task()`
91    /// - `file_stream_rx`: A receiver that yields streams of record batches and their
92    ///   corresponding file paths for writing. See `start_demuxer_task()`
93    /// - `object_store`: A handle to the object store where the files are written.
94    ///
95    /// # Returns
96    /// - `Result<u64>`: Returns the total number of rows written across all files.
97    async fn spawn_writer_tasks_and_join(
98        &self,
99        context: &Arc<TaskContext>,
100        demux_task: SpawnedTask<Result<()>>,
101        file_stream_rx: DemuxedStreamReceiver,
102        object_store: Arc<dyn ObjectStore>,
103    ) -> Result<u64>;
104
105    /// File sink implementation of the [`DataSink::write_all`] method.
106    async fn write_all(
107        &self,
108        data: SendableRecordBatchStream,
109        context: &Arc<TaskContext>,
110    ) -> Result<u64> {
111        let config = self.config();
112        let object_store = context
113            .runtime_env()
114            .object_store(&config.object_store_url)?;
115        let (demux_task, file_stream_rx) = start_demuxer_task(config, data, context);
116        self.spawn_writer_tasks_and_join(
117            context,
118            demux_task,
119            file_stream_rx,
120            object_store,
121        )
122        .await
123    }
124}
125
126/// The base configurations to provide when creating a physical plan for
127/// writing to any given file format.
128#[derive(Debug, Clone)]
129pub struct FileSinkConfig {
130    /// The unresolved URL specified by the user
131    pub original_url: String,
132    /// Object store URL, used to get an ObjectStore instance
133    pub object_store_url: ObjectStoreUrl,
134    /// A collection of files organized into groups.
135    /// Each FileGroup contains one or more PartitionedFile objects.
136    pub file_group: FileGroup,
137    /// Vector of partition paths
138    pub table_paths: Vec<ListingTableUrl>,
139    /// The schema of the output file
140    pub output_schema: SchemaRef,
141    /// A vector of column names and their corresponding data types,
142    /// representing the partitioning columns for the file
143    pub table_partition_cols: Vec<(String, DataType)>,
144    /// Controls how new data should be written to the file, determining whether
145    /// to append to, overwrite, or replace records in existing files.
146    pub insert_op: InsertOp,
147    /// Controls whether partition columns are kept for the file
148    pub keep_partition_by_columns: bool,
149    /// File extension without a dot(.)
150    pub file_extension: String,
151    /// Determines how the output path is interpreted.
152    pub file_output_mode: FileOutputMode,
153}
154
155impl FileSinkConfig {
156    /// Get output schema
157    pub fn output_schema(&self) -> &SchemaRef {
158        &self.output_schema
159    }
160}