datafusion_datasource/write/mod.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
5//! Module containing helper methods/traits related to enabling
6//! write support for the various file formats
7
8use crate::file_compression_type::FileCompressionType;
9use crate::file_sink_config::FileSinkConfig;
10use crate::write::demux::FileSize;
11use arrow::array::RecordBatch;
12use arrow::datatypes::Schema;
13use bytes::Bytes;
14use datafusion_common::error::Result;
15use object_store::ObjectStore;
16use object_store::buffered::BufWriter;
17use object_store::path::Path;
18use pin_project_lite::pin_project;
19use std::io::{IoSlice, Write};
20use std::pin::Pin;
21use std::sync::Arc;
22use std::sync::atomic::{AtomicU64, Ordering};
23use std::task::{Context, Poll, ready};
24use tokio::io::AsyncWrite;
25
26pub mod demux;
27pub mod orchestration;
28
29/// A buffer with interior mutability shared by the SerializedFileWriter and
30/// ObjectStore writer
31#[derive(Clone)]
32pub struct SharedBuffer {
33 /// The inner buffer for reading and writing
34 ///
35 /// The lock is used to obtain internal mutability, so no worry about the
36 /// lock contention.
37 pub buffer: Arc<futures::lock::Mutex<Vec<u8>>>,
38}
39
40impl SharedBuffer {
41 pub fn new(capacity: usize) -> Self {
42 Self {
43 buffer: Arc::new(futures::lock::Mutex::new(Vec::with_capacity(capacity))),
44 }
45 }
46}
47
48impl Write for SharedBuffer {
49 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
50 let mut buffer = self.buffer.try_lock().unwrap();
51 Write::write(&mut *buffer, buf)
52 }
53
54 fn flush(&mut self) -> std::io::Result<()> {
55 let mut buffer = self.buffer.try_lock().unwrap();
56 Write::flush(&mut *buffer)
57 }
58}
59
60/// A trait that defines the methods required for a RecordBatch serializer.
61pub trait BatchSerializer: Sync + Send {
62 /// Asynchronously serializes a `RecordBatch` and returns the serialized bytes.
63 /// Parameter `initial` signals whether the given batch is the first batch.
64 /// This distinction is important for certain serializers (like CSV).
65 fn serialize(&self, batch: RecordBatch, initial: bool) -> Result<Bytes>;
66}
67
68/// Converts table schema to writer schema, which may differ in the case
69/// of hive style partitioning where some columns are removed from the
70/// underlying files.
71pub fn get_writer_schema(config: &FileSinkConfig) -> Arc<Schema> {
72 if !config.table_partition_cols.is_empty() && !config.keep_partition_by_columns {
73 let schema = config.output_schema();
74 let partition_names: Vec<_> =
75 config.table_partition_cols.iter().map(|(s, _)| s).collect();
76 Arc::new(Schema::new_with_metadata(
77 schema
78 .fields()
79 .iter()
80 .filter(|f| !partition_names.contains(&f.name()))
81 .map(|f| (**f).clone())
82 .collect::<Vec<_>>(),
83 schema.metadata().clone(),
84 ))
85 } else {
86 Arc::clone(config.output_schema())
87 }
88}
89
90/// A builder for an [`AsyncWrite`] that writes to an object store location.
91///
92/// This can be used to specify file compression on the writer. The writer
93/// will have a default buffer size unless altered. The specific default size
94/// is chosen by [`BufWriter::new`].
95///
96/// We drop the `AbortableWrite` struct and the writer will not try to cleanup on failure.
97/// Users can configure automatic cleanup with their cloud provider.
98#[derive(Debug)]
99pub struct ObjectWriterBuilder {
100 /// Compression type for object writer.
101 file_compression_type: FileCompressionType,
102 /// Output path
103 location: Path,
104 /// The related store that handles the given path
105 object_store: Arc<dyn ObjectStore>,
106 /// The size of the buffer for the object writer.
107 buffer_size: Option<usize>,
108 /// The compression level for the object writer.
109 compression_level: Option<u32>,
110 /// Counts the number of bytes actually written.
111 bytes_written_counter: Option<Arc<AtomicU64>>,
112}
113
114impl ObjectWriterBuilder {
115 /// Create a new [`ObjectWriterBuilder`] for the specified path and compression type.
116 pub fn new(
117 file_compression_type: FileCompressionType,
118 location: &Path,
119 object_store: Arc<dyn ObjectStore>,
120 ) -> Self {
121 Self {
122 file_compression_type,
123 location: location.clone(),
124 object_store,
125 buffer_size: None,
126 compression_level: None,
127 bytes_written_counter: None,
128 }
129 }
130
131 /// Set buffer size in bytes for object writer.
132 ///
133 /// # Example
134 /// ```
135 /// # use datafusion_datasource::file_compression_type::FileCompressionType;
136 /// # use datafusion_datasource::write::ObjectWriterBuilder;
137 /// # use object_store::memory::InMemory;
138 /// # use object_store::path::Path;
139 /// # use std::sync::Arc;
140 /// # let compression_type = FileCompressionType::UNCOMPRESSED;
141 /// # let location = Path::from("/foo/bar");
142 /// # let object_store = Arc::new(InMemory::new());
143 /// let mut builder = ObjectWriterBuilder::new(compression_type, &location, object_store);
144 /// builder.set_buffer_size(Some(20 * 1024 * 1024)); //20 MiB
145 /// assert_eq!(
146 /// builder.get_buffer_size(),
147 /// Some(20 * 1024 * 1024),
148 /// "Internal error: Builder buffer size doesn't match"
149 /// );
150 /// ```
151 pub fn set_buffer_size(&mut self, buffer_size: Option<usize>) {
152 self.buffer_size = buffer_size;
153 }
154
155 /// Set buffer size in bytes for object writer, returning the builder.
156 ///
157 /// # Example
158 /// ```
159 /// # use datafusion_datasource::file_compression_type::FileCompressionType;
160 /// # use datafusion_datasource::write::ObjectWriterBuilder;
161 /// # use object_store::memory::InMemory;
162 /// # use object_store::path::Path;
163 /// # use std::sync::Arc;
164 /// # let compression_type = FileCompressionType::UNCOMPRESSED;
165 /// # let location = Path::from("/foo/bar");
166 /// # let object_store = Arc::new(InMemory::new());
167 /// let builder = ObjectWriterBuilder::new(compression_type, &location, object_store)
168 /// .with_buffer_size(Some(20 * 1024 * 1024)); //20 MiB
169 /// assert_eq!(
170 /// builder.get_buffer_size(),
171 /// Some(20 * 1024 * 1024),
172 /// "Internal error: Builder buffer size doesn't match"
173 /// );
174 /// ```
175 pub fn with_buffer_size(mut self, buffer_size: Option<usize>) -> Self {
176 self.buffer_size = buffer_size;
177 self
178 }
179
180 /// Currently specified buffer size in bytes.
181 pub fn get_buffer_size(&self) -> Option<usize> {
182 self.buffer_size
183 }
184
185 /// Set compression level for object writer.
186 pub fn set_compression_level(&mut self, compression_level: Option<u32>) {
187 self.compression_level = compression_level;
188 }
189
190 /// Set compression level for object writer, returning the builder.
191 pub fn with_compression_level(mut self, compression_level: Option<u32>) -> Self {
192 self.compression_level = compression_level;
193 self
194 }
195
196 /// Currently specified compression level.
197 pub fn get_compression_level(&self) -> Option<u32> {
198 self.compression_level
199 }
200
201 pub fn with_bytes_written_counter(mut self, counter: FileSize) -> Self {
202 self.bytes_written_counter = Some(counter);
203 self
204 }
205
206 /// Return a writer object that writes to the object store location.
207 ///
208 /// If a buffer size has not been set, the default buffer buffer size will
209 /// be used.
210 ///
211 /// # Errors
212 /// If there is an error applying the compression type.
213 pub fn build(self) -> Result<Box<dyn AsyncWrite + Send + Unpin>> {
214 let Self {
215 file_compression_type,
216 location,
217 object_store,
218 buffer_size,
219 compression_level,
220 bytes_written_counter,
221 } = self;
222
223 let buf_writer = match buffer_size {
224 Some(size) => BufWriter::with_capacity(object_store, location, size),
225 None => BufWriter::new(object_store, location),
226 };
227 if let Some(counter) = bytes_written_counter {
228 file_compression_type.convert_async_writer_with_level(
229 CountingWriter {
230 inner: buf_writer,
231 counter,
232 },
233 compression_level,
234 )
235 } else {
236 file_compression_type
237 .convert_async_writer_with_level(buf_writer, compression_level)
238 }
239 }
240}
241
242pin_project! {
243 /// [`AsyncWrite`] wrapper that counts the number of effectively written bytes
244 struct CountingWriter<W> {
245 #[pin]
246 inner: W,
247 counter: Arc<AtomicU64>,
248 }
249}
250
251impl<W: AsyncWrite> AsyncWrite for CountingWriter<W> {
252 fn poll_write(
253 self: Pin<&mut Self>,
254 cx: &mut Context<'_>,
255 buf: &[u8],
256 ) -> Poll<std::io::Result<usize>> {
257 let this = self.project();
258 Poll::Ready(ready!(this.inner.poll_write(cx, buf)).inspect(|count| {
259 this.counter.fetch_add((*count) as u64, Ordering::Relaxed);
260 }))
261 }
262
263 fn poll_flush(
264 self: Pin<&mut Self>,
265 cx: &mut Context<'_>,
266 ) -> Poll<std::io::Result<()>> {
267 self.project().inner.poll_flush(cx)
268 }
269
270 fn poll_shutdown(
271 self: Pin<&mut Self>,
272 cx: &mut Context<'_>,
273 ) -> Poll<std::io::Result<()>> {
274 self.project().inner.poll_shutdown(cx)
275 }
276
277 fn poll_write_vectored(
278 self: Pin<&mut Self>,
279 cx: &mut Context<'_>,
280 bufs: &[IoSlice<'_>],
281 ) -> Poll<std::io::Result<usize>> {
282 let this = self.project();
283 Poll::Ready(
284 ready!(this.inner.poll_write_vectored(cx, bufs)).inspect(|count| {
285 this.counter.fetch_add((*count) as u64, Ordering::Relaxed);
286 }),
287 )
288 }
289
290 fn is_write_vectored(&self) -> bool {
291 self.inner.is_write_vectored()
292 }
293}